From a83d68b562b19fba1f8836edc93eb76d9ca1ce25 Mon Sep 17 00:00:00 2001 From: Tarek Dakhran Date: Fri, 20 Nov 2026 19:55:44 +0100 Subject: [PATCH 001/401] metal : allow the norm chain in either operand of the fused MUL/ADD (#32300) Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-metal/ggml-metal-fusion.cpp | 10 ++++------ ggml/src/ggml-metal/ggml-metal-ops.cpp | 15 ++++++++------- tests/fusion/MTL.csv | 9 +++++---- tests/test-backend-ops.cpp | 15 +++++++++++---- 4 files changed, 28 insertions(+), 21 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-fusion.cpp b/ggml/src/ggml-metal/ggml-metal-fusion.cpp index 6766b4bd998f..7b55a301ea1f 100644 --- a/ggml/src/ggml-metal/ggml-metal-fusion.cpp +++ b/ggml/src/ggml-metal/ggml-metal-fusion.cpp @@ -135,17 +135,15 @@ static bool ggml_metal_fusion_check_norm( } for (int j = 1; j < (int) fusion->ops.size(); j++) { - // the fused MUL/ADD must read the previous node as src0 - if (nodes[j]->src[0] != nodes[j - 1]) { - return false; - } + // MUL/ADD are commutative, the previous node can be either operand + const ggml_tensor * src = nodes[j]->src[0] == nodes[j - 1] ? nodes[j]->src[1] : nodes[j]->src[0]; // the weight/bias must have the same row width as the norm input - if (nodes[j]->src[1]->ne[0] != nodes[0]->ne[0]) { + if (src->ne[0] != nodes[0]->ne[0]) { return false; } - if (!ggml_is_contiguous_rows(nodes[j]->src[1])) { + if (!ggml_is_contiguous_rows(src)) { return false; } diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 1ae7f3d5dcf9..a7a1ef61e9cf 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -4698,16 +4698,17 @@ int ggml_metal_op_norm(ggml_metal_op_t ctx, int idx) { for (int i = 1; i < n_fuse; i++) { const ggml_tensor * fn = ctx->node(idx + i); + const ggml_tensor * fs = fn->src[0] == ctx->node(idx + i - 1) ? fn->src[1] : fn->src[0]; - bid_fuse[i - 1] = ggml_metal_get_buffer_id(fn->src[1]); + bid_fuse[i - 1] = ggml_metal_get_buffer_id(fs); - args.nef1[i] = fn->src[1]->ne[1]; - args.nef2[i] = fn->src[1]->ne[2]; - args.nef3[i] = fn->src[1]->ne[3]; + args.nef1[i] = fs->ne[1]; + args.nef2[i] = fs->ne[2]; + args.nef3[i] = fs->ne[3]; - args.nbf1[i] = fn->src[1]->nb[1]; - args.nbf2[i] = fn->src[1]->nb[2]; - args.nbf3[i] = fn->src[1]->nb[3]; + args.nbf1[i] = fs->nb[1]; + args.nbf2[i] = fs->nb[2]; + args.nbf3[i] = fs->nb[3]; } if (debug_fusion > 1) { diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 295740c7cd3c..b939d6683e6d 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -63,7 +63,7 @@ deepseek4 ,0 ,any ,MUL+ADD , 8 deepseek4 ,0 ,any ,RMS_NORM+MUL , 20 deepseek4 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 4 deepseek41 ,0 ,any ,MUL+ADD , 12 -deepseek41 ,0 ,any ,RMS_NORM+MUL , 29 +deepseek41 ,0 ,any ,RMS_NORM+MUL , 31 deepseek41 ,0 ,any ,UNARY+SQRT+ADD+ARGSORT+GET_ROWS+SUM_ROWS+SCALE+DIV, 6 domynedge ,0 ,any ,RMS_NORM+MUL , 8 domynedge ,0 ,any ,RMS_NORM+MUL+ADD , 3 @@ -101,8 +101,8 @@ gemma2 ,0 ,any ,RMS_NORM+MUL , 5 gemma2 ,0 ,any ,RMS_NORM+MUL+ADD , 4 gemma3 ,0 ,any ,RMS_NORM+MUL , 9 gemma3 ,0 ,any ,RMS_NORM+MUL+ADD , 4 -gemma4 ,0 ,any ,RMS_NORM+MUL , 47 -gemma4 ,0 ,any ,RMS_NORM+MUL+ADD , 20 +gemma4 ,0 ,any ,RMS_NORM+MUL , 37 +gemma4 ,0 ,any ,RMS_NORM+MUL+ADD , 30 glm-dsa ,0 ,any ,ADD+ADD , 1 glm-dsa ,0 ,any ,MUL+ADD , 2 glm-dsa ,0 ,any ,NORM+MUL+ADD , 2 @@ -258,7 +258,8 @@ muse-glimmer ,0 ,any ,RMS_NORM+MUL , 10 muse-glimmer ,0 ,any ,RMS_NORM+MUL+ADD , 3 muse-spark ,0 ,prefill ,MUL+ADD , 2 muse-spark ,0 ,decode ,MUL+ADD , 4 -muse-spark ,0 ,any ,RMS_NORM+MUL , 14 +muse-spark ,0 ,any ,RMS_NORM+MUL , 11 +muse-spark ,0 ,any ,RMS_NORM+MUL+ADD , 3 muse-spark ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 nanbeige ,0 ,any ,RMS_NORM+MUL , 5 nemotron ,0 ,any ,NORM+MUL+ADD , 5 diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 42e356ae0617..11bfa42a9aa7 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -4135,6 +4135,7 @@ struct test_rms_norm_mul_add : public test_case { const bool weight_broadcast; const ggml_type type_w; // type of b and d, GGML_TYPE_COUNT -> same as a const ggml_type type_add; // type of c, GGML_TYPE_COUNT -> same as b + const bool swap; // the norm chain is the second operand of MUL and ADD std::string op_desc(ggml_tensor * t) override { GGML_UNUSED(t); @@ -4151,6 +4152,9 @@ struct test_rms_norm_mul_add : public test_case { if (type_add != GGML_TYPE_COUNT) { s += "," + VAR_TO_STR(type_add); } + if (swap) { + s += "," + VAR_TO_STR(swap); + } return s; } @@ -4158,9 +4162,10 @@ struct test_rms_norm_mul_add : public test_case { std::array ne = {64, 5, 4, 3}, float eps = 1e-6f, bool broadcast = false, bool multi_add = false, bool post_mul = false, bool alias_rms_input = false, bool weight_broadcast = false, ggml_type type_w = GGML_TYPE_COUNT, - ggml_type type_add = GGML_TYPE_COUNT) + ggml_type type_add = GGML_TYPE_COUNT, bool swap = false) : type(type), ne(ne), eps(eps), broadcast(broadcast), multi_add(multi_add), post_mul(post_mul), - alias_rms_input(alias_rms_input), weight_broadcast(weight_broadcast), type_w(type_w), type_add(type_add) {} + alias_rms_input(alias_rms_input), weight_broadcast(weight_broadcast), type_w(type_w), type_add(type_add), + swap(swap) {} ggml_tensor * build_graph(ggml_context * ctx) override { std::array broadcast_dims = {ne[0]*2, ne[1]*3, ne[2]*3, ne[3]*4}; @@ -4191,8 +4196,9 @@ struct test_rms_norm_mul_add : public test_case { if (multi_add) { a = ggml_add(ctx, ggml_add(ctx, a, b), c); } - ggml_tensor * mul = ggml_mul(ctx, ggml_rms_norm(ctx, a, eps), b); - ggml_tensor * out = alias_rms_input ? ggml_add_inplace(ctx, a, mul) : ggml_add(ctx, mul, c); + ggml_tensor * norm = ggml_rms_norm(ctx, a, eps); + ggml_tensor * mul = swap ? ggml_mul(ctx, b, norm) : ggml_mul(ctx, norm, b); + ggml_tensor * out = alias_rms_input ? ggml_add_inplace(ctx, a, mul) : swap ? ggml_add(ctx, c, mul) : ggml_add(ctx, mul, c); if (post_mul) { out = ggml_mul(ctx, out, d); } @@ -11771,6 +11777,7 @@ static std::vector> make_test_cases_eval() { for (uint32_t n : { 64, 1025 }) { test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, true)); + test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_F32, { n, 5, 4, 3 }, eps, false, false, false, false, false, GGML_TYPE_COUNT, GGML_TYPE_COUNT, true)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, false, false, false, false, false, GGML_TYPE_F32)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32)); test_cases.emplace_back(new test_rms_norm_mul_add(GGML_TYPE_BF16, { n, 5, 4, 3 }, eps, true, false, false, false, false, GGML_TYPE_F32, GGML_TYPE_BF16)); From 919794500475862f6768c353255469dc661cb734 Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Fri, 20 Nov 2026 20:54:57 +0100 Subject: [PATCH 002/401] convert: qwen3-asr: put "language ..." output into thinking block (#32571) * convert: qwen3-asr: put "language ..." output into thinking block * convert: qwen3-asr: read the chat template from models/templates The converter embedded its own copy of Qwen3-ASR.jinja. Read the bundled file instead, as the Kimi-K3 and Kokoro converters do, so the GGUF and test-chat share a single template. --------- Co-authored-by: Pascal --- conversion/qwen3vl.py | 7 +++++-- models/templates/Qwen3-ASR.jinja | 8 ++++++++ tests/test-chat.cpp | 22 ++++++++++++++++++++++ tools/server/server-task.cpp | 16 +++++++++++----- 4 files changed, 46 insertions(+), 7 deletions(-) create mode 100644 models/templates/Qwen3-ASR.jinja diff --git a/conversion/qwen3vl.py b/conversion/qwen3vl.py index 9458366b1001..c15959bc4078 100644 --- a/conversion/qwen3vl.py +++ b/conversion/qwen3vl.py @@ -2,6 +2,7 @@ import json +from pathlib import Path from typing import Any, Callable, Iterable, TYPE_CHECKING if TYPE_CHECKING: @@ -393,8 +394,10 @@ def set_gguf_parameters(self): def set_vocab(self): super().set_vocab() - # fix chat template, use correct chatml format - self.gguf_writer.add_chat_template("{% for message in messages %}{{'<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}") + # the model outputs "language ", the template renders the language prefix as reasoning_content + # so that the chat parser can separate it from the transcript + template_path = Path(__file__).parent.parent / "models" / "templates" / "Qwen3-ASR.jinja" + self.gguf_writer.add_chat_template(template_path.read_text(encoding="utf-8")) # correct BOS/EOS tokens with open(self.dir_model / "tokenizer_config.json", "r", encoding="utf-8") as f: tokenizer_config = json.load(f) diff --git a/models/templates/Qwen3-ASR.jinja b/models/templates/Qwen3-ASR.jinja new file mode 100644 index 000000000000..0342d9e7e8f4 --- /dev/null +++ b/models/templates/Qwen3-ASR.jinja @@ -0,0 +1,8 @@ +{%- for message in messages -%} +{{- '<|im_start|>' + message.role + '\n' -}} +{%- if message.role == 'assistant' and message.reasoning_content is defined and message.reasoning_content -%} +{{- message.reasoning_content + '' -}} +{%- endif -%} +{{- message.content + '<|im_end|>\n' -}} +{%- endfor -%} +{%- if add_generation_prompt -%}{{- '<|im_start|>assistant\n' -}}{%- endif -%} diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index efffae530d83..302ef319fa48 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -7006,6 +7006,28 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .run(); } + // Qwen3-ASR: "language ", the language prefix is delimiter-style reasoning + { + auto tst = peg_tester("models/templates/Qwen3-ASR.jinja", detailed_debug); + + tst.test("language EnglishAnd so, my fellow Americans, ask not.") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect(simple_assist_msg("And so, my fellow Americans, ask not.", "language English")) + .expect_reconstruction() + .run(); + + tst.test("language None") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect(simple_assist_msg("", "language None")) + .run(); + + // reasoning_format none keeps the raw output + tst.test("language EnglishHello") + .reasoning_format(COMMON_REASONING_FORMAT_NONE) + .expect_content("language EnglishHello") + .run(); + } + // Mistral Small 3.2 - FUNC_BRACKET_TAG format: [TOOL_CALLS]func_name[CALL_ID]id[ARGS]{...} { auto tst = peg_tester("models/templates/Mistral-Small-3.2-24B-Instruct-2506.jinja", detailed_debug); diff --git a/tools/server/server-task.cpp b/tools/server/server-task.cpp index 9b2ba5ac5ace..595e57ffb240 100644 --- a/tools/server/server-task.cpp +++ b/tools/server/server-task.cpp @@ -1327,11 +1327,17 @@ json server_task_result_cmpl_partial::to_json_oaicompat_resp() { } json server_task_result_cmpl_partial::to_json_oaicompat_asr() { - json event = json { - {"type", "transcript.text.delta"}, - {"delta", content.text}, - }; - return event; + // only the parsed content is the transcript, e.g. the "language XXX" prefix of Qwen3-ASR is reasoning + json events = json::array(); + for (const auto & diff : oaicompat_msg_diffs) { + if (!diff.content_delta.empty()) { + events.push_back({ + {"type", "transcript.text.delta"}, + {"delta", diff.content_delta}, + }); + } + } + return events; } json server_task_result_cmpl_partial::to_json_anthropic() { From b2e659ec24e2c44e860fac03f111593fddca6c88 Mon Sep 17 00:00:00 2001 From: Ravi Panchumarthy Date: Fri, 20 Nov 2026 13:51:49 -0800 Subject: [PATCH 003/401] ggml-openvino: update openvino CI runs triggers (#32593) * ci : run the OpenVINO GPU job only for OpenVINO changes The self-hosted OpenVINO GPU job ran for most PRs and every master push on a shared runner, so it queued for hours. - ci-self-hosted-openvino.yml (GPU): runs only for changes to ggml/src/ggml-openvino. - build-openvino.yml: keeps its triggers (OpenVINO changes on PRs, every source change pushed to master). The Linux job runs on a GitHub-hosted runner and tests the OpenVINO CPU device only. * address review comments * ci : limit the OpenVINO PR CMake trigger to ggml * ci : drop the OpenVINO Ubuntu job * ci : trigger OpenVINO PR runs on tests/CMakeLists.txt --- .github/workflows/build-openvino.yml | 55 ------------------- .github/workflows/ci-self-hosted-openvino.yml | 4 +- 2 files changed, 3 insertions(+), 56 deletions(-) diff --git a/.github/workflows/build-openvino.yml b/.github/workflows/build-openvino.yml index 009bde4e48fb..9e092b52be19 100644 --- a/.github/workflows/build-openvino.yml +++ b/.github/workflows/build-openvino.yml @@ -40,61 +40,6 @@ env: CTEST_EXCLUDE: "test-llama-archs|test-llama-context|test-fp8-kv" jobs: - ubuntu-24-openvino: - runs-on: [self-hosted, Linux, Intel, OpenVINO] - - env: - # Sync versions in build-openvino.yml, ci-self-hosted-openvino.yml, release.yml, release-publish.yml, build-cache.yml, .devops/openvino.Dockerfile, docs/backend/OPENVINO.md - OPENVINO_VERSION_MAJOR: "2026.4.1" - OPENVINO_VERSION_FULL: "2026.4.1.22982.07f9c262b05" - - steps: - - name: Clone - id: checkout - uses: actions/checkout@v6 - - - name: Dependencies - id: depends - run: | - sudo apt-get update - sudo apt-get install -y build-essential libssl-dev libtbb12 cmake ninja-build python3-pip - sudo apt-get install -y ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd - - - name: Setup OpenVINO Toolkit - uses: ./.github/actions/linux-setup-openvino - with: - path: ./openvino_toolkit - version_major: ${{ env.OPENVINO_VERSION_MAJOR }} - version_full: ${{ env.OPENVINO_VERSION_FULL }} - - - name: Install OpenVINO dependencies - run: | - cd ./openvino_toolkit - chmod +x ./install_dependencies/install_openvino_dependencies.sh - echo "Y" | sudo -E ./install_dependencies/install_openvino_dependencies.sh - - - name: Build - id: cmake_build - run: | - source ./openvino_toolkit/setupvars.sh - cmake -B build/ReleaseOV -G Ninja \ - -DCMAKE_BUILD_TYPE=Release \ - -DGGML_OPENVINO=ON - time cmake --build build/ReleaseOV --config Release --parallel - - - name: Test (CPU) - id: cmake_test_cpu - run: | - cd ${{ github.workspace }} - ctest --test-dir build/ReleaseOV -L main -E "${{ env.CTEST_EXCLUDE }}" --verbose --timeout 3000 - - - name: Test (GPU) - id: cmake_test_gpu - run: | - cd ${{ github.workspace }} - export GGML_OPENVINO_DEVICE=GPU - ctest --test-dir build/ReleaseOV -L main -E "${{ env.CTEST_EXCLUDE }}" --verbose --timeout 3000 - openvino-windows-2022: runs-on: windows-2022 diff --git a/.github/workflows/ci-self-hosted-openvino.yml b/.github/workflows/ci-self-hosted-openvino.yml index ef89f004de32..f2df28a42e8f 100644 --- a/.github/workflows/ci-self-hosted-openvino.yml +++ b/.github/workflows/ci-self-hosted-openvino.yml @@ -21,7 +21,9 @@ on: paths: [ '.github/workflows/ci-self-hosted-openvino.yml', 'ci/run.sh', - '**/CMakeLists.txt', + 'CMakeLists.txt', + 'ggml/CMakeLists.txt', + 'tests/CMakeLists.txt', '**/.cmake', 'ggml/src/*', 'ggml/src/ggml-cpu/**', From e3c3f666a4ca1ca9994adea6a2b7f72a9746482a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pelayo=20Garcia=20B=C3=A1rcena?= <40317024+PelaGB17@users.noreply.github.com> Date: Fri, 20 Nov 2026 22:52:19 +0100 Subject: [PATCH 004/401] hip: add RDNA1 MMVQ parameter table (1 warp per block for ncols=1) (#32389) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * hip: add RDNA1 MMVQ parameter table (1 warp per block for ncols=1) * hip: write the RDNA1 MMVQ values explicitly instead of recursing into the generic table * hip: list the RDNA1 MMVQ table before RDNA2 in the enum * Update ggml/src/ggml-cuda/mmvq.cu --------- Co-authored-by: Johannes Gäßler --- ggml/src/ggml-cuda/mmvq.cu | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 091fc3071561..6f10428e682b 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -93,6 +93,7 @@ enum mmvq_parameter_table_id { MMVQ_PARAMETERS_GENERIC = 0, MMVQ_PARAMETERS_TURING, MMVQ_PARAMETERS_GCN, + MMVQ_PARAMETERS_RDNA1, MMVQ_PARAMETERS_RDNA2, MMVQ_PARAMETERS_RDNA3_0, MMVQ_PARAMETERS_RDNA4, @@ -105,6 +106,8 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { return MMVQ_PARAMETERS_RDNA4; #elif defined(RDNA3_0) return MMVQ_PARAMETERS_RDNA3_0; +#elif defined(RDNA1) + return MMVQ_PARAMETERS_RDNA1; #elif defined(RDNA2) || defined(RDNA3_5) || defined(RDNA4_M) return MMVQ_PARAMETERS_RDNA2; #elif defined(GCN) || defined(CDNA) @@ -127,6 +130,9 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) { if (GGML_CUDA_CC_IS_RDNA3_0(cc)) { return MMVQ_PARAMETERS_RDNA3_0; } + if (GGML_CUDA_CC_IS_RDNA1(cc)) { + return MMVQ_PARAMETERS_RDNA1; + } if (GGML_CUDA_CC_IS_RDNA2(cc) || GGML_CUDA_CC_IS_RDNA3_5(cc) || GGML_CUDA_CC_IS_RDNA4_M(cc)) { return MMVQ_PARAMETERS_RDNA2; } @@ -538,6 +544,23 @@ static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_d } return 1; } + if (table_id == MMVQ_PARAMETERS_RDNA1) { + switch (ncols_dst) { + case 1: + return 1; + case 2: + case 3: + case 4: + return 4; + case 5: + case 6: + case 7: + case 8: + return 2; + default: + return 1; + } + } if (table_id == MMVQ_PARAMETERS_TURING) { if (ncols_dst == 1) { switch (type) { @@ -607,7 +630,7 @@ static constexpr __host__ __device__ bool mmvq_two_rows_ncols1(ggml_type type) { } static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int ncols_dst, int table_id, bool small_k = false, int nwarps = 1) { - if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10) { + if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) { switch (ncols_dst) { case 1: if (small_k) { @@ -616,7 +639,7 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int if (table_id == MMVQ_PARAMETERS_GB10) { return type == GGML_TYPE_IQ2_S || type == GGML_TYPE_IQ3_S ? 2 : 1; } - return table_id == MMVQ_PARAMETERS_GENERIC && mmvq_two_rows_ncols1(type) ? 2 : 1; + return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1; case 2: case 3: case 4: From 29b52d398b294509746ec0a3f28948a3107c0213 Mon Sep 17 00:00:00 2001 From: Pedro Cuenca Date: Fri, 20 Nov 2026 23:01:07 +0100 Subject: [PATCH 005/401] model : Inkling 2 Mini (#32694) * Conversion * Separate model_type * Add gate_rank to allow building from metadata while testing * Base model * Loop graph * Support the new is_varloop attribute * Adopt naming scheme from https://github.com/ggml-org/llama.cpp/pull/32588 * Rename to varying --- conversion/__init__.py | 3 + conversion/inkling2.py | 59 ++++++- gguf-py/gguf/constants.py | 84 ++++++++++ gguf-py/gguf/gguf_writer.py | 15 ++ gguf-py/gguf/tensor_mapping.py | 60 +++++++ src/llama-arch.cpp | 37 +++++ src/llama-arch.h | 19 +++ src/llama-model.cpp | 5 +- src/llama-quant.cpp | 5 +- src/models/inkling2-loop.cpp | 113 ++++++++++++++ src/models/inkling2.cpp | 278 +++++++++++++++++++-------------- src/models/models.h | 59 +++++++ tests/test-llama-archs.cpp | 17 +- 13 files changed, 631 insertions(+), 123 deletions(-) create mode 100644 src/models/inkling2-loop.cpp diff --git a/conversion/__init__.py b/conversion/__init__.py index 253a18fd48aa..8869b7252982 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -148,7 +148,9 @@ "HYV4ForCausalLM": "hy_v4", "IQuestCoderForCausalLM": "llama", "Inkling2ForCausalLM": "inkling2", + "Inkling2LoopForCausalLM": "inkling2", "Inkling2ForConditionalGeneration": "inkling2", + "Inkling2LoopForConditionalGeneration": "inkling2", "InternLM2ForCausalLM": "internlm", "InternLM3ForCausalLM": "internlm", "JAISLMHeadModel": "jais", @@ -389,6 +391,7 @@ "HunYuanVLForConditionalGeneration": "hunyuan", "Idefics3ForConditionalGeneration": "smolvlm", "Inkling2ForConditionalGeneration": "inkling2", + "Inkling2LoopForConditionalGeneration": "inkling2", "InternVisionModel": "internvl", "JanusForConditionalGeneration": "januspro", "KimiK25ForConditionalGeneration": "kimivl", diff --git a/conversion/inkling2.py b/conversion/inkling2.py index a8e8b892ed72..63e73a6d527f 100644 --- a/conversion/inkling2.py +++ b/conversion/inkling2.py @@ -69,7 +69,7 @@ def _is_inkling2(dir_model: Path) -> bool: if not (dir_model / "config.json").is_file(): return False with open(dir_model / "config.json", encoding="utf-8") as f: - return json.load(f).get("model_type") in ("inkling2", "inkling2_text") + return json.load(f).get("model_type") in ("inkling2", "inkling2_text", "inkling2_loop", "inkling2_loop_text") @ModelBase.register_hparams_loader(_is_inkling2) @@ -274,7 +274,62 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield from super().modify_tensors(data_torch, name, bid) -@ModelBase.register("Inkling2ForConditionalGeneration") +@ModelBase.register("Inkling2LoopForConditionalGeneration", "Inkling2LoopForCausalLM") +class Inkling2LoopModel(Inkling2Model): + model_arch = gguf.MODEL_ARCH.INKLING2_LOOP + + # raw checkpoint and transformers names of the cross-pass message queries + _query_kinds = { + "model.middle_cycle_cross_pass_queries": "q", + "model.middle_cycle_cross_pass_kv_queries": "kv", + "model.cross_pass_messages.queries": "q", + "model.cross_pass_messages.kv_queries": "kv", + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._queries: dict[str, Tensor] = {} + self.loop = self.hparams["loop_config"] + if set(self.loop) != {"core_start", "core_end", "num_passes", "gate_rank", "is_varloop"}: + raise ValueError(f"Inkling2Loop: unsupported loop_config keys {sorted(self.loop)}") + start, end, block = self.loop["core_start"], self.loop["core_end"], self.hparams["n_layers_per_attn_res_block"] + # a fixed loop needs at least 2 passes, a variable loop at least 1 + min_passes = 1 if self.loop["is_varloop"] else 2 + if not 0 < start < end <= self.block_count or start % block or end % block or self.loop["num_passes"] < min_passes or self.loop["gate_rank"] < 1: + raise ValueError(f"Inkling2Loop: invalid loop_config {self.loop}") + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_loop_start(self.loop["core_start"]) + self.gguf_writer.add_loop_end(self.loop["core_end"]) + self.gguf_writer.add_loop_count(self.loop["num_passes"]) + self.gguf_writer.add_loop_gate_rank(self.loop["gate_rank"]) + self.gguf_writer.add_loop_varying(self.loop["is_varloop"]) + + def tensor_force_quant(self, name: str, new_name: str, bid: int | None, n_dims: int) -> gguf.GGMLQuantizationType | bool: + # the reference does not quantize the loop tensors + if new_name.endswith(("loop_msg_query.weight", "_ctrl_down.weight", "_ctrl_gain.weight", "_ctrl_forget.weight")): + return gguf.GGMLQuantizationType.F32 + return super().tensor_force_quant(name, new_name, bid, n_dims) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + if name not in self._query_kinds: + yield from super().modify_tensors(data_torch, name, bid) + return + self._queries[self._query_kinds[name]] = data_torch + if len(self._queries) < 2: + return + q, kv = self._queries["q"], self._queries["kv"] + start = self.loop["core_start"] + if q.shape[0] != 2 * (self.loop["core_end"] - start) or kv.shape != q.shape: + raise ValueError(f"Inkling2Loop: cross-pass queries {tuple(q.shape)} and {tuple(kv.shape)} do not match the loop core") + # core layer start + i mixes its q, k, v and mlp messages with these four queries + for i in range(q.shape[0] // 2): + query = torch.stack([q[2 * i], kv[2 * i], kv[2 * i + 1], q[2 * i + 1]]) + yield self.format_tensor_name(gguf.MODEL_TENSOR.LOOP_MSG_QUERY, start + i, ".weight"), query + + +@ModelBase.register("Inkling2ForConditionalGeneration", "Inkling2LoopForConditionalGeneration") class Inkling2VisionModel(MmprojModel): def get_vision_config(self): config = self.global_config.get("vision_config") diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index f36566a815d9..cc0347bbacf2 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -326,6 +326,13 @@ class HRM: L_CYCLES = "{arch}.hrm.l_cycles" PREFIX_LM = "{arch}.hrm.prefix_lm" + class Loop: + START = "{arch}.loop.start" + END = "{arch}.loop.end" + COUNT = "{arch}.loop.count" + GATE_RANK = "{arch}.loop.gate_rank" + VARYING = "{arch}.loop.varying" + class Metis: PASS_COUNT = "{arch}.metis.pass_count" MEMORY_LENGTH = "{arch}.metis.memory_length" @@ -778,6 +785,7 @@ class MODEL_ARCH(IntEnum): KOLIBRI1 = auto() LIMITE = auto() INKLING2 = auto() + INKLING2_LOOP = auto() DOMYN_EDGE = auto() @@ -880,6 +888,19 @@ class MODEL_TENSOR(IntEnum): MOE_LATENT_UP = auto() # nemotron 3 super FFN_POST_CONV = auto() FFN_RES_QUERY = auto() + LOOP_MSG_QUERY = auto() + LOOP_Q_CTRL_DOWN = auto() + LOOP_Q_CTRL_GAIN = auto() + LOOP_Q_CTRL_FORGET = auto() + LOOP_K_CTRL_DOWN = auto() + LOOP_K_CTRL_GAIN = auto() + LOOP_K_CTRL_FORGET = auto() + LOOP_V_CTRL_DOWN = auto() + LOOP_V_CTRL_GAIN = auto() + LOOP_V_CTRL_FORGET = auto() + LOOP_FFN_CTRL_DOWN = auto() + LOOP_FFN_CTRL_GAIN = auto() + LOOP_FFN_CTRL_FORGET = auto() STREAM_EMBD = auto() DEPTH_MEM_STATE_WRITE = auto() DEPTH_MEM_META_WRITE = auto() @@ -1779,6 +1800,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.KOLIBRI1: "kolibri1", MODEL_ARCH.LIMITE: "limite", MODEL_ARCH.INKLING2: "inkling2", + MODEL_ARCH.INKLING2_LOOP: "inkling2_loop", MODEL_ARCH.DOMYN_EDGE: "domynedge", } @@ -1881,6 +1903,19 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.MOE_LATENT_UP: "blk.{bid}.ffn_latent_up", # nemotron 3 super MODEL_TENSOR.FFN_POST_CONV: "blk.{bid}.ffn_post_conv", MODEL_TENSOR.FFN_RES_QUERY: "blk.{bid}.ffn_res_query", + MODEL_TENSOR.LOOP_MSG_QUERY: "blk.{bid}.loop_msg_query", + MODEL_TENSOR.LOOP_Q_CTRL_DOWN: "blk.{bid}.loop_q_ctrl_down", + MODEL_TENSOR.LOOP_Q_CTRL_GAIN: "blk.{bid}.loop_q_ctrl_gain", + MODEL_TENSOR.LOOP_Q_CTRL_FORGET: "blk.{bid}.loop_q_ctrl_forget", + MODEL_TENSOR.LOOP_K_CTRL_DOWN: "blk.{bid}.loop_k_ctrl_down", + MODEL_TENSOR.LOOP_K_CTRL_GAIN: "blk.{bid}.loop_k_ctrl_gain", + MODEL_TENSOR.LOOP_K_CTRL_FORGET: "blk.{bid}.loop_k_ctrl_forget", + MODEL_TENSOR.LOOP_V_CTRL_DOWN: "blk.{bid}.loop_v_ctrl_down", + MODEL_TENSOR.LOOP_V_CTRL_GAIN: "blk.{bid}.loop_v_ctrl_gain", + MODEL_TENSOR.LOOP_V_CTRL_FORGET: "blk.{bid}.loop_v_ctrl_forget", + MODEL_TENSOR.LOOP_FFN_CTRL_DOWN: "blk.{bid}.loop_ffn_ctrl_down", + MODEL_TENSOR.LOOP_FFN_CTRL_GAIN: "blk.{bid}.loop_ffn_ctrl_gain", + MODEL_TENSOR.LOOP_FFN_CTRL_FORGET: "blk.{bid}.loop_ffn_ctrl_forget", MODEL_TENSOR.STREAM_EMBD: "stream_embd", MODEL_TENSOR.DEPTH_MEM_STATE_WRITE: "depth_mem_state_write", MODEL_TENSOR.DEPTH_MEM_META_WRITE: "depth_mem_meta_write", @@ -7087,6 +7122,55 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_POST_CONV, MODEL_TENSOR.FFN_RES_QUERY, ], + MODEL_ARCH.INKLING2_LOOP: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.TOKEN_EMBD_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT_RES_QUERY, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_GATE, + MODEL_TENSOR.ATTN_REL, + MODEL_TENSOR.ATTN_REL_BIAS, + MODEL_TENSOR.ATTN_Q_CLIP, + MODEL_TENSOR.ATTN_REL_CLIP, + MODEL_TENSOR.ATTN_SINK_PROJ, + MODEL_TENSOR.ATTN_Q_INP_NORM, + MODEL_TENSOR.ATTN_K_INP_NORM, + MODEL_TENSOR.ATTN_V_INP_NORM, + MODEL_TENSOR.ATTN_K_CONV, + MODEL_TENSOR.ATTN_V_CONV, + MODEL_TENSOR.ATTN_K_CONV_PROJ, + MODEL_TENSOR.ATTN_V_CONV_PROJ, + MODEL_TENSOR.ATTN_POST_CONV, + MODEL_TENSOR.ATTN_RES_QUERY, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_EXP_PROBS_B, + MODEL_TENSOR.FFN_GATE_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_UP_EXP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_POST_CONV, + MODEL_TENSOR.FFN_RES_QUERY, + MODEL_TENSOR.LOOP_MSG_QUERY, + MODEL_TENSOR.LOOP_Q_CTRL_DOWN, + MODEL_TENSOR.LOOP_Q_CTRL_GAIN, + MODEL_TENSOR.LOOP_Q_CTRL_FORGET, + MODEL_TENSOR.LOOP_K_CTRL_DOWN, + MODEL_TENSOR.LOOP_K_CTRL_GAIN, + MODEL_TENSOR.LOOP_K_CTRL_FORGET, + MODEL_TENSOR.LOOP_V_CTRL_DOWN, + MODEL_TENSOR.LOOP_V_CTRL_GAIN, + MODEL_TENSOR.LOOP_V_CTRL_FORGET, + MODEL_TENSOR.LOOP_FFN_CTRL_DOWN, + MODEL_TENSOR.LOOP_FFN_CTRL_GAIN, + MODEL_TENSOR.LOOP_FFN_CTRL_FORGET, + ], MODEL_ARCH.DOMYN_EDGE: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.ATTN_Q, diff --git a/gguf-py/gguf/gguf_writer.py b/gguf-py/gguf/gguf_writer.py index eb0bd91d0049..08c8d2f33c15 100644 --- a/gguf-py/gguf/gguf_writer.py +++ b/gguf-py/gguf/gguf_writer.py @@ -990,6 +990,21 @@ def add_hrm_l_cycles(self, value: int) -> None: def add_hrm_prefix_lm(self, value: bool) -> None: self.add_bool(Keys.HRM.PREFIX_LM.format(arch=self.arch), value) + def add_loop_start(self, value: int) -> None: + self.add_uint32(Keys.Loop.START.format(arch=self.arch), value) + + def add_loop_end(self, value: int) -> None: + self.add_uint32(Keys.Loop.END.format(arch=self.arch), value) + + def add_loop_count(self, value: int) -> None: + self.add_uint32(Keys.Loop.COUNT.format(arch=self.arch), value) + + def add_loop_gate_rank(self, value: int) -> None: + self.add_uint32(Keys.Loop.GATE_RANK.format(arch=self.arch), value) + + def add_loop_varying(self, value: bool) -> None: + self.add_bool(Keys.Loop.VARYING.format(arch=self.arch), value) + def add_metis_pass_count(self, value: int) -> None: self.add_uint32(Keys.Metis.PASS_COUNT.format(arch=self.arch), value) diff --git a/gguf-py/gguf/tensor_mapping.py b/gguf-py/gguf/tensor_mapping.py index d48d46b9a307..c0bbfde2298d 100644 --- a/gguf-py/gguf/tensor_mapping.py +++ b/gguf-py/gguf/tensor_mapping.py @@ -543,6 +543,66 @@ class TensorNameMap: "model.layers.{bid}.attention_input.query", # inkling2 ), + MODEL_TENSOR.LOOP_Q_CTRL_DOWN: ( + "model.layers.{bid}.q_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.attn.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_Q_CTRL_GAIN: ( + "model.layers.{bid}.q_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.attn.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_Q_CTRL_FORGET: ( + "model.layers.{bid}.q_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.attn.forget_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_K_CTRL_DOWN: ( + "model.layers.{bid}.k_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.k.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_K_CTRL_GAIN: ( + "model.layers.{bid}.k_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.k.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_K_CTRL_FORGET: ( + "model.layers.{bid}.k_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.k.forget_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_V_CTRL_DOWN: ( + "model.layers.{bid}.v_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.v.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_V_CTRL_GAIN: ( + "model.layers.{bid}.v_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.v.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_V_CTRL_FORGET: ( + "model.layers.{bid}.v_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.v.forget_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_FFN_CTRL_DOWN: ( + "model.layers.{bid}.mlp_controller.down_proj", # inkling2_loop + "model.layers.{bid}.controllers.mlp.down_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_FFN_CTRL_GAIN: ( + "model.layers.{bid}.mlp_controller.gain_proj", # inkling2_loop + "model.layers.{bid}.controllers.mlp.gain_weight", # inkling2_loop + ), + + MODEL_TENSOR.LOOP_FFN_CTRL_FORGET: ( + "model.layers.{bid}.mlp_controller.forget_proj", # inkling2_loop + "model.layers.{bid}.controllers.mlp.forget_weight", # inkling2_loop + ), + # Feed-forward norm MODEL_TENSOR.FFN_NORM: ( "layers.{bid}.moe_connection.norm", # metis16 diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 1c90b2180bfd..3cda4f7fb725 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -184,6 +184,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_KOLIBRI1, "kolibri1" }, { LLM_ARCH_RICURSIVE, "ricursive" }, { LLM_ARCH_INKLING2, "inkling2" }, + { LLM_ARCH_INKLING2_LOOP, "inkling2_loop" }, { LLM_ARCH_DOMYN_EDGE, "domynedge" }, { LLM_ARCH_UNKNOWN, "(unknown)" }, }; @@ -285,6 +286,11 @@ static const std::map LLM_KV_NAMES = { { LLM_KV_HRM_H_CYCLES, "%s.hrm.h_cycles" }, { LLM_KV_HRM_L_CYCLES, "%s.hrm.l_cycles" }, { LLM_KV_HRM_PREFIX_LM, "%s.hrm.prefix_lm" }, + { LLM_KV_LOOP_START, "%s.loop.start" }, + { LLM_KV_LOOP_END, "%s.loop.end" }, + { LLM_KV_LOOP_COUNT, "%s.loop.count" }, + { LLM_KV_LOOP_GATE_RANK, "%s.loop.gate_rank" }, + { LLM_KV_LOOP_VARYING, "%s.loop.varying" }, { LLM_KV_METIS_PASS_COUNT, "%s.metis.pass_count" }, { LLM_KV_METIS_MEMORY_LENGTH, "%s.metis.memory_length" }, { LLM_KV_METIS_ROUTE_LENGTH, "%s.metis.route_length" }, @@ -591,6 +597,19 @@ static const std::map LLM_TENSOR_NAMES = { { LLM_TENSOR_FFN_LATENT_UP, "blk.%d.ffn_latent_up" }, { LLM_TENSOR_FFN_POST_CONV, "blk.%d.ffn_post_conv" }, { LLM_TENSOR_FFN_RES_QUERY, "blk.%d.ffn_res_query" }, + { LLM_TENSOR_LOOP_MSG_QUERY, "blk.%d.loop_msg_query" }, + { LLM_TENSOR_LOOP_Q_CTRL_DOWN, "blk.%d.loop_q_ctrl_down" }, + { LLM_TENSOR_LOOP_Q_CTRL_GAIN, "blk.%d.loop_q_ctrl_gain" }, + { LLM_TENSOR_LOOP_Q_CTRL_FORGET, "blk.%d.loop_q_ctrl_forget" }, + { LLM_TENSOR_LOOP_K_CTRL_DOWN, "blk.%d.loop_k_ctrl_down" }, + { LLM_TENSOR_LOOP_K_CTRL_GAIN, "blk.%d.loop_k_ctrl_gain" }, + { LLM_TENSOR_LOOP_K_CTRL_FORGET, "blk.%d.loop_k_ctrl_forget" }, + { LLM_TENSOR_LOOP_V_CTRL_DOWN, "blk.%d.loop_v_ctrl_down" }, + { LLM_TENSOR_LOOP_V_CTRL_GAIN, "blk.%d.loop_v_ctrl_gain" }, + { LLM_TENSOR_LOOP_V_CTRL_FORGET, "blk.%d.loop_v_ctrl_forget" }, + { LLM_TENSOR_LOOP_FFN_CTRL_DOWN, "blk.%d.loop_ffn_ctrl_down" }, + { LLM_TENSOR_LOOP_FFN_CTRL_GAIN, "blk.%d.loop_ffn_ctrl_gain" }, + { LLM_TENSOR_LOOP_FFN_CTRL_FORGET, "blk.%d.loop_ffn_ctrl_forget" }, { LLM_TENSOR_STREAM_EMBD, "stream_embd" }, { LLM_TENSOR_DEPTH_MEM_STATE_WRITE, "depth_mem_state_write" }, { LLM_TENSOR_DEPTH_MEM_META_WRITE, "depth_mem_meta_write" }, @@ -1262,6 +1281,19 @@ static const std::map LLM_TENSOR_INFOS = { {LLM_TENSOR_FFN_LATENT_UP, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_FFN_POST_CONV, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_SSM_CONV}}, {LLM_TENSOR_FFN_RES_QUERY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_MSG_QUERY, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_Q_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_Q_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_Q_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_K_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_K_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_K_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_V_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_V_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_V_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_FFN_CTRL_DOWN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_FFN_CTRL_GAIN, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, + {LLM_TENSOR_LOOP_FFN_CTRL_FORGET, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}}, {LLM_TENSOR_STREAM_EMBD, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_ADD}}, {LLM_TENSOR_DEPTH_MEM_STATE_WRITE, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, {LLM_TENSOR_DEPTH_MEM_META_WRITE, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_MUL_MAT}}, @@ -1448,6 +1480,7 @@ bool llm_arch_is_hybrid(const llm_arch & arch) { case LLM_ARCH_MINIMAX_01: case LLM_ARCH_ZONOS3: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return true; default: return false; @@ -1484,6 +1517,7 @@ bool llm_arch_supports_rs_rollback(const llm_arch & arch) { case LLM_ARCH_LFM3: case LLM_ARCH_BAILINGMOE3: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return true; default: return false; @@ -1502,6 +1536,7 @@ bool llm_arch_supports_mixed_batch(const llm_arch & arch) { case LLM_ARCH_GEMMA4_ASSISTANT: case LLM_ARCH_LIMITE: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return false; default: return true; @@ -1522,6 +1557,7 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { case LLM_ARCH_JAMBA: case LLM_ARCH_FALCON_H1: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: case LLM_ARCH_OLMO2: case LLM_ARCH_OLMOE: case LLM_ARCH_DEEPSEEK2: @@ -1564,6 +1600,7 @@ bool llama_arch_supports_save(llm_arch arch) { case LLM_ARCH_APERTUS: case LLM_ARCH_STEP35: case LLM_ARCH_CLEF: // the head tensors are not saved + case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load case LLM_ARCH_VLLM_DECISION2: return false; default: diff --git a/src/llama-arch.h b/src/llama-arch.h index a8c0fdf098fd..1ac22ecee67c 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -188,6 +188,7 @@ enum llm_arch { LLM_ARCH_LIMITE, LLM_ARCH_RICURSIVE, LLM_ARCH_INKLING2, + LLM_ARCH_INKLING2_LOOP, LLM_ARCH_DOMYN_EDGE, LLM_ARCH_UNKNOWN, }; @@ -289,6 +290,11 @@ enum llm_kv { LLM_KV_HRM_H_CYCLES, LLM_KV_HRM_L_CYCLES, LLM_KV_HRM_PREFIX_LM, + LLM_KV_LOOP_START, + LLM_KV_LOOP_END, + LLM_KV_LOOP_COUNT, + LLM_KV_LOOP_GATE_RANK, + LLM_KV_LOOP_VARYING, LLM_KV_METIS_PASS_COUNT, LLM_KV_METIS_MEMORY_LENGTH, LLM_KV_METIS_ROUTE_LENGTH, @@ -610,6 +616,19 @@ enum llm_tensor { LLM_TENSOR_FFN_LATENT_UP, LLM_TENSOR_FFN_POST_CONV, LLM_TENSOR_FFN_RES_QUERY, + LLM_TENSOR_LOOP_MSG_QUERY, + LLM_TENSOR_LOOP_Q_CTRL_DOWN, + LLM_TENSOR_LOOP_Q_CTRL_GAIN, + LLM_TENSOR_LOOP_Q_CTRL_FORGET, + LLM_TENSOR_LOOP_K_CTRL_DOWN, + LLM_TENSOR_LOOP_K_CTRL_GAIN, + LLM_TENSOR_LOOP_K_CTRL_FORGET, + LLM_TENSOR_LOOP_V_CTRL_DOWN, + LLM_TENSOR_LOOP_V_CTRL_GAIN, + LLM_TENSOR_LOOP_V_CTRL_FORGET, + LLM_TENSOR_LOOP_FFN_CTRL_DOWN, + LLM_TENSOR_LOOP_FFN_CTRL_GAIN, + LLM_TENSOR_LOOP_FFN_CTRL_FORGET, LLM_TENSOR_STREAM_EMBD, LLM_TENSOR_DEPTH_MEM_STATE_WRITE, LLM_TENSOR_DEPTH_MEM_META_WRITE, diff --git a/src/llama-model.cpp b/src/llama-model.cpp index ec0820a07c0a..4c77f6f68f70 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -326,6 +326,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_falcon_h1(params); case LLM_ARCH_INKLING2: return new llama_model_inkling2(params); + case LLM_ARCH_INKLING2_LOOP: + return new llama_model_inkling2_loop(params); case LLM_ARCH_LFM2: return new llama_model_lfm2(params); case LLM_ARCH_LFM2MOE: @@ -3359,7 +3361,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, filter_idx = [&](uint32_t il) { return il < hparams.n_layer() && !hparams.is_recr(il) && hparams.is_indexer_full(il); }; - } else if (arch == LLM_ARCH_FALCON_H1 || arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_ZAYA1) { + } else if (arch == LLM_ARCH_FALCON_H1 || arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP || arch == LLM_ARCH_ZAYA1) { filter_attn = [&](uint32_t) { return true; }; filter_recr = [&](uint32_t) { return true; }; } else if (arch == LLM_ARCH_NEMOTRON_H || arch == LLM_ARCH_NEMOTRON_H_MOE) { @@ -3735,6 +3737,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_GLM5_NEXT: case LLM_ARCH_STARCODER: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: case LLM_ARCH_KOKORO: return LLAMA_ROPE_TYPE_NONE; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 79d964972831..0515756dcee9 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -340,12 +340,13 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= name.find("mudd_") == std::string::npos; } - // inkling2: short conv kernels, clip scales, residual mix queries and the relative bias projection - if (arch == LLM_ARCH_INKLING2) { + // inkling2: short conv kernels, clip scales, residual mix queries, the relative bias projection and the loop tensors + if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) { quantize &= name.find("_conv.weight") == std::string::npos; quantize &= name.find("_clip.weight") == std::string::npos; quantize &= name.find("_res_query.weight") == std::string::npos; quantize &= name.find("attn_rel_bias.weight") == std::string::npos; + quantize &= name.find(".loop_") == std::string::npos; } // zaya1: the top-1 router and the grouped conv kernels stay F32 diff --git a/src/models/inkling2-loop.cpp b/src/models/inkling2-loop.cpp new file mode 100644 index 000000000000..0de66baeec3c --- /dev/null +++ b/src/models/inkling2-loop.cpp @@ -0,0 +1,113 @@ +#include "models.h" + +int llama_model_inkling2_loop::layer_phys(int il) const { + return il < n_phys ? il : core_start + (il - n_phys) % (core_end - core_start); +} + +void llama_model_inkling2_loop::load_arch_hparams(llama_model_loader & ml) { + llama_model_inkling2::load_arch_hparams(ml); + + ml.get_key(LLM_KV_LOOP_START, core_start); + ml.get_key(LLM_KV_LOOP_END, core_end); + ml.get_key(LLM_KV_LOOP_COUNT, n_passes); + ml.get_key(LLM_KV_LOOP_GATE_RANK, gate_rank); + ml.get_key(LLM_KV_LOOP_VARYING, varying, false); + + n_phys = hparams.n_layer(); + const uint32_t block = hparams.attn_res_block_size; + // a fixed loop needs at least 2 passes, a variable loop at least 1 + if (n_passes < (varying ? 1u : 2u) || !gate_rank || !core_start || core_start >= core_end || core_end > (uint32_t) n_phys || + core_start % block || core_end % block || hparams.n_layer_nextn) { + throw std::runtime_error(format("inkling2_loop: invalid loop core [%u, %u) with block size %u, %u passes or gate rank %u for %d layers", + core_start, core_end, block, n_passes, gate_rank, n_phys)); + } + const size_t n_slot = n_phys + (size_t) (n_passes - 1)*(core_end - core_start); + if (n_slot > LLAMA_MAX_LAYERS) { + throw std::runtime_error(format("inkling2_loop: %zu cache slots exceed the maximum of %d", n_slot, LLAMA_MAX_LAYERS)); + } + + // expand to the cache slots before load_tensors() allocates the layers and the memory + hparams.n_layer_all = n_slot; + for (int il = n_phys; il < (int) n_slot; ++il) { + const int p = layer_phys(il); + hparams.n_head_arr[il] = hparams.n_head_arr[p]; + hparams.n_head_kv_arr[il] = hparams.n_head_kv_arr[p]; + hparams.n_ff_arr[il] = hparams.n_ff_arr[p]; + hparams.n_ff_exp_arr[il] = hparams.n_ff_exp_arr[p]; + hparams.n_expert_used_arr[il] = hparams.n_expert_used_arr[p]; + hparams.is_swa_impl[il] = hparams.is_swa_impl[p]; + hparams.is_recr_impl[il] = hparams.is_recr_impl[p]; + } +} + +void llama_model_inkling2_loop::load_arch_tensors(llama_model_loader & ml) { + llama_model_inkling2::load_arch_tensors(ml); + + const int64_t n_embd = hparams.n_embd; + const int64_t rank = gate_rank; + const llm_tensor down[LOOP_CTRL_COUNT] = { LLM_TENSOR_LOOP_Q_CTRL_DOWN, LLM_TENSOR_LOOP_K_CTRL_DOWN, LLM_TENSOR_LOOP_V_CTRL_DOWN, LLM_TENSOR_LOOP_FFN_CTRL_DOWN }; + const llm_tensor gain[LOOP_CTRL_COUNT] = { LLM_TENSOR_LOOP_Q_CTRL_GAIN, LLM_TENSOR_LOOP_K_CTRL_GAIN, LLM_TENSOR_LOOP_V_CTRL_GAIN, LLM_TENSOR_LOOP_FFN_CTRL_GAIN }; + const llm_tensor forget[LOOP_CTRL_COUNT] = { LLM_TENSOR_LOOP_Q_CTRL_FORGET, LLM_TENSOR_LOOP_K_CTRL_FORGET, LLM_TENSOR_LOOP_V_CTRL_FORGET, LLM_TENSOR_LOOP_FFN_CTRL_FORGET }; + + loop_layers.resize(core_end - core_start); + for (uint32_t il = core_start; il < core_end; ++il) { + auto & l = loop_layers[il - core_start]; + // the q, k, v and ffn message queries + l.msg_query = create_tensor(tn(LLM_TENSOR_LOOP_MSG_QUERY, "weight", il), {n_embd, LOOP_CTRL_COUNT}, 0); + for (int c = 0; c < LOOP_CTRL_COUNT; ++c) { + l.ctrl_down[c] = create_tensor(tn(down[c], "weight", il), {2*n_embd, rank}, 0); + l.ctrl_gain[c] = create_tensor(tn(gain[c], "weight", il), {rank, n_embd}, 0); + l.ctrl_forget[c] = create_tensor(tn(forget[c], "weight", il), {rank, n_embd}, 0); + } + } + + // share the physical weights, each cache slot keeps its own KV and conv state + for (int il = n_phys; il < (int) hparams.n_layer(); ++il) { + layers[il] = layers[layer_phys(il)]; + } +} + +std::unique_ptr llama_model_inkling2_loop::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +llama_model_inkling2_loop::graph::graph(const llm_graph_params & params) : llama_model_inkling2::graph(params, no_build{}) { + const auto & m = static_cast(model); + const int start = m.core_start; + const int end = m.core_end; + + auto * cur = build_inputs(); + std::vector blocks; + for (int il = 0; il < start; ++il) { + cur = build_layer(il, il, cur, blocks); + } + + // every pass starts from the prelude output + auto * prelude = cur; + const auto prelude_blocks = blocks; + for (uint32_t pass = 0; pass < m.n_passes; ++pass) { + // the bank of the previous pass: its blocks after the first core block, and its output + std::vector bank; + ggml_tensor * bank_out = nullptr; + if (pass > 0) { + bank.assign(blocks.begin() + prelude_blocks.size() + 1, blocks.end()); + bank_out = cur; + cur = prelude; + blocks = prelude_blocks; + } + for (int ip = start; ip < end; ++ip) { + const int il = pass == 0 ? ip : m.n_phys + (pass - 1)*(end - start) + (ip - start); + if (pass == 0) { + cur = build_layer(il, ip, cur, blocks); + continue; + } + const auto & loop = m.loop_layers[ip - start]; + cur = build_layer(il, ip, cur, blocks, mix(bank, bank_out, loop.msg_query), &loop); + } + } + + for (int il = end; il < m.n_phys; ++il) { + cur = build_layer(il, il, cur, blocks); + } + build_output(cur, blocks); +} diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index ca25c1d53501..3e43ef4184ea 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -100,7 +100,7 @@ void llama_model_inkling2::load_arch_tensors(llama_model_loader &) { output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); output_res_query = create_tensor(tn(LLM_TENSOR_OUTPUT_RES_QUERY, "weight"), {n_embd}, 0); - for (int i = 0; i < n_layer; ++i) { + for (int i = 0; i < n_layer_phys(); ++i) { auto & layer = layers[i]; const int64_t n_head = hparams.n_head(i); @@ -236,16 +236,27 @@ ggml_tensor * llama_model_inkling2::graph::convolve( return ggml_scale(ctx0, ggml_add(ctx0, cur, out), 1.0f/sqrtf((dynamic ? 2 : 1)*n_conv + 1)); } -llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { - auto * inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); - auto * attn = inp->get_attn(); - auto * recr = inp->get_recr(); +// mix a cross-pass message into a looped layer input: (1 - forget)*cur + gain*message, both gated on cur and message +ggml_tensor * llama_model_inkling2::graph::control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl) { + ggml_tensor * gate = ggml_concat(ctx0, ggml_rms_norm(ctx0, cur, 1e-6f), ggml_rms_norm(ctx0, message, 1e-6f), 0); + gate = build_lora_mm(loop.ctrl_down[ctrl], gate); + + ggml_tensor * gain = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_gain[ctrl], gate)); + ggml_tensor * forget = ggml_tanh(ctx0, build_lora_mm(loop.ctrl_forget[ctrl], gate)); + + return ggml_add(ctx0, ggml_sub(ctx0, cur, ggml_mul(ctx0, forget, cur)), ggml_mul(ctx0, gain, message)); +} + +ggml_tensor * llama_model_inkling2::graph::build_inputs() { + inp = build_inp_mem_hybrid_iswa_rel(hparams.n_relative_extent, hparams.n_swa); + attn = inp->get_attn(); + recr = inp->get_recr(); - ggml_tensor * inp_pos = build_inp_pos(); - ggml_tensor * inp_out_ids = build_inp_out_ids(); + ggml_tensor * inp_pos = build_inp_pos(); + inp_out_ids = build_inp_out_ids(); // log-scaled positions: 1 + alpha*log(max(1, (pos + 1)/floor)), multiplies q and r of the full-attention layers - ggml_tensor * tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, inp_pos, GGML_TYPE_F32), 1.0f, 1.0f); + tau = ggml_scale_bias(ctx0, ggml_cast(ctx0, inp_pos, GGML_TYPE_F32), 1.0f, 1.0f); tau = ggml_log(ctx0, ggml_clamp(ctx0, ggml_scale(ctx0, tau, 1.0f/hparams.n_log_scale_floor), 1.0f, INFINITY)); tau = ggml_reshape_3d(ctx0, ggml_scale_bias(ctx0, tau, hparams.f_log_scale_alpha, 1.0f), 1, 1, n_tokens); @@ -256,134 +267,160 @@ llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_ cur = build_norm(cur, model.tok_norm, nullptr, LLM_NORM_RMS, -1); } - std::vector blocks; + return cur; +} - for (int il = 0; il < n_layer; ++il) { - const auto & layer = model.layers[il]; - - const bool is_swa = hparams.is_swa(il); - const int64_t n_head = hparams.n_head(il); - const int64_t n_head_kv = hparams.n_head_kv(il); - const int64_t n_embd_head = hparams.n_embd_head_k(il); - const int64_t n_embd_k_gqa = n_embd_head*n_head_kv; - - ggml_tensor * state = recr->mctx->get_r_l(il); - ggml_tensor * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); - history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); - - ggml_tensor * inpSA = cur; - - // attention inputs: SWA layers mix one, full-attention layers one each for Q, K and V - ggml_tensor * inputs[3] = {cur, cur, cur}; - if (layer.attn_res_query) { - ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); - for (int j = 0; j < 3; ++j) { - inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (is_swa ? 0 : j)*mixed->nb[1])); - } - } +ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tensor * cur, std::vector & blocks, + ggml_tensor * messages, const loop_layer * loop) { + GGML_ASSERT(!messages == !loop); - if (is_swa) { - inputs[0] = build_norm(inputs[0], layer.attn_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = inputs[2] = inputs[0]; - } else { - inputs[0] = build_norm(inputs[0], layer.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[1] = build_norm(inputs[1], layer.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); - inputs[2] = build_norm(inputs[2], layer.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); + const auto & layer = model.layers[il]; + + const bool is_swa = hparams.is_swa(il); + const int64_t n_head = hparams.n_head(il); + const int64_t n_head_kv = hparams.n_head_kv(il); + const int64_t n_embd_head = hparams.n_embd_head_k(il); + const int64_t n_embd_k_gqa = n_embd_head*n_head_kv; + + // the message of controller ctrl, [n_embd, n_tokens] + auto message = [&](int ctrl) { + return ggml_cont(ctx0, ggml_view_2d(ctx0, messages, n_embd, n_tokens, messages->nb[2], ctrl*messages->nb[1])); + }; + + ggml_tensor * state = recr->mctx->get_r_l(il); + ggml_tensor * history = build_rs(recr, state, hparams.n_embd_r(), ubatch.n_seqs); + history = ggml_reshape_3d(ctx0, history, hparams.n_shortconv_l_cache - 1, hparams.n_sconv_channels, ubatch.n_seqs); + + ggml_tensor * inpSA = cur; + + // attention inputs: SWA layers mix one, full-attention layers one each for Q, K and V + ggml_tensor * inputs[3] = {cur, cur, cur}; + if (layer.attn_res_query) { + ggml_tensor * mixed = mix(blocks, cur, layer.attn_res_query); + for (int j = 0; j < 3; ++j) { + inputs[j] = ggml_cont(ctx0, ggml_view_2d(ctx0, mixed, n_embd, n_tokens, mixed->nb[2], (is_swa ? 0 : j)*mixed->nb[1])); } + } - // self-attention - { - ggml_tensor * Qcur = build_lora_mm(layer.wq, inputs[0]); - ggml_tensor * Kcur = convolve(build_lora_mm(layer.wk, inputs[1]), layer.attn_k_conv, - is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]), state, history, recr, 0); - ggml_tensor * Vcur = convolve(build_lora_mm(layer.wv, inputs[2]), layer.attn_v_conv, - is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]), state, history, recr, n_embd_k_gqa); - ggml_tensor * Rcur = build_lora_mm(layer.attn_rel, inputs[0]); + if (messages) { + // the messages make the Q, K and V inputs of a SWA layer differ + for (int j = 0; j < 3; ++j) { + inputs[j] = control(inputs[j], message(LOOP_CTRL_Q + j), *loop, LOOP_CTRL_Q + j); + } + } - Qcur = clip(ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), layer.attn_q_clip, hparams.f_qk_clip); - Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip); - Vcur = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens), hparams.f_norm_rms_eps); - Rcur = clip(ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens), layer.attn_rel_clip, hparams.f_relative_clip); + if (is_swa && messages) { + for (int j = 0; j < 3; ++j) { + inputs[j] = build_norm(inputs[j], layer.attn_norm, nullptr, LLM_NORM_RMS, il); + } + } else if (is_swa) { + inputs[0] = build_norm(inputs[0], layer.attn_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = inputs[2] = inputs[0]; + } else { + inputs[0] = build_norm(inputs[0], layer.attn_q_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[1] = build_norm(inputs[1], layer.attn_k_inp_norm, nullptr, LLM_NORM_RMS, il); + inputs[2] = build_norm(inputs[2], layer.attn_v_inp_norm, nullptr, LLM_NORM_RMS, il); + } - if (!is_swa) { - Qcur = ggml_mul(ctx0, Qcur, tau); - Rcur = ggml_mul(ctx0, Rcur, tau); - } + // self-attention + { + ggml_tensor * Qcur = build_lora_mm(layer.wq, inputs[0]); + ggml_tensor * Kcur = convolve(build_lora_mm(layer.wk, inputs[1]), layer.attn_k_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_k_conv_proj, inputs[1]), state, history, recr, 0); + ggml_tensor * Vcur = convolve(build_lora_mm(layer.wv, inputs[2]), layer.attn_v_conv, + is_swa ? nullptr : build_lora_mm(layer.attn_v_conv_proj, inputs[2]), state, history, recr, n_embd_k_gqa); + ggml_tensor * Rcur = build_lora_mm(layer.attn_rel, inputs[0]); + + Qcur = clip(ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens), layer.attn_q_clip, hparams.f_qk_clip); + Kcur = clip(ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens), nullptr, hparams.f_qk_clip); + Vcur = ggml_rms_norm(ctx0, ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens), hparams.f_norm_rms_eps); + Rcur = clip(ggml_reshape_3d(ctx0, Rcur, hparams.n_relative, n_head, n_tokens), layer.attn_rel_clip, hparams.f_relative_clip); + + if (!is_swa) { + Qcur = ggml_mul(ctx0, Qcur, tau); + Rcur = ggml_mul(ctx0, Rcur, tau); + } - cb(Qcur, "Qcur", il); - cb(Kcur, "Kcur", il); - cb(Vcur, "Vcur", il); - cb(Rcur, "Rcur", il); + cb(Qcur, "Qcur", il); + cb(Kcur, "Kcur", il); + cb(Vcur, "Vcur", il); + cb(Rcur, "Rcur", il); - ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; + ggml_tensor * rel_pos = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos; - const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; - const int64_t n_kv = rel_pos->ne[0]; + const int64_t n_stream = (is_swa ? attn->self_attn_mask_swa.raw : attn->self_attn_mask.raw)->ne[3]; + const int64_t n_kv = rel_pos->ne[0]; - ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); + ggml_tensor * sinks = build_lora_mm(layer.attn_sink_proj, inputs[0]); - // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head - ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); + // project r on the bias table first, then gather by distance: only the gathered bias is n_kv x n_tokens x n_head + ggml_tensor * table = ggml_mul_mat(ctx0, ggml_pad(ctx0, layer.attn_rel_bias, 0, 1, 0, 0), Rcur); - // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink - table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); - table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); + // the sink logit t is per query: exp(s - t)/(1 + sum(exp(s - t))) = exp(s)/(exp(t) + sum(exp(s))), with a zero sink + table = ggml_sub(ctx0, table, ggml_reshape_3d(ctx0, sinks, 1, n_head, n_tokens)); + table = ggml_cont(ctx0, ggml_permute(ctx0, table, 1, 0, 2, 3)); - ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); - kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); - kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); - cb(kq_b, "kq_b", il); + ggml_tensor * kq_b = ggml_get_rows(ctx0, table, rel_pos); + kq_b = ggml_reshape_4d(ctx0, kq_b, n_head, n_kv, n_tokens/n_stream, n_stream); + kq_b = ggml_cont(ctx0, ggml_permute(ctx0, kq_b, 2, 0, 1, 3)); + cb(kq_b, "kq_b", il); - sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); + sinks = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_head), 0.0f); - cur = build_attn(inp, - nullptr, nullptr, nullptr, - Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); + cur = build_attn(inp, + nullptr, nullptr, nullptr, + Qcur, Kcur, Vcur, kq_b, sinks, 1.0f/sqrtf(n_embd_head), il); - cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); - cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); - cb(cur, "attn_out", il); - } + cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, build_lora_mm(layer.wqkv_gate, inputs[0]))); + cur = convolve(build_lora_mm(layer.wo, cur), layer.attn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa); + cb(cur, "attn_out", il); + } - // the first layer of each block starts a new residual stream, the earlier one joins the mixed blocks - if (il % hparams.attn_res_block_size == 0) { - blocks.push_back(inpSA); - } else { - cur = ggml_add(ctx0, inpSA, cur); - } + // the first layer of each block starts a new residual stream, the earlier one joins the mixed blocks + if (ip % hparams.attn_res_block_size == 0) { + blocks.push_back(inpSA); + } else { + cur = ggml_add(ctx0, inpSA, cur); + } - ggml_tensor * ffn_inp = cur; - cb(ffn_inp, "ffn_inp", il); + ggml_tensor * ffn_inp = cur; + cb(ffn_inp, "ffn_inp", il); - // MoE - cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); - cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); - - cur = build_moe_ffn(cur, - layer.ffn_gate_inp, - nullptr, - nullptr, - layer.ffn_down_exps, - layer.ffn_exp_probs_b, - hparams.n_expert, - hparams.n_expert_used(il), - LLM_FFN_SITU, true, - hparams.expert_weights_scale, - LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, - il, - nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); - - cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); - cb(cur, "ffn_out", il); - - cur = ggml_add(ctx0, ffn_inp, cur); - cb(cur, "l_out", il); + // MoE + cur = ggml_reshape_2d(ctx0, mix(blocks, cur, layer.ffn_res_query), n_embd, n_tokens); + if (messages) { + cur = control(cur, message(LOOP_CTRL_FFN), *loop, LOOP_CTRL_FFN); } + cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); + + cur = build_moe_ffn(cur, + layer.ffn_gate_inp, + nullptr, + nullptr, + layer.ffn_down_exps, + layer.ffn_exp_probs_b, + hparams.n_expert, + hparams.n_expert_used(il), + LLM_FFN_SITU, true, + hparams.expert_weights_scale, + LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, + il, + nullptr, + layer.ffn_gate_up_exps, + layer.ffn_up_exps_s, + layer.ffn_gate_exps_s, + layer.ffn_down_exps_s); + + cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); + cb(cur, "ffn_out", il); + + cur = ggml_add(ctx0, ffn_inp, cur); + cb(cur, "l_out", il); + + return cur; +} +void llama_model_inkling2::graph::build_output(ggml_tensor * cur, const std::vector & blocks) { cur = ggml_reshape_2d(ctx0, mix(blocks, cur, model.output_res_query), n_embd, n_tokens); cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1); @@ -410,3 +447,14 @@ llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_ cb(cur, "result_output", -1); res->t_logits = cur; } + +llama_model_inkling2::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { + ggml_tensor * cur = build_inputs(); + + std::vector blocks; + for (int il = 0; il < n_layer; ++il) { + cur = build_layer(il, il, cur, blocks); + } + + build_output(cur, blocks); +} diff --git a/src/models/models.h b/src/models/models.h index 822d707b9475..636afeae9805 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2492,6 +2492,19 @@ struct llama_model_inkling2 : public llama_model_base { void load_arch_tensors(llama_model_loader & ml) override; uint32_t graph_nodes_per_tensor() const override { return 32; } + // the layers stored in the file + virtual int n_layer_phys() const { return hparams.n_layer(); } + + // message controllers of the q, k, v and ffn inputs of a looped layer (inkling2_loop) + enum { LOOP_CTRL_Q, LOOP_CTRL_K, LOOP_CTRL_V, LOOP_CTRL_FFN, LOOP_CTRL_COUNT }; + + struct loop_layer { + ggml_tensor * msg_query = nullptr; + ggml_tensor * ctrl_down[LOOP_CTRL_COUNT] = {}; + ggml_tensor * ctrl_gain[LOOP_CTRL_COUNT] = {}; + ggml_tensor * ctrl_forget[LOOP_CTRL_COUNT] = {}; + }; + struct graph : public llm_graph_context { graph(const llm_graph_params & params); ggml_tensor * mix(const std::vector & blocks, ggml_tensor * cur, ggml_tensor * query); @@ -2504,6 +2517,52 @@ struct llama_model_inkling2 : public llama_model_base { ggml_tensor * history, llm_graph_input_rs * inp, int64_t offset); + ggml_tensor * control(ggml_tensor * cur, ggml_tensor * message, const loop_layer & loop, int ctrl); + + protected: + // the helpers alone, a derived graph builds its own body + struct no_build {}; + graph(const llm_graph_params & params, no_build) : llm_graph_context(params) {} + + // the inputs and the token embeddings + ggml_tensor * build_inputs(); + // cache slot il of physical layer ip; messages [n_embd, LOOP_CTRL_COUNT, n_tokens] are mixed into its inputs + ggml_tensor * build_layer(int il, int ip, ggml_tensor * cur, std::vector & blocks, + ggml_tensor * messages = nullptr, const loop_layer * loop = nullptr); + void build_output(ggml_tensor * cur, const std::vector & blocks); + + llm_graph_input_mem_hybrid_iswa_rel * inp = nullptr; + llm_graph_input_attn_kv_iswa * attn = nullptr; + llm_graph_input_rs * recr = nullptr; + + ggml_tensor * inp_out_ids = nullptr; + ggml_tensor * tau = nullptr; // log-scaled positions + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + +// the cache slots after the physical layers repeat the core [core_start, core_end) for each later pass +struct llama_model_inkling2_loop : public llama_model_inkling2 { + llama_model_inkling2_loop(const struct llama_model_params & params) : llama_model_inkling2(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + int n_layer_phys() const override { return n_phys; } + int layer_phys(int il) const; + + int n_phys = 0; + uint32_t core_start = 0; + uint32_t core_end = 0; + uint32_t n_passes = 0; + uint32_t gate_rank = 0; + bool varying = false; // trained for a varying number of passes + + // indexed by physical layer - core_start + std::vector loop_layers; + + struct graph : public llama_model_inkling2::graph { + graph(const llm_graph_params & params); }; std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index 90a32abc72cf..6faa8843decd 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -326,7 +326,7 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const n_vocab = 3072; // TODO: should be 4096, but user code cannot get `n_vocab_out` yet [TAG_LLAMA_N_VOCAB_OUT] } else if (arch == LLM_ARCH_HRM_TEXT) { n_layer = 6; // 1 layer per stack x 2 h-cycles x (2 l-cycles + 1) cache slots - } else if (arch == LLM_ARCH_INKLING2) { + } else if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) { n_embd = 128; n_head = 4; n_ff = 24; @@ -703,7 +703,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_MUDD_TAP_INDICES, std::vector({-1, -1, -1, -1, 0, 2, 1, 3})); } - if (arch == LLM_ARCH_INKLING2) { + if (arch == LLM_ARCH_INKLING2 || arch == LLM_ARCH_INKLING2_LOOP) { + const bool loop = arch == LLM_ARCH_INKLING2_LOOP; ms.add_kv(LLM_KV_ATTENTION_RELATIVE_LENGTH, uint32_t(4)); ms.add_kv(LLM_KV_ATTENTION_RELATIVE_EXTENT, uint32_t(16)); ms.add_kv(LLM_KV_ATTENTION_QK_CLIP, 0.25f); @@ -711,6 +712,14 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_ATTENTION_LOG_SCALE_FLOOR, uint32_t(4)); ms.add_kv(LLM_KV_ATTENTION_LOG_SCALE_ALPHA, 0.1f); ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(2)); + if (loop) { + // prelude 0, core 1, coda 2; the loader adds slot 3 for the second pass over the core + ms.add_kv(LLM_KV_LOOP_START, uint32_t(1)); + ms.add_kv(LLM_KV_LOOP_END, uint32_t(2)); + ms.add_kv(LLM_KV_LOOP_COUNT, uint32_t(2)); + ms.add_kv(LLM_KV_LOOP_GATE_RANK, uint32_t(8)); + ms.add_kv(LLM_KV_LOOP_VARYING, false); + } ms.add_kv(LLM_KV_SHORTCONV_L_CACHE, uint32_t(4)); ms.add_kv(LLM_KV_VOCAB_SIZE, n_vocab + 2); ms.add_kv(LLM_KV_VOCAB_SIZE_UNPADDED, n_vocab); @@ -827,7 +836,8 @@ static gguf_context_ptr get_gguf_ctx(const llm_arch arch, const bool moe, const ms.add_kv(LLM_KV_WKV_HEAD_SIZE, n_embd/n_head); ms.add_kv(LLM_KV_SHORTCONV_L_CACHE, uint32_t(3)); ms.add_kv(LLM_KV_RESIDUAL_SCALE, 3.5565588200778455f); - ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(12)); + // the inkling2_loop core boundaries must be multiples of the block size + ms.add_kv(LLM_KV_ATTN_RES_BLOCK_SIZE, uint32_t(arch == LLM_ARCH_INKLING2_LOOP ? 1 : 12)); ms.add_kv(LLM_KV_ACTIVATION_SITU_BETA, 4.0f); ms.add_kv(LLM_KV_ACTIVATION_SITU_LINEAR_BETA, 25.0f); ms.add_kv(LLM_KV_KDA_GATE_LOWER_BOUND, -5.0f); @@ -1145,6 +1155,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_METIS16: case LLM_ARCH_ZONOS3: case LLM_ARCH_INKLING2: + case LLM_ARCH_INKLING2_LOOP: return true; default: return false; From 7476e4726178b27e949b2b45e45705882ac8c501 Mon Sep 17 00:00:00 2001 From: Ashutosh Singh Date: Sat, 21 Nov 2026 08:38:53 +0530 Subject: [PATCH 006/401] docs: openvino backend details, fix SYCL docs (#30967) --- docs/backend/SYCL.md | 31 ++++++++++++++----------------- docs/build.md | 18 +++++++++++++----- 2 files changed, 27 insertions(+), 22 deletions(-) diff --git a/docs/backend/SYCL.md b/docs/backend/SYCL.md index 8649fca0f8a7..ca0b6d7bc161 100644 --- a/docs/backend/SYCL.md +++ b/docs/backend/SYCL.md @@ -62,7 +62,7 @@ The packages for FP32 and FP16 would have different accuracy and performance on - 2026.04-05 - Optimize mul_mat by reorder feature for data type: Q4_K, Q5_K, Q6_K, Q8_0. - Fused MoE. - - Upgrate CI and built package for oneAPI 2025.3.3, support Ubuntu 24.04 built package. + - Upgrade CI and built package for oneAPI 2025.3.3, support Ubuntu 24.04 built package. - 2026.03 - Support Flash-Attention: less memory usage, performance impact depends on LLM. @@ -131,8 +131,6 @@ SYCL backend supports Intel GPU Family: - Intel Built-in Arc GPU - Intel iGPU in Core CPU (11th Generation Core CPU and newer, refer to [oneAPI supported GPU](https://www.intel.com/content/www/us/en/developer/articles/system-requirements/intel-oneapi-base-toolkit-system-requirements.html#inpage-nav-1-1)). -On older Intel GPUs, you may try [OpenCL](/docs/backend/OPENCL.md) although the performance is not optimal, and some GPUs may not support OpenCL nor have any GPGPU capabilities. - #### Verified devices | Intel GPU | Status | Verified Model | @@ -147,7 +145,7 @@ On older Intel GPUs, you may try [OpenCL](/docs/backend/OPENCL.md) although the *Notes:* - **Memory** - - The device memory is a limitation when running a large model. The loaded model size, *`llm_load_tensors: buffer_size`*, is displayed in the log when running `./bin/llama-completion`. + - The device memory is a limitation when running a large model. The loaded model size is displayed in the log when running `./bin/llama-completion`, for example *`load_tensors: SYCL0 model buffer size = 3577.56 MiB`*. - Please make sure the GPU shared memory from the host is large enough to account for the model's size. For e.g. the *llama-2-7b.Q4_0* requires at least 8.0GB for integrated GPU and 4.0GB for discrete GPU. - **Execution Unit (EU)** @@ -172,12 +170,12 @@ Please refer to [Docker with SYCL](../docker.md#docker-with-sycl) for details. This chapter is for quick development & try with SYCL backend on Intel GPU. -You need to install following sofeware before development: +You need to install following software before development: - Intel GPU driver - oneAPI package - other development tools. -Please refer to [Linux](#linux) or [Windows](#windows-1) for above installation and resolve the trouble in usage. There are the detailed guide. +Please refer to [Linux](#linux) or [Windows](#windows-1) for above installation and resolve the trouble in usage. They have the detailed guide. - Linux @@ -474,7 +472,7 @@ Download the binary package for Windows from: https://github.com/ggml-org/llama. Extract the package to local folder, run the llama tools directly. Refer to [Run the inference](#iii-run-the-inference-1). -Note, the package includes the SYCL running time and all depended dll files, no need to install oneAPI package and activte them. +Note, the package includes the SYCL running time and all depended dll files, no need to install oneAPI package and activate them. ### Option 2: build locally from the source code. @@ -484,7 +482,7 @@ Note, the package includes the SYCL running time and all depended dll files, no If you already have a recent version of Microsoft Visual Studio, you can skip this step. Otherwise, please refer to the official download page for [Microsoft Visual Studio](https://visualstudio.microsoft.com/). -2. Install Intel® oneAPI Base toolkit +2. Install Intel® oneAPI Toolkit SYCL backend depends on: - Intel® oneAPI DPC++/C++ compiler/running-time. @@ -492,11 +490,10 @@ SYCL backend depends on: - Intel® oneAPI Deep Neural Network Library (oneDNN). - Intel® oneAPI Math Kernel Library (oneMKL). -All above are included in both **Intel® oneAPI Base toolkit** and **Intel® Deep Learning Essentials** packages. - -It's recommended to install **Intel® Deep Learning Essentials** which only provides the necessary libraries with less size. +a. Install the toolkit -The **Intel® oneAPI Base toolkit** and **Intel® Deep Learning Essentials** can be obtained from the official [Intel® oneAPI Base Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html) page. +It's recommended to install the [Intel® oneAPI Toolkit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit.html). +Alternatively, users can install **Intel® Deep Learning Essentials** + **oneDNN** to provide the necessary libraries with lesser size. Please follow the instructions for downloading and installing the Toolkit for Windows, and preferably keep the default installation values unchanged, notably the installation path *(`C:\Program Files (x86)\Intel\oneAPI` by default)*. @@ -792,7 +789,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_GRAPH | ON *(default)* \|OFF *(Optional)* | Enable build with [SYCL Graph extension](https://github.com/intel/llvm/blob/sycl/sycl/doc/extensions/experimental/sycl_ext_oneapi_graph.asciidoc). | | GGML_SYCL_DNN | ON *(default)* \|OFF *(Optional)* | Enable build with oneDNN. | | GGML_SYCL_HOST_MEM_FALLBACK | ON *(default)* \|OFF *(Optional)* | Allow host memory fallback when device memory is full during quantized weight reorder. Enables inference to continue at reduced speed (reading over PCIe) instead of failing. Requires Linux kernel 6.8+. | -| GGML_SYCL_SUPPORT_LEVEL_ZERO_API | ON *(default)* \|OFF *(Optional)* | Support to use Level Zero API for device memory allocation. Requires Level Zero headers/library at build time and Intel GPU driver (Level Zero runtime) at run time. Reduces system RAM usage during multi-GPU inference. SYCL backend always runs on Level Zero running time even if it's set as OFF (The SYCL api will be usage for memory allocation).| +| GGML_SYCL_SUPPORT_LEVEL_ZERO_API | ON *(default)* \|OFF *(Optional)* | Support to use Level Zero API for device memory allocation. Requires Level Zero headers/library at build time and Intel GPU driver (Level Zero runtime) at run time. Reduces system RAM usage during multi-GPU inference. SYCL backend always runs on Level Zero running time even if it's set as OFF (the SYCL API is then used for memory allocation).| | CMAKE_C_COMPILER | `icx` *(Linux)*, `icx/cl` *(Windows)* | Set `icx` compiler for SYCL code path. | | CMAKE_CXX_COMPILER | `icpx` *(Linux)*, `icx` *(Windows)* | Set `icpx/icx` compiler for SYCL code path. | @@ -809,11 +806,11 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_ENABLE_OPT | 0 or 1 (default)| Enable optimize features for Intel GPUs. (Recommended to 0 for Intel devices older than Gen 10) | | GGML_SYCL_ENABLE_GRAPH | 0 (default) or 1 | Enable running computations through SYCL Graphs feature. Disabled by default because SYCL Graph is still in development, performance depends on model and device. [1.](#sycl-graph-footnote) | | GGML_SYCL_GRAPH_EVICTION_TIMEOUT | 10 (default) or positive integer | Seconds a cached SYCL graph can go unused before it is evicted. Checked on a sweep that runs every half of this timeout. | -| GGML_SYCL_ENABLE_HOST_PINNED_MEM | 0 or 1 (default) | Enable host pinned memory to speed up copy data from host to device. When disable it, host memory will common malloc() on CPU. Disable it when use `--load-model mlock`.| +| GGML_SYCL_ENABLE_HOST_PINNED_MEM | 0 or 1 (default) | Enable host pinned memory to speed up copy data from host to device. When disable it, host memory will common malloc() on CPU. Disable it when use `--load-mode mlock`.| | GGML_SYCL_HOST_PINNED_MEM_2G | 0 (default) or 1 | Limit the max memory allocation to be no more than 2GB when enable host pinned memory. USM allocations above 2 GiB take the relaxed/large-allocation path, which serializes H2D copies with compute and prevents copy/compute overlap. It will impact the startup time. Need more test. Depend on `GGML_SYCL_ENABLE_HOST_PINNED_MEM=1`.| | GGML_SYCL_UPLOAD_STAGING_SLOTS | 4 (default) or non-negative integer | Number of 8 MiB pinned host slots used to stage tensor uploads (model loading), so the host copy of one slot overlaps the transfer of the previous one. Set to 0 to use the old path: a malloc'd bounce buffer and a blocking copy per tensor. | | GGML_SYCL_GET_MEM_API | 0 (default) or 1 | Set to get memory info (free, total) by Level Zero or SYCL API:
0 - Level Zero API: support more GPUs, only run on Level Zero running time. When there is an error, fallback to call SYCL API. Depend on GGML_SYCL_SUPPORT_LEVEL_ZERO_API.
1 - SYCL API: legacy, support more running time, it can't get the free size of some GPUs (like Arc770). In such case, return the free size as value of total size.| -| GGML_SYCL_USE_LEVEL_ZERO_API | 1 (default) or 0 | Use Level Zero API for device memory allocation instead of SYCL. Reduces system RAM usage on Intel dGPUs by avoiding DMA-buf/TTM host memory staging. Requires GGML_SYCL_SUPPORT_LEVEL_ZERO_API=ON at build time. SYCL backend always runs on Level Zero running time even if it's set as OFF (The SYCL api will be usage for memory allocation).| +| GGML_SYCL_USE_LEVEL_ZERO_API | 1 (default) or 0 | Use Level Zero API for device memory allocation instead of SYCL. Reduces system RAM usage on Intel dGPUs by avoiding DMA-buf/TTM host memory staging. Requires GGML_SYCL_SUPPORT_LEVEL_ZERO_API=ON at build time. SYCL backend always runs on Level Zero running time even if it's set as OFF (the SYCL API is then used for memory allocation).| | GGML_SYCL_ENABLE_DNN | 0 or 1 (default)| Enable running computations through oneDNN and always use oneMKL. | | GGML_SYCL_FA_ONEDNN | 1 (default) or 0 | Enable the oneDNN fused SDPA (flash-attention) path on supported GPUs. Set to 0 to always use the native SYCL flash-attention kernel. | | GGML_SYCL_FA_ONEDNN_MAX_KV | 0 (default, disabled) or positive integer | By default (0), all sequences are handled by the oneDNN fused SDPA path, regardless of KV length; a positive value caps that length, past which sequences fall back to the native kernel. If GPU driver watchdog resets (DEVICE_LOST) occur during long-context inference, set this near the context depth where they start, e.g. 24576. | @@ -839,7 +836,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_SPARSE_FA_DEBUG | 0 (default) or 1 | Enable to debug for Sparse Flash-attention.| | GGML_SYCL_SPARSE_FA_MARGIN | [0,..] default:256 | Set the margin value for Sparse Flash-attention.| | ZES_ENABLE_SYSMAN | 0 (default) or 1 | Support to get free memory of GPU by sycl::aspect::ext_intel_free_memory.
Recommended to use when --split-mode = layer | -| UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS | 0 (default) or 1 | Allow SYCL/Unified Runtime Level Zero device allocations larger than 4 GiB. llama.cpp's direct Level Zero allocation path requests the relaxed maximum-size limit itself when GGML_SYCL_ENABLE_LEVEL_ZERO=1. | +| UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS | 0 (default) or 1 | Allow SYCL/Unified Runtime Level Zero device allocations larger than 4 GiB. llama.cpp's direct Level Zero allocation path requests the relaxed maximum-size limit itself when GGML_SYCL_USE_LEVEL_ZERO_API=1. | | GGML_SYCL_USM_SYSTEM | 0 (default) or 1 | Enable experimental support for [USM system allocations](https://github.khronos.org/SYCL_Reference/iface/usm_basic_concept.html#system-allocations) for large GPU buffers. This requires enough host memory for model weights and caches, an Intel Xe2+ GPU such as BMG or newer and supported on Linux only, with CONFIG_DRM_XE_GPUSVM enabled. | | GGML_SYCL_BMG_VRAM_CHECK | 1 (default) or 0 | Workaround for BMG (Arc B-series) GPUs, where the Level Zero driver accepts device allocations beyond VRAM and moves the overflow to system RAM, which can exhaust host memory when a model does not fit (e.g. `-ngl 999`, see https://github.com/intel/compute-runtime/issues/1047). When enabled, a model or split buffer that does not fit in the device's free memory is refused and the model load fails with an error. Set to 0 to disable. | @@ -950,7 +947,7 @@ Pass these via `CXXFLAGS` or add a one-off `#define` to enable a flag on the spo - `ggml_backend_sycl_buffer_type_alloc_buffer: can't allocate 5000000000 Bytes of memory on device` - With the default `GGML_SYCL_ENABLE_LEVEL_ZERO=1`, llama.cpp requests Level Zero's relaxed maximum-size allocation limit directly. If Level Zero support is disabled at build time or runtime and the allocation goes through SYCL/Unified Runtime instead, enable support for allocations larger than 4 GiB by: + With the default `GGML_SYCL_USE_LEVEL_ZERO_API=1`, llama.cpp requests Level Zero's relaxed maximum-size allocation limit directly. If Level Zero support is disabled at build time or runtime and the allocation goes through SYCL/Unified Runtime instead, enable support for allocations larger than 4 GiB by: ``` export UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1 set UR_L0_ENABLE_RELAXED_ALLOCATION_LIMITS=1 diff --git a/docs/build.md b/docs/build.md index e369aad01f49..759985544cb8 100644 --- a/docs/build.md +++ b/docs/build.md @@ -132,7 +132,10 @@ Full steps, threading notes, and a fallback for older CMake: [AOCL.md](./backend ### Intel oneMKL -Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni. Please note that this build config **does not support Intel GPU**. For Intel GPU support, please refer to [llama.cpp for SYCL](./backend/SYCL.md). +Building through oneAPI compilers will make avx_vnni instruction set available for intel processors that do not support avx512 and avx512_vnni. +> Note: This build config **does not support Intel GPU and NPU**. +> - For Intel GPU support, refer to [OpenVINO](#openvino), [SYCL](#sycl) and [Vulkan](#vulkan) backends. +> - For Intel NPU support, refer to [OpenVINO](#openvino) backend. - Using manual oneAPI installation: By default, `GGML_BLAS_VENDOR` is set to `Generic`, so if you already sourced intel environment script and assign `-DGGML_BLAS=ON` in cmake, the mkl version of Blas will automatically been selected. Otherwise please install oneAPI and follow the below steps: @@ -444,9 +447,9 @@ Launch `w64devkit.exe` and run the following commands to copy Vulkan dependencie ```sh SDK_VERSION=1.3.283.0 cp /VulkanSDK/$SDK_VERSION/Bin/glslc.exe $W64DEVKIT_HOME/bin/ -cp /VulkanSDK/$SDK_VERSION/Lib/vulkan-1.lib $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/ -cp -r /VulkanSDK/$SDK_VERSION/Include/* $W64DEVKIT_HOME/x86_64-w64-mingw32/include/ -cat > $W64DEVKIT_HOME/x86_64-w64-mingw32/lib/pkgconfig/vulkan.pc < $W64DEVKIT_HOME/lib/pkgconfig/vulkan.pc < Date: Sat, 21 Nov 2026 04:37:40 +0100 Subject: [PATCH 007/401] sycl: Improve Grouped XMX GEMM by avoiding SLM staging (#31428) --- docs/backend/SYCL.md | 1 + ggml/src/ggml-sycl/CMakeLists.txt | 14 +- ggml/src/ggml-sycl/common.hpp | 1 + ggml/src/ggml-sycl/fused-gemm-esimd.cpp | 1160 +++++++++++++++++++++++ ggml/src/ggml-sycl/fused-gemm-esimd.hpp | 33 + ggml/src/ggml-sycl/fused-gemm.cpp | 89 +- ggml/src/ggml-sycl/fused-gemm.hpp | 27 + ggml/src/ggml-sycl/ggml-sycl.cpp | 3 + 8 files changed, 1299 insertions(+), 29 deletions(-) create mode 100644 ggml/src/ggml-sycl/fused-gemm-esimd.cpp create mode 100644 ggml/src/ggml-sycl/fused-gemm-esimd.hpp diff --git a/docs/backend/SYCL.md b/docs/backend/SYCL.md index ca0b6d7bc161..4a1d16aad703 100644 --- a/docs/backend/SYCL.md +++ b/docs/backend/SYCL.md @@ -827,6 +827,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm | GGML_SYCL_XMX_MAX_COLS | non-negative integer, 80 (default) | Most activation columns (batch size) the `GGML_SYCL_ENABLE_XMX_ESIMD` kernels take; wider batches use the other mat-mul kernels. A larger value keeps XMX for bigger batches (as repeated launches), `0` never uses it. | | GGML_SYCL_XMX_GLU_MAX_COLS | 0 to 16, 16 (default) | Most columns the fused gate and up XMX kernel takes; wider batches run gate and up as separate mat-vecs. 16 is the most the kernel is built for, larger values are clamped to 16 and `0` turns the fused kernel off. | | GGML_SYCL_XMX_GATHER_TYPES | decimal bitmask, all bits set (default) | Weight formats that may use the XMX dequant-GEMM paths, which dequantize weights straight into the XMX tiles. This speeds up prompt processing of MoE models on GPUs with XMX units (Arc A- and B-series, Arc Pro, Data Center GPU Max), for example pp512 of Qwen3-30B-A3B UD-IQ3_XXS by about 50% on an Arc Pro B60. Bits:
* 1: IQ4_NL, 2: IQ3_S, 4: IQ4_XS, 8: IQ3_XXS, 16: IQ2_XXS, 32: IQ2_XS, 64: IQ2_S, 128: IQ1_S, 256: IQ1_M
* 512: Q8_0, 1024: Q4_K, 2048: Q5_K, 4096: Q6_K, 8192: Q2_K, 16384: Q3_K (MoE `MUL_MAT_ID` only)
Add values to combine them, for example `3` for IQ4_NL and IQ3_S; `0` disables the paths. A set bit does not force the path: batches of more than 64 tokens per expert use the library GEMM unless the device schedule width heuristic is overridden with `GGML_SYCL_MMID_SCHED=3`. Row lengths must be a multiple of 256 (32 for IQ4_NL and Q8_0). | +| GGML_SYCL_MMID_ESIMD | 0, 1 (default), 2 | The `MUL_MAT_ID` grouped XMX dequant-GEMM as an ESIMD kernel that dequantizes the weights straight into the `dpas` register operands, with no shared local memory image of them, from either weight layout (the per-expert reorder or the canonical blocks). q8_0, iq4_nl, iq4_xs, iq3_s, iq3_xxs and q2_K to q6_K. It stands in for the 8x16x16 sub-group-16 combination of f16 or bf16 (Xe2, Xe-HPC) and for the 8x8x16 sub-group-8 one (Xe-HPG: Arc A-series, ARL-H; there it works on 16 rows a thread and reads with 1D block loads, since that architecture has half the register file and no 2D block loads); while it is on, a grouped call whose weight type it covers is moved to that combination from any other shape of its type and sub-group size, whatever `GGML_SYCL_XMX_GATHER_SHAPES` allows, because the shape bits choose among `joint_matrix` tiles and the ESIMD kernel tiles on its own. A call it declines runs that combination's `joint_matrix` kernel. 0 uses the `joint_matrix` kernel, 1 the ESIMD one, 2 the ESIMD one summing K in the `joint_matrix` kernel's order (bit-identical output for f16; slower). An AOT build gets its 256-register file through `-ze-opt-enable-auto-large-GRF-mode` (set by the CMake build). Not built with `GGML_SYCL_SUPPORT_XMX=OFF`. | | GGML_SYCL_MMID_SCHED | decimal bitmask, 1 (default) | Build the grouped MoE routing and tile schedule on the GPU, avoiding the expert-ID host readback and CPU sort.
* 1: enable the device schedule.
* 2: override the fallback for models with few routed experts by disabling the performance heuristic that rejects batches averaging more than 64 routed rows per expert. This may reduce performance; type, shape, precision and device capability checks still apply.
Use `3` to enable the device schedule and override this heuristic, or `0` to use the host schedule. Bit 2 alone does not enable the device schedule. Higher bits are ignored. | | GGML_SYCL_XMX_GATHER_SHAPES | decimal bitmask, 255 (default) | XMX `joint_matrix` combinations the paths of `GGML_SYCL_XMX_GATHER_TYPES` may use; the operand type comes from `GGML_SYCL_DYNAMIC_PRECISION` and the best supported combination is picked automatically (logged as `fg_pick_combo`). Bits:
* Xe2, Xe3, Xe-HPC: 1: f16 8x16x16, 2: f16 16x16x16, 4: f16 32x64x16, 8: f16 32x64x32, 32: tf32 8x16x8, 64: bf16 8x16x16
* Xe-HPG (Arc A770, ARL-H): 16: f16 8x8x16, 128: bf16 8x8x16
Clear a bit to exclude a combination, or set a single bit to force one for testing. | | GGML_SYCL_DYNAMIC_PRECISION | `F16` (default with `GGML_SYCL_F16=ON`), `BF16`, `TF32` or `F32` (default otherwise) | Operand type of the XMX dequant-GEMM paths (`GGML_SYCL_XMX_GATHER_TYPES`); accumulation is always f32. `F16` is the fastest, but activations above 65504 overflow. `BF16` keeps the f32 range at a 7-bit mantissa, `TF32` keeps the range and the f16 mantissa but is about 30% slower and needs Xe2, Xe3 or Xe-HPC, and `F32` turns the XMX paths off. Ops that request a higher src1 precision ([TAG_GGML_PREC]) get it regardless of this setting. | diff --git a/ggml/src/ggml-sycl/CMakeLists.txt b/ggml/src/ggml-sycl/CMakeLists.txt index 8312a83052ca..0a5aede0bfe4 100644 --- a/ggml/src/ggml-sycl/CMakeLists.txt +++ b/ggml/src/ggml-sycl/CMakeLists.txt @@ -218,6 +218,8 @@ endif() if (GGML_SYCL_TARGET STREQUAL "INTEL") add_compile_definitions(GGML_SYCL_WARP_SIZE=16) + # With AOT the option goes to ocloc inside -options (see GGML_SYCL_DEVICE_ARCH below): a bare + # -Xs hands it to ocloc as a command-line flag, which fails the device link. if (NOT GGML_SYCL_DEVICE_ARCH) target_link_options(ggml-sycl PRIVATE -Xs -ze-intel-greater-than-4GB-buffer-required) else() @@ -248,10 +250,18 @@ endif() if (GGML_SYCL_DEVICE_ARCH) message(STATUS "GGML_SYCL_DEVICE_ARCH=${GGML_SYCL_DEVICE_ARCH} (AOT via spir64_gen)") + # AOT (oneAPI 2026.2) ignores the grf_size<256> kernel property on ESIMD kernels and builds them + # with 128 registers, which made the ESIMD MoE GEMM 1.7-3.9x slower than under JIT; SPMD kernels + # keep honouring the property. A module-wide -doubleGRF also moves the ESIMD kernels that ask for + # 128 to 256, and a server built with it hung on its first request, so IGC picks the size per + # kernel from its register pressure instead (ESIMD kernels too; -ze-opt-large-grf-kernel does not + # reach them). + set(GGML_SYCL_AOT_BACKEND_OPTIONS + "-device ${GGML_SYCL_DEVICE_ARCH} -options '-ze-intel-greater-than-4GB-buffer-required -ze-opt-enable-auto-large-GRF-mode'") target_compile_options( ggml-sycl PRIVATE -fsycl-targets=spir64_gen - "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\"" + "SHELL:-Xsycl-target-backend=spir64_gen \"${GGML_SYCL_AOT_BACKEND_OPTIONS}\"" ) # Pass through parallel job (process) count for parallelising the @@ -266,7 +276,7 @@ if (GGML_SYCL_DEVICE_ARCH) target_link_options( ggml-sycl PRIVATE -fsycl-targets=spir64_gen - "SHELL:-Xsycl-target-backend=spir64_gen \"-device ${GGML_SYCL_DEVICE_ARCH} -options -ze-intel-greater-than-4GB-buffer-required\"" + "SHELL:-Xsycl-target-backend=spir64_gen \"${GGML_SYCL_AOT_BACKEND_OPTIONS}\"" -fsycl-max-parallel-link-jobs=${GGML_SYCL_MAX_PARALLEL_LINK_JOBS} ) diff --git a/ggml/src/ggml-sycl/common.hpp b/ggml/src/ggml-sycl/common.hpp index 75e783d12095..ae156acca75f 100644 --- a/ggml/src/ggml-sycl/common.hpp +++ b/ggml/src/ggml-sycl/common.hpp @@ -72,6 +72,7 @@ extern int g_ggml_sycl_debug; extern int g_ggml_sycl_enable_optimize; extern int g_ggml_sycl_enable_fusion; extern int g_ggml_sycl_enable_esimd; +extern int g_ggml_sycl_mmid_esimd; extern int g_ggml_sycl_mmvq_wide; extern int g_ggml_sycl_enable_xmx_esimd; extern int g_ggml_sycl_xmx_max_cols; diff --git a/ggml/src/ggml-sycl/fused-gemm-esimd.cpp b/ggml/src/ggml-sycl/fused-gemm-esimd.cpp new file mode 100644 index 000000000000..37f87e377819 --- /dev/null +++ b/ggml/src/ggml-sycl/fused-gemm-esimd.cpp @@ -0,0 +1,1160 @@ +#include "fused-gemm-esimd.hpp" + +#include +#include +#include + +// One thread owns MR rows of one expert's weight and one BN-wide tile of the schedule, over the +// whole K. Per k step (32 values) it loads the rows' stored bits, dequantizes them in registers to +// the f16 A operand of dpas (RC = 8 rows x 16 k, row major) and multiplies it with the packed B, +// which is already the dpas VNNI operand: [K/2][Npad][2] halves, NW columns a dpas. +// +// The joint_matrix kernel dequantizes into SLM and reads it back in the same sub-group, which is +// staging, not sharing; dpas takes registers, so that round trip and its barriers are gone here. +// Its K split over GGML_SYCL_GROUPED_GEMM_KSPLIT sub-groups is reproduced as sequential K ranges summed in +// the same ascending order as its tile_c reduction, and every format below rounds A exactly as its +// joint_matrix A stage does, so the output is the same bits. +// +// A weight format is a grouped_gemm_esimd_a with: raw, the stored bits of the MR rows for one k +// step; load(), which fetches them from the expert's slice in either layout (grouped_gemm_esimd::slice); and +// decode(), the f16 A of one row group. +// It reads the same fields as the joint_matrix A stage of its format. +// +// The kernel is built for one grouped_gemm_arch: the dpas width NW (the columns of B one dpas takes, the +// sub-group size of the joint_matrix combination it stands in for), the rows of one thread, and +// whether 2D block loads exist. Xe2 and Xe-HPC: 16 wide, 32 rows, 2D loads. Xe-HPG (Arc A, ARL-H): +// 8 wide, no 2D block messages, and 256 registers of 32 bytes, half of Xe2's file, so 16 rows: its +// 32-row accumulators alone would take half the registers. +static constexpr int GGML_SYCL_GROUPED_GEMM_KSPLIT = FG_KSPLIT; +static constexpr int GGML_SYCL_GROUPED_GEMM_BN = GGML_SYCL_FG_BN; +static constexpr int GROUPED_GEMM_MR = 32; // rows of one thread on Xe2: one 2D load covers them +static constexpr int GROUPED_GEMM_RC = 8; // rows of one dpas +static constexpr int GROUPED_GEMM_QK = 32; // values of one k step + +template struct grouped_gemm_arch { + static constexpr int NW = NW_; + static constexpr int MR = MR_; + static constexpr bool L2D = L2D_; +}; + +using grouped_gemm_xe2 = grouped_gemm_arch<16, GROUPED_GEMM_MR, true>; +using grouped_gemm_xehpg = grouped_gemm_arch<8, 16, false>; + +// An AOT build compiles each kernel only for the targets of its dpas width: GGML_SYCL_XMX_AOT_SG for +// spir64_gen, FG_AOT_SG (fused-gemm.hpp) for intel_gpu_* targets. A build without XMX (GGML_SYCL_SUPPORT_XMX +// off) compiles none of them +template static constexpr bool grouped_gemm_built() { +#if !defined(GGML_SYCL_SUPPORT_XMX) + return false; +#elif defined(GGML_SYCL_XMX_AOT_SG) + return A::NW == GGML_SYCL_XMX_AOT_SG; +#elif defined(FG_AOT_SG) + return A::NW == FG_AOT_SG; +#else + return true; +#endif +} + +namespace grouped_gemm_esimd { +using namespace sycl::ext::intel::esimd; + +// f(std::integral_constant) for I in [0, N): register selects at a runtime offset become +// indirect accesses, so loops whose index picks registers are spelled out at compile time +template struct static_for { + template static ESIMD_INLINE void run(Fn & f) { + if constexpr (I < N) { + f(std::integral_constant{}); + static_for::run(f); + } + } +}; + +// One field of a format's block. In the reorder (SoA) layout it is a stream of its own, `size` bytes +// a block, after `pre` bytes a block of the streams before it; in the canonical (AoS) layout it is +// `aos` bytes into the block. +struct field { + int pre; + int size; + int aos; +}; + +// Where one thread's rows sit in an expert's slice, in either layout. nblocks counts the stored blocks +// of the slice, bpr those of one row, bs is the size of one block. +template struct slice { + const uint8_t * x; + int M; + int bpr; + int nblocks; + int m0; + bool aos; + int bs; + + // per row, the byte offset from x of byte `inner` of field f of block ib + ESIMD_INLINE simd at(const field & f, const int ib, const int inner) const { + const int stride = aos ? bs : f.size; + simd o(0, (uint32_t) (bpr * stride)); + return o + (uint32_t) ((aos ? f.aos : nblocks * f.pre) + (m0 * bpr + ib) * stride + inner); + } + + // a field's bytes at offset `inner` start on a dword in every block (the AoS block and offset + // are multiples of 4); the SoA streams always do + ESIMD_INLINE bool dword_aligned(const field & f, const int inner) const { + return !aos || (bs % 4 == 0 && (f.aos + inner) % 4 == 0); + } + + ESIMD_INLINE simd u16(const field & f, const int ib, const int inner) const { + return gather((const uint16_t *) x, at(f, ib, inner)); + } + + ESIMD_INLINE simd u32(const field & f, const int ib, const int inner) const { + if (dword_aligned(f, inner)) { + return gather((const uint32_t *) x, at(f, ib, inner)); + } + return rows<1>(f, ib, inner); + } + + // W dwords of each of the MR rows from byte `inner` (a multiple of 4) of field f of block ib, as + // [row][W]. SoA with 2D block loads (L2D): one message over the stream. Otherwise the rows' dwords + // are gathered, as [W][row], at offsets rounded down to a dword (every field starts on an even + // byte; the SoA streams are dword aligned), shifted by 16 bits where an AoS row's block starts on + // 2 mod 4, and transposed with strided reads. + template ESIMD_INLINE simd rows(const field & f, const int ib, const int inner) const { + if constexpr (L2D) { + if (!aos) { + const unsigned pitch = (unsigned) (bpr * f.size); + return load_2d((const uint32_t *) (x + (size_t) nblocks * f.pre), pitch - 1, M - 1, + pitch - 1, (ib * f.size + inner) / 4, m0); + } + } + const simd o = at(f, ib, inner); + simd g; + if (dword_aligned(f, inner)) { + g = gather((const uint32_t *) x, o); + } else { + // per row: sh is 16 where the run starts on 2 mod 4, else 0; hm keeps the next dword's low + // half only where it is needed + const simd oa = o & ~3u; + const simd sh = (o & 2u) << 3; + const simd hm = 0u - (sh >> 4); + simd lo = gather((const uint32_t *) x, oa); + // the dword after the run holds its last 2 bytes where a row needs it; a row that does not + // reads its first dword again rather than past the field + const simd tail = gather((const uint32_t *) x, oa + ((4u * W) & hm)); + auto shift = [&](auto vc) SYCL_ESIMD_FUNCTION { + constexpr int v = decltype(vc)::value; + simd a = lo.template select(v * MR); + simd b; + if constexpr (v + 1 < W) { + b = lo.template select((v + 1) * MR); + } else { + b = tail; + } + g.template select(v * MR) = (a >> sh) | ((b << 16) & hm); + }; + static_for<0, W>::run(shift); + } + if constexpr (W == 1) { + return g; + } else { + simd t; + auto row = [&](auto rc) SYCL_ESIMD_FUNCTION { + constexpr int r = decltype(rc)::value; + t.template select(r * W) = g.template select(r); + }; + static_for<0, MR>::run(row); + return t; + } + } +}; + +// A decode returns its row group's A in the order the two dpas of a k step read it, [k half][row][16 +// k]: both iq formats store k and k + 16 in the same byte or grid dword half, so that order needs +// only reads with a stride, while [row][32 k] needed strided writes, which split into SIMD4. +using a_halves = simd; + +// f16 of the f32 product code * scale, each row's scale over its 16 values of a k half: the +// expression the joint_matrix stages evaluate before E::make rounds it +ESIMD_INLINE simd scale_half(simd v, + simd d) { + v *= d.template replicate_vs_w_hs(0); + return v; +} + +// The iq4 codebook by byte, in SLM: entry b holds the values of its low and its high nibble as the +// two 16-bit halves of one dword, as T (half, or int16 for an f32 product). A read-only table every +// lane indexes, which is what SLM is for: register-indirect iselect() over the same lanes cost +// 7.3 of 12.7 ms, a 16-entry SLM table per nibble about 0.4. +template ESIMD_INLINE void iq4_pair_table_to_slm() { + static_assert(sizeof(T) == 2, "two values a dword"); + simd lo; +#pragma unroll + for (int i = 0; i < 16; ++i) { + lo[i] = sycl::bit_cast((T) kvalues_iq4nl[i]); + } +#pragma unroll + for (int hi = 0; hi < 16; ++hi) { + slm_block_store(hi * 64, lo | ((uint32_t) sycl::bit_cast((T) kvalues_iq4nl[hi]) << 16)); + } +} + +// 16 packed bytes a row; byte j holds k = j in its low and k = 16 + j in its high nibble (the order +// of fg_decode_iq4_xs and of the iq4_nl stage). One gather per byte; the low halves are k half 0, +// the high halves k half 1, each [row][16]. +template +ESIMD_INLINE simd iq4_codes(simd q) { + simd off = q.template bit_cast_view(); + simd pr = slm_gather(off * 4); + auto pv = pr.template bit_cast_view(); + simd v; + v.template select(0) = pv.template select(0); + v.template select(GROUPED_GEMM_RC * 16) = pv.template select(1); + return v; +} +// A 2D surface: rows `pitch` bytes apart, 16-byte aligned and at least 64 bytes +constexpr bool surface_ok(const int pitch) { + return pitch % 16 == 0 && pitch >= 64; +} + +// byte i of each lane's dword, i a runtime index: a shift by a scalar, not a register pick +template ESIMD_INLINE simd byte_of(simd w, const int i) { + return (w >> (8 * i)) & 0xffu; +} + +// one of four per-lane dwords by a runtime index, as uniform branches rather than a register pick +template ESIMD_INLINE simd dword_of(simd * w, const int i) { + simd r = w[0]; + if (i == 1) { + r = w[1]; + } else if (i == 2) { + r = w[2]; + } else if (i == 3) { + r = w[3]; + } + return r; +} + +// a row group's 32 k-ordered code bytes a row as f32, in [k half][row][16 k] +ESIMD_INLINE simd byte_codes(simd q) { + auto bm = q.template bit_cast_view(); + simd v; + v.template select(0) = bm.template select(0, 0); + v.template select(GROUPED_GEMM_RC * 16) = + bm.template select(0, 16); + return v; +} + +// f16 of d * code - m in f32, each row's d and m over its 16 values of a k half: the expression of +// the K-quant stages with a min +ESIMD_INLINE simd scale_min_half(simd v, + simd d, + simd m) { + v = v * d.template replicate_vs_w_hs(0) - + m.template replicate_vs_w_hs(0); + return v; +} + +// the two k halves of a row group, the code bytes times one (d, m) per row and half +ESIMD_INLINE a_halves halves_dm(simd q, + simd d0, + simd m0, + simd d1, + simd m1, + const float bias = 0.0f) { + simd c = byte_codes(q); + if (bias != 0.0f) { + c -= bias; + } + a_halves v; + v.template select(0) = + scale_min_half(c.template select(0), d0, m0); + v.template select(GROUPED_GEMM_RC * 16) = + scale_min_half(c.template select(GROUPED_GEMM_RC * 16), d1, m1); + return v; +} + +// a row group's 32 values from grid dwords (byte b of entry e is k = 4e + b) and a sign dword per +// row (bit k negates k), times d: the expression of the iq3 stages +ESIMD_INLINE a_halves grid_signed(simd ge, + simd signs, + simd d) { + auto gm = ge.template bit_cast_view(); + simd sg = signs.template replicate_vs_w_hs(0); + simd k(0, 1); + k &= 15; + a_halves v; +#pragma unroll + for (int h = 0; h < 2; ++h) { + simd eh = gm.template select(0, 4 * h); + simd f = eh.template bit_cast_view(); + f.merge(-f, ((sg >> (k + 16 * h)) & 1) != 0); + v.template select(h * GROUPED_GEMM_RC * 16) = scale_half(f, d); + } + return v; +} +} // namespace grouped_gemm_esimd + +template struct grouped_gemm_esimd_a { + static constexpr bool supported = false; +}; + +// [qs 32][d], one block a k step +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK8_0; + static constexpr bool whole = true; // decode_all() for the whole tile + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK8_0, 2 }, D = { QK8_0, 2, 0 }; + static bool ok(const int K, const bool aos) { return K % qk == 0 && (aos || K >= 64); } + struct sb_t {}; + template static ESIMD_INLINE void load_sb(sb_t &, const Sl &, const int) {} + template static ESIMD_INLINE void load(raw & r, sb_t &, const Sl & s, const int kb, const int) { + r.q = s.template rows<8>(QS, kb, 0); + r.d = s.u16(D, kb, 0); + } + // all MR x 32 quants at once: int8 -> half, times the row's scale. q * d needs at most 19 + // significant bits, so the f32 product the joint_matrix stage rounds to half is exact and one + // correctly rounded half multiply gives the same bits. + static ESIMD_INLINE grouped_gemm_esimd::simd decode_all(raw & r) { + using namespace grouped_gemm_esimd; + simd av = r.q.template bit_cast_view(); + simd dh = r.d.template bit_cast_view(); + av *= dh.template replicate_vs_w_hs(0); + return av; + } +}; + +// [qs 16][d], one block a k step +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK4_NL; + static constexpr bool whole = false; + static constexpr int slm_bytes = 256 * sizeof(uint32_t); + + static ESIMD_INLINE void init_slm() { grouped_gemm_esimd::iq4_pair_table_to_slm(); } + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK4_NL / 2, 2 }, D = { QK4_NL / 2, 2, 0 }; + static bool ok(const int K, const bool aos) { return K % qk == 0 && (aos || K / 2 >= 64); } + struct sb_t {}; + template static ESIMD_INLINE void load_sb(sb_t &, const Sl &, const int) {} + template static ESIMD_INLINE void load(raw & r, sb_t &, const Sl & s, const int kb, const int) { + using namespace grouped_gemm_esimd; + r.q = s.template rows<4>(QS, kb, 0); + simd d = s.u16(D, kb, 0); + r.d = d.template bit_cast_view(); + } + // the codebook values are integers below 128, exact in half, and d * value has at most 18 + // significant bits: one correctly rounded half multiply is the stage's f32 product rounded + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + a_halves v = iq4_codes(r.q.template select(g * GROUPED_GEMM_RC * 4)); + simd dg = r.d.template select(g * GROUPED_GEMM_RC); + simd dr = dg.template replicate_vs_w_hs(0); + v.template select(0) *= dr; + v.template select(GROUPED_GEMM_RC * 16) *= dr; + return v; + } +}; + +// [qs 128][d 2][scales_h 2][scales_l 4] per 256 values; k step ib8 of a superblock is sub-block ib8 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + // int16 table and f32 products: d * (scale - 32) * value can need 24 significant bits, more + // than a half multiply keeps + static constexpr int slm_bytes = 256 * sizeof(uint32_t); + + static ESIMD_INLINE void init_slm() { grouped_gemm_esimd::iq4_pair_table_to_slm(); } + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d; + }; + struct sb_t { + grouped_gemm_esimd::simd d; + grouped_gemm_esimd::simd sh; // scales_h + grouped_gemm_esimd::simd sl; // scales_l, 4 bytes + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 2, 8 }, D = { QK_K / 2, 2, 0 }, + SH = { QK_K / 2 + 2, 2, 2 }, SL = { QK_K / 2 + 4, 4, 4 }; + static bool ok(const int K, const bool) { return K % qk == 0; } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + sb.sh = s.u16(SH, ib, 0); + sb.sl = s.u32(SL, ib, 0); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + r.q = s.template rows<4>(QS, kb / 8, 16 * j); + // d * (6-bit scale - 32), in f32 as the stage computes it + simd sc = simd(((sb.sl >> (4 * j)) & 0xf) | (((sb.sh >> (2 * j)) & 3) << 4)) - 32; + r.d = sb.d * simd(sc); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd c = + iq4_codes(r.q.template select(g * GROUPED_GEMM_RC * 4)); + simd dg = r.d.template select(g * GROUPED_GEMM_RC); + a_halves v; + v.template select(0) = scale_half(c.template select(0), dg); + v.template select(GROUPED_GEMM_RC * 16) = + scale_half(c.template select(GROUPED_GEMM_RC * 16), dg); + return v; + } +}; + +// [qs 64][qh 8][signs 32][d 2, scales 4] per 256 values. Value k of sub-block ib8 is byte k % 4 of +// grid entry k / 4, the entry index being qs[k / 4] with bit 8 from qh bit k / 4, negated where bit +// k of the sub-block's sign dword is set; times d * (1 + 2 * 4-bit scale) +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + // the 512-entry grid in SLM, read by every lane: the global gather of it cost 2.4x the kernel + static constexpr int slm_bytes = 512 * sizeof(uint32_t); + static ESIMD_INLINE void init_slm() { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int i = 0; i < 512; i += 64) { + slm_block_store(i * 4, block_load(iq3s_grid + i)); + } + } + struct raw { + grouped_gemm_esimd::simd q; // [row][8 qs bytes] + grouped_gemm_esimd::simd qh; // the sub-block's qh byte + grouped_gemm_esimd::simd signs; // the sub-block's 32 sign bits + grouped_gemm_esimd::simd d; + }; + // d and the scale bytes are a block's, kept over its k steps; the sign dword and the qh byte of + // a k step are a 2D load each at that step's column, so no register is picked by a runtime index + struct sb_t { + grouped_gemm_esimd::simd d; + grouped_gemm_esimd::simd sc; // the 4 scale bytes + }; + // the SoA stream {d, scales} is d and scales of the block in AoS, which are not adjacent there: MS + // reads the scales at their SoA offset 2 in the stream, which is AoS offset 2 past 104 + static constexpr int META = QK_K / 4 + QK_K / 32 + QK_K / 8; + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 4, 2 }, QH = { QK_K / 4, QK_K / 32, 2 + QK_K / 4 }, + SG = { QK_K / 4 + QK_K / 32, QK_K / 8, 2 + QK_K / 4 + QK_K / 32 }, + MD = { META, 2 + IQ3S_N_SCALE, 0 }, + MS = { META, 2 + IQ3S_N_SCALE, META }; + // the SoA qh and signs streams are 2D surfaces: their row pitches must be 16-byte aligned + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || ((K / QK_K * 8) % 16 == 0 && K / QK_K * 8 >= 64)); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; + simd dh = s.u16(MD, ib, 0); + simd s0 = s.u16(MS, ib, 2); + simd s1 = s.u16(MS, ib, 4); + sb.d = simd(dh.template bit_cast_view()); + sb.sc = s0 | (s1 << 16); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + r.q = s.template rows<2>(QS, ib, 8 * j); + r.qh = (s.template rows<1>(QH, ib, 4 * (j / 4)) >> (8 * (j % 4))) & 0xffu; + r.signs = s.template rows<1>(SG, ib, 4 * j); + r.d = sb.d * simd(simd(1 + 2 * ((sb.sc >> (4 * j)) & 0xf))); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + // the 8 grid entries of each of the row group's rows + simd qb = + r.q.template select(g * GROUPED_GEMM_RC * 2).template bit_cast_view(); + simd qr = r.qh.template select(g * GROUPED_GEMM_RC); + simd qh = qr.template replicate_vs_w_hs(0); + simd j(0, 1); + j &= 7; + simd idx = simd(qb) | (((qh >> j) & 1) << 8); + simd ge = slm_gather(idx * 4); + return grid_signed(ge, r.signs.template select(g * GROUPED_GEMM_RC), + r.d.template select(g * GROUPED_GEMM_RC)); + } +}; + +// The K-quants and iq3_xxs: a 256-value superblock, k step j its sub-block j. Their value bytes for +// a k step are one rectangle of a stream, in k order after a shift and a mask per dword; scales, +// mins and d are the block's and are loaded once per block. + +// [qs 128][scales 12][dm]: value l of sub-block j is nibble j & 1 of byte 32 (j / 2) + l, times +// dall * scale_j, minus dmin * min_j (6-bit scale and min, get_scale_min_k4) +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d, m; + }; + struct sb_t { + grouped_gemm_esimd::simd sc[3]; // the 12 scale bytes + grouped_gemm_esimd::simd dall, dmin; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 2, 16 }, SC = { QK_K / 2, K_SCALE_SIZE, 4 }, + DM = { QK_K / 2 + K_SCALE_SIZE, 4, 0 }; + + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || grouped_gemm_esimd::surface_ok(K / 2)); + } + + template + static ESIMD_INLINE void load_sb(sb_t & sb, + const Sl & s, + const int ib, + const grouped_gemm_esimd::field & sc = SC, + const grouped_gemm_esimd::field & dmf = DM) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 3; ++w) { + sb.sc[w] = s.u32(sc, ib, 4 * w); + } + simd dm = s.u32(dmf, ib, 0); + auto dh = dm.template bit_cast_view(); + sb.dall = simd(dh.template select(0)); + sb.dmin = simd(dh.template select(1)); + } + // get_scale_min_k4 for sub-block j over the lanes + static ESIMD_INLINE void scale_min(sb_t & sb, + const int j, + grouped_gemm_esimd::simd & d, + grouped_gemm_esimd::simd & m) { + using namespace grouped_gemm_esimd; + simd sc, mb; + if (j < 4) { + sc = byte_of(sb.sc[0], j) & 63; + mb = byte_of(sb.sc[1], j) & 63; + } else { + sc = (byte_of(sb.sc[2], j - 4) & 0xf) | ((byte_of(sb.sc[0], j - 4) >> 6) << 4); + mb = (byte_of(sb.sc[2], j - 4) >> 4) | ((byte_of(sb.sc[1], j - 4) >> 6) << 4); + } + d = sb.dall * simd(sc); + m = sb.dmin * simd(mb); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + r.q = (s.template rows<8>(QS, kb / 8, 32 * (j / 2)) >> (4 * (j & 1))) & 0x0F0F0F0Fu; + scale_min(sb, j, r.d, r.m); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd d = r.d.template select(g * GROUPED_GEMM_RC), + m = r.m.template select(g * GROUPED_GEMM_RC); + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), d, m, d, m); + } +}; + +// [qs 128][qh 32][scales 12][dm]: q4_K plus bit j of qh byte l as 16 +template struct grouped_gemm_esimd_a { + using q4 = grouped_gemm_esimd_a; + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + using raw = typename q4::raw; + using sb_t = typename q4::sb_t; + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 2, 48 }, QH = { QK_K / 2, QK_K / 8, 16 }, + SC = { QK_K / 2 + QK_K / 8, K_SCALE_SIZE, 4 }, + DM = { QK_K / 2 + QK_K / 8 + K_SCALE_SIZE, 4, 0 }; + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || (grouped_gemm_esimd::surface_ok(K / 2) && grouped_gemm_esimd::surface_ok(K / 8))); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { q4::load_sb(sb, s, ib, SC, DM); } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + simd qh = s.template rows<8>(QH, ib, 0); + r.q = ((s.template rows<8>(QS, ib, 32 * (j / 2)) >> (4 * (j & 1))) & 0x0F0F0F0Fu) | + (((qh >> j) & 0x01010101u) << 4); + q4::scale_min(sb, j, r.d, r.m); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + return q4::template decode(r); + } +}; + +// [ql 128][qh 64][scales 16][d]: sub-block j is quarter r = j % 4 of half h = j / 4; value l is +// nibble r >> 1 of ql byte 64h + 32 (r & 1) + l with bits 2r, 2r+1 of qh byte 32h + l above it, +// minus 32, times d * the int8 scale 2j + l / 16 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d0, d1; // per k half + }; + struct sb_t { + grouped_gemm_esimd::simd sc[4]; // the 16 int8 scales + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QL = { 0, QK_K / 2, 0 }, QH = { QK_K / 2, QK_K / 4, QK_K / 2 }, + SC = { QK_K / 2 + QK_K / 4, QK_K / 16, QK_K / 2 + QK_K / 4 }, + D = { QK_K / 2 + QK_K / 4 + QK_K / 16, 2, + QK_K / 2 + QK_K / 4 + QK_K / 16 }; + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || (grouped_gemm_esimd::surface_ok(K / 2) && grouped_gemm_esimd::surface_ok(K / 4))); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 4; ++w) { + sb.sc[w] = s.u32(SC, ib, 4 * w); + } + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8, h = j / 4, q = j % 4; + simd ql = s.template rows<8>(QL, ib, 64 * h + 32 * (q & 1)); + simd qh = s.template rows<8>(QH, ib, 32 * h); + r.q = ((ql >> (4 * (q >> 1))) & 0x0F0F0F0Fu) | (((qh >> (2 * q)) & 0x03030303u) << 4); + // scales 2j and 2j + 1: bytes 2 (j % 2) and 2 (j % 2) + 1 of dword j / 2, sign extended + simd w = dword_of(sb.sc, j / 2); + simd s0 = simd(w << (24 - 16 * (j % 2))) >> 24; + simd s1 = simd(w << (16 - 16 * (j % 2))) >> 24; + r.d0 = sb.d * simd(s0); + r.d1 = sb.d * simd(s1); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd z = 0.0f; + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), + r.d0.template select(g * GROUPED_GEMM_RC), z, + r.d1.template select(g * GROUPED_GEMM_RC), z, 32.0f); + } +}; + +// [qs 64][scales 16][dm]: value l of sub-block j is bits 2 (j % 4) of byte 32 (j / 4) + l, times +// d * (scale & 15), minus dmin * (scale >> 4), scale byte 2j + l / 16 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d0, m0, d1, m1; + }; + struct sb_t { + grouped_gemm_esimd::simd sc[4]; + grouped_gemm_esimd::simd d, dmin; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 4, QK_K / 16 }, SC = { QK_K / 4, QK_K / 16, 0 }, + DM = { QK_K / 4 + QK_K / 16, 4, QK_K / 4 + QK_K / 16 }; + + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || grouped_gemm_esimd::surface_ok(K / 4)); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 4; ++w) { + sb.sc[w] = s.u32(SC, ib, 4 * w); + } + simd dm = s.u32(DM, ib, 0); + auto dh = dm.template bit_cast_view(); + sb.d = simd(dh.template select(0)); + sb.dmin = simd(dh.template select(1)); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + r.q = (s.template rows<8>(QS, kb / 8, 32 * (j / 4)) >> (2 * (j % 4))) & 0x03030303u; + simd w = dword_of(sb.sc, j / 2); + simd s0 = byte_of(w, 2 * (j % 2)), s1 = byte_of(w, 2 * (j % 2) + 1); + r.d0 = sb.d * simd(s0 & 0xf); + r.m0 = sb.dmin * simd(s0 >> 4); + r.d1 = sb.d * simd(s1 & 0xf); + r.m1 = sb.dmin * simd(s1 >> 4); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), + r.d0.template select(g * GROUPED_GEMM_RC), + r.m0.template select(g * GROUPED_GEMM_RC), + r.d1.template select(g * GROUPED_GEMM_RC), + r.m1.template select(g * GROUPED_GEMM_RC)); + } +}; + +// [qs 64][hmask 32][scales 12][d]: q2_K's 2 bits, minus 4 where bit j of hmask byte l is clear, +// times d * (6-bit scale - 32), scale s = 2j + l / 16 split over bytes s % 8 and 8 + s % 4 +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + static constexpr int slm_bytes = 0; + static ESIMD_INLINE void init_slm() {} + struct raw { + grouped_gemm_esimd::simd q; + grouped_gemm_esimd::simd d0, d1; + }; + struct sb_t { + grouped_gemm_esimd::simd sc[4]; // 12 scale bytes, sc[3] unused + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, QK_K / 4, QK_K / 8 }, HM = { QK_K / 4, QK_K / 8, 0 }, + SC = { QK_K / 4 + QK_K / 8, 12, QK_K / 4 + QK_K / 8 }, + D = { QK_K / 4 + QK_K / 8 + 12, 2, QK_K / 4 + QK_K / 8 + 12 }; + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || (grouped_gemm_esimd::surface_ok(K / 4) && grouped_gemm_esimd::surface_ok(K / 8))); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int w = 0; w < 3; ++w) { + sb.sc[w] = s.u32(SC, ib, 4 * w); + } + sb.sc[3] = 0; + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + } + + static ESIMD_INLINE grouped_gemm_esimd::simd scale(sb_t & sb, const int sidx) { + using namespace grouped_gemm_esimd; + simd lo = (byte_of(dword_of(sb.sc, (sidx % 8) / 4), sidx % 4) >> (4 * (sidx / 8))) & 0xf; + simd hi = (byte_of(sb.sc[2], sidx % 4) >> (2 * (sidx / 4))) & 3; + return sb.d * simd(simd(lo | (hi << 4)) - 32); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + simd hm = s.template rows<8>(HM, ib, 0); + r.q = ((s.template rows<8>(QS, ib, 32 * (j / 4)) >> (2 * (j % 4))) & 0x03030303u) | + (((hm >> j) & 0x01010101u) << 2); + r.d0 = scale(sb, 2 * j); + r.d1 = scale(sb, 2 * j + 1); + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd z = 0.0f; + return halves_dm(r.q.template select(g * GROUPED_GEMM_RC * 8), + r.d0.template select(g * GROUPED_GEMM_RC), z, + r.d1.template select(g * GROUPED_GEMM_RC), z, 4.0f); + } +}; + +// [qs 96][d]: per sub-block j, 8 grid indices at 8j and an aux dword at 64 + 4j whose 4 x 7 bits +// are sign bytes of ksigns_iq2xs and whose top 4 bits scale d * (0.5 + s) * 0.5. ksigns_iq2xs[i] is +// i with the parity of its 7 bits as bit 7, so the sign bytes are computed, not looked up. +template struct grouped_gemm_esimd_a { + static constexpr bool supported = true; + static constexpr int qk = QK_K; + static constexpr bool whole = false; + // the 256-entry grid, a read-only table in SLM + static constexpr int slm_bytes = 256 * sizeof(uint32_t); + static ESIMD_INLINE void init_slm() { + using namespace grouped_gemm_esimd; +#pragma unroll + for (int i = 0; i < 256; i += 64) { + slm_block_store(i * 4, block_load(iq3xxs_grid + i)); + } + } + struct raw { + grouped_gemm_esimd::simd q; // [row][8 grid indices] + grouped_gemm_esimd::simd aux; + grouped_gemm_esimd::simd d; + }; + struct sb_t { + grouped_gemm_esimd::simd d; + }; + + static constexpr grouped_gemm_esimd::field QS = { 0, 3 * QK_K / 8, 2 }, D = { 3 * QK_K / 8, 2, 0 }; + + static bool ok(const int K, const bool aos) { + return K % qk == 0 && (aos || grouped_gemm_esimd::surface_ok(K / QK_K * 96)); + } + template static ESIMD_INLINE void load_sb(sb_t & sb, const Sl & s, const int ib) { + using namespace grouped_gemm_esimd; + simd dh = s.u16(D, ib, 0); + sb.d = simd(dh.template bit_cast_view()); + } + template static ESIMD_INLINE void load(raw & r, sb_t & sb, const Sl & s, const int kb, const int j) { + using namespace grouped_gemm_esimd; + const int ib = kb / 8; + r.q = s.template rows<2>(QS, ib, 8 * j); + r.aux = s.template rows<1>(QS, ib, 64 + 4 * j); + r.d = sb.d * (0.5f + simd(r.aux >> 28)) * 0.5f; + } + + template static ESIMD_INLINE grouped_gemm_esimd::a_halves decode(raw & r) { + using namespace grouped_gemm_esimd; + simd qb = + r.q.template select(g * GROUPED_GEMM_RC * 2).template bit_cast_view(); + simd ge = slm_gather(qb * 4); + simd ax = r.aux.template select(g * GROUPED_GEMM_RC); + simd sg = 0; +#pragma unroll + for (int il = 0; il < 4; ++il) { + simd si = (ax >> (7 * il)) & 127; + sg |= (si | ((cbit(si) & 1) << 7)) << (8 * il); + } + return grid_signed(ge, sg, r.d.template select(g * GROUPED_GEMM_RC)); + } +}; + +// T is the dpas operand type, sycl::half or bfloat16: the type B is packed in. A is decoded in half +// either way and converted for bf16 (see the double rounding note at the conversion). AOS: the weight +// is in the canonical block layout rather than the reorder (SoA) one. A: the grouped_gemm_arch built for. +template struct grouped_gemm_esimd_kernel { + using F = grouped_gemm_esimd_a; + + const char * src0_dd; + size_t expert_stride; + const ggml_sycl_grouped_gemm_tile * tiles; + const T * packed; + float * dst; + int M; + int Npad; + int K; + ggml_sycl_grouped_gemm_rows dst_rows; + + void operator()(sycl::nd_item<1> it) const SYCL_ESIMD_KERNEL { + if constexpr (grouped_gemm_built()) { + run(it); + } + } + + ESIMD_INLINE void run(sycl::nd_item<1> it) const { + using namespace sycl::ext::intel::esimd; + namespace xmx = sycl::ext::intel::esimd::xmx; + constexpr int MR = A::MR; + constexpr int NW = A::NW; + constexpr int RC = GROUPED_GEMM_RC; + constexpr int RG = MR / RC; // dpas row groups of this thread + constexpr int BN = GGML_SYCL_GROUPED_GEMM_BN; + constexpr int NT = BN / NW; + + if constexpr (F::slm_bytes > 0) { + // the format's lookup table; a work-group is one thread, so nothing else writes it + slm_init(); + F::init_slm(); + } + + const int mblocks = M / MR; + const int gid = it.get_global_id(0); + const int t = gid / mblocks; + const int m0 = (gid % mblocks) * MR; + + const ggml_sycl_grouped_gemm_tile tile = tiles[t]; + if (tile.n1 <= tile.n0) { + return; + } + const int b0 = t * BN; // the tile's packed-B columns + + // the slice of this expert + const int bpr = K / F::qk; + const grouped_gemm_esimd::slice sl = { + (const uint8_t *) src0_dd + (size_t) tile.expert * expert_stride, + M, + bpr, + M * bpr, + m0, + AOS, + (int) sizeof(block_q_t) + }; + const uint32_t * bp = (const uint32_t *) packed; + const unsigned bw = (unsigned) Npad * 4; // bytes of one packed B row + const int nstep = K / GROUPED_GEMM_QK; + + simd acc[RG][NT]; + simd total[KS > 1 ? RG : 1][KS > 1 ? NT : 1]; +#pragma unroll + for (int g = 0; g < RG; ++g) { +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + acc[g][nt] = 0.0f; + if constexpr (KS > 1) { + total[g][nt] = 0.0f; + } + } + } + + // The tile's route map, gathered once up front; the K loop hides its latency, and the epilogue + // below reads it at compile-time indices. + const int ncols = tile.n1 - tile.n0; + simd_mask cm = simd(0, 1) < ncols; + simd i2 = 0, r1 = 0; // r1: the dst row slot, i1 % ne1 + if (dst_rows.map) { + const int32_t * mp = (const int32_t *) (dst_rows.map + tile.n0); + simd mo(0, sizeof(mmid_row_mapping)); + simd i1 = gather(mp, mo, cm); + i2 = gather(mp + 1, mo, cm); + // once per thread in 32 bits: a 64-bit modulo per column is emulated, and at 20 columns a + // tile it cost more than the whole GEMM (7.2 vs 3.1 ms) + r1 = i1 % simd((int32_t) dst_rows.ne1); + } + + // One k step at a time: the format's stored bits for the MR rows, and the 16 k pairs x NW + // columns of packed B per dpas column tile, one 2D block message each (without 2D loads, one + // block load per packed row, cut into the tiles in registers). A second stage in + // flight spilled 7 KB of the 256 registers and ran 1.6x slower; the other threads of the + // XVE hide the load latency instead. + // A stored block's metadata (its sub-block scales) is loaded once per block. With KS > 1 the + // K split of the joint_matrix kernel is reproduced for bit-identical output (a second set of + // accumulators); KS == 1 sums the whole K in one, which is a different f32 rounding order and + // frees the 4 KB of registers the second set holds. + constexpr int KPB = F::qk / GROUPED_GEMM_QK; // k steps per stored block + int split = 0; + int split_end = KS > 1 ? nstep / KS : nstep; + typename F::sb_t sb; + for (int kb = 0; kb < nstep; ++kb) { + const int j = kb % KPB; + if (j == 0) { + F::load_sb(sb, sl, kb / KPB); + } + typename F::raw r; + F::load(r, sb, sl, kb, j); + simd b[NT]; // [16 k pairs][NW columns] each + if constexpr (A::L2D) { +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + b[nt] = load_2d(bp, bw - 1, K / 2 - 1, bw - 1, b0 + nt * NW, kb * 16); + } + } else { + simd bm; +#pragma unroll + for (int r = 0; r < 16; ++r) { + bm.template select(r * BN) = + block_load(bp + (size_t) (kb * 16 + r) * Npad + b0, overaligned_tag<16>{}); + } + auto bv = bm.template bit_cast_view(); +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + b[nt] = bv.template select<16, 1, NW, 1>(0, nt * NW); + } + } + simd all; + if constexpr (F::whole) { + all = F::decode_all(r); + } + // one row group of the thread, g a compile-time constant: with a runtime g the larger + // decodes were left rolled + auto row_group = [&](auto gc) SYCL_ESIMD_FUNCTION { + constexpr int g = decltype(gc)::value; + grouped_gemm_esimd::a_halves av; + if constexpr (F::whole) { + // [row][32 k] of the whole tile to this row group's [k half][row][16 k] + auto am = all.template bit_cast_view(); + av.template select(0) = am.template select(g * RC, 0); + av.template select(RC * 16) = am.template select(g * RC, 16); + } else { + av = F::template decode(r); + } +#pragma unroll + for (int h = 0; h < 2; ++h) { + // A of this k16 half: rows x k [16h, 16h+16), row major + simd ah = av.template select(h * RC * 16); + simd at; + if constexpr (std::is_same_v) { + at = ah; + } else { + // rounded twice (f32 to half in the decode, half to bf16 here), so A's rounding + // error is about twice the joint_matrix bf16 stage's, which rounds f32 once + at = simd(ah); + } +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + simd bh32 = b[nt].template select<8 * NW, 1>(h * 8 * NW); + simd bh = bh32.template bit_cast_view(); + acc[g][nt] = xmx::dpas<8, RC, float, float>(acc[g][nt], bh, at); + } + } + }; + grouped_gemm_esimd::static_for<0, RG>::run(row_group); + if constexpr (KS > 1) { + // the K split's range ends, in k steps; a range's partial joins the total when it closes + if (kb + 1 == split_end) { +#pragma unroll + for (int g = 0; g < RG; ++g) { +#pragma unroll + for (int nt = 0; nt < NT; ++nt) { + total[g][nt] += acc[g][nt]; + acc[g][nt] = 0.0f; + } + } + ++split; + split_end = ((split + 1) * nstep) / KS; + } + } + } + (void) split; + (void) split_end; + + // column c of the tile: MR consecutive floats of one dst row. Unrolled, so c indexes the + // accumulators at compile time; a runtime index sends them all to private memory. +#pragma unroll + for (int c = 0; c < BN; ++c) { + if (c >= ncols) { + continue; + } + simd col; +#pragma unroll + for (int g = 0; g < RG; ++g) { + if constexpr (KS > 1) { + col.template select(g * RC) = total[g][c / NW].template select(c % NW); + } else { + col.template select(g * RC) = acc[g][c / NW].template select(c % NW); + } + } + const int n = tile.n0 + c; + if (dst_rows.map) { + float * out = (float *) (dst_rows.base + (size_t) r1[c] * dst_rows.nb1 + i2[c] * dst_rows.nb2) + m0; + block_store(out, col, element_aligned_tag{}); + } else { + block_store(dst + (size_t) n * M + m0, col, element_aligned_tag{}); + } + } + } + + auto get(syclexp::properties_tag) const { return syclexp::properties{ sycl::ext::intel::experimental::grf_size<256> }; } +}; + +// the weights' surfaces: 2D block loads (SoA with L2D) want 64-byte aligned bases, the dword gathers 4 +static bool grouped_gemm_esimd_weights_ok(const char * w, const size_t expert_stride, const bool l2d) { + const size_t a = l2d ? 64 : 4; + return (uintptr_t) w % a == 0 && expert_stride % a == 0; +} + +// 0 off, 1 on (default), 2 on with the joint_matrix kernel's K-split order reproduced (bit-identical output) +static int ggml_sycl_grouped_gemm_esimd_mode() { + return g_ggml_sycl_mmid_esimd; +} + +bool ggml_sycl_grouped_gemm_esimd_enabled() { +#if defined(GGML_SYCL_SUPPORT_XMX) + return g_ggml_sycl_enable_esimd && ggml_sycl_grouped_gemm_esimd_mode() != 0; +#else + return false; +#endif +} + +template +static void grouped_gemm_esimd_launch(const char * src0_dd, + size_t expert_stride, + const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, + float * dst, + int M, + int Npad, + int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, + int64_t n_tiles, + dpct::queue_ptr stream) { + const sycl::nd_range<1> range((size_t) n_tiles * (M / A::MR), 1); + if (ggml_sycl_grouped_gemm_esimd_mode() == 2) { + stream->parallel_for(range, grouped_gemm_esimd_kernel{ + src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, dst_rows }); + } else { + stream->parallel_for(range, grouped_gemm_esimd_kernel{ + src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, dst_rows }); + } +} + +template +static bool grouped_gemm_esimd_run(const char * src0_dd, + size_t expert_stride, + const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, + float * dst, + int M, + int Npad, + int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, + bool reordered, + int64_t n_tiles, + dpct::queue_ptr stream) { + using F = grouped_gemm_esimd_a; + // whole row groups and stored blocks, every K-split range non-empty (also in mode 1, so both + // modes take the same shapes); B is read with 2D block loads, which want 64-byte aligned + // surfaces and pitches, or with 16-byte aligned block loads of whole tiles + if (M % A::MR != 0 || !F::ok(K, !reordered) || K < GROUPED_GEMM_QK * GGML_SYCL_GROUPED_GEMM_KSPLIT || + !grouped_gemm_esimd_weights_ok(src0_dd, expert_stride, reordered && A::L2D) || ((uintptr_t) packed % 64) != 0 || + Npad % 16 != 0) { + return false; + } + if (reordered) { + grouped_gemm_esimd_launch(src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, + dst_rows, n_tiles, stream); + } else { + grouped_gemm_esimd_launch(src0_dd, expert_stride, tiles, packed, dst, M, Npad, K, + dst_rows, n_tiles, stream); + } + return true; +} + +template +bool ggml_sycl_grouped_gemm_esimd(const char * src0_dd, + size_t expert_stride, + const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, + float * dst, + int M, + int Npad, + int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, + bool reordered, + int64_t n_tiles, + dpct::queue_ptr stream) { + static_assert(grouped_gemm_esimd_a::supported == ggml_sycl_grouped_gemm_esimd_has, + "the header's format list and the formats implemented here must agree"); + static_assert(NW == 8 || NW == 16, "the dpas widths of Xe-HPG and of Xe2 / Xe-HPC"); + if constexpr (NW == 16) { + return grouped_gemm_esimd_run(src0_dd, expert_stride, tiles, packed, dst, M, + Npad, K, dst_rows, reordered, n_tiles, stream); + } else { + return grouped_gemm_esimd_run(src0_dd, expert_stride, tiles, packed, dst, M, + Npad, K, dst_rows, reordered, n_tiles, stream); + } +} + +#define GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, T, NW) \ + template bool ggml_sycl_grouped_gemm_esimd( \ + const char *, size_t, const ggml_sycl_grouped_gemm_tile *, const T *, float *, int, int, int, \ + const ggml_sycl_grouped_gemm_rows &, bool, int64_t, dpct::queue_ptr); +#define GROUPED_GEMM_ESIMD_INSTANCE(block_q_t) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::half, 16) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::ext::oneapi::bfloat16, 16) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::half, 8) \ + GROUPED_GEMM_ESIMD_INSTANCE_T(block_q_t, sycl::ext::oneapi::bfloat16, 8) +GROUPED_GEMM_ESIMD_INSTANCE(block_q8_0) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq4_nl) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq4_xs) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq3_s) +GROUPED_GEMM_ESIMD_INSTANCE(block_iq3_xxs) +GROUPED_GEMM_ESIMD_INSTANCE(block_q3_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q2_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q6_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q5_K) +GROUPED_GEMM_ESIMD_INSTANCE(block_q4_K) diff --git a/ggml/src/ggml-sycl/fused-gemm-esimd.hpp b/ggml/src/ggml-sycl/fused-gemm-esimd.hpp new file mode 100644 index 000000000000..029d19480624 --- /dev/null +++ b/ggml/src/ggml-sycl/fused-gemm-esimd.hpp @@ -0,0 +1,33 @@ +#ifndef GGML_SYCL_FUSED_GEMM_ESIMD_HPP +#define GGML_SYCL_FUSED_GEMM_ESIMD_HPP + +#include "fused-gemm.hpp" + +// The grouped (MUL_MAT_ID) dequant GEMM, written with ESIMD so the dequantized weights go from +// registers straight into the dpas A operand: no SLM, no barrier. Same inputs and outputs as the +// joint_matrix grouped kernel of the 8 x NW x 16 sub-group-NW combination of T (sycl::half or +// bfloat16): NW = 16 on Xe2 and Xe-HPC, 8 on Xe-HPG (Arc A, ARL-H). The schedule's tiles, B packed as +// [K/2][Npad][2] T, and dst through dst_rows. The weight is in the reorder (SoA) layout if +// `reordered`, else in the canonical block layout. Returns false when the shape is not covered. +template +constexpr bool ggml_sycl_grouped_gemm_esimd_has = std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v; + +template +bool ggml_sycl_grouped_gemm_esimd(const char * src0_dd, size_t expert_stride, const ggml_sycl_grouped_gemm_tile * tiles, + const T * packed, float * dst, int M, int Npad, int K, + const ggml_sycl_grouped_gemm_rows & dst_rows, bool reordered, int64_t n_tiles, + dpct::queue_ptr stream); + +// GGML_SYCL_MMID_ESIMD: 1 (default) takes the ESIMD kernel above where it applies, 0 never does +bool ggml_sycl_grouped_gemm_esimd_enabled(); + +#endif // GGML_SYCL_FUSED_GEMM_ESIMD_HPP diff --git a/ggml/src/ggml-sycl/fused-gemm.cpp b/ggml/src/ggml-sycl/fused-gemm.cpp index 803a994c04bb..d0525e3a0bb8 100644 --- a/ggml/src/ggml-sycl/fused-gemm.cpp +++ b/ggml/src/ggml-sycl/fused-gemm.cpp @@ -1,4 +1,5 @@ #include "fused-gemm.hpp" +#include "fused-gemm-esimd.hpp" #include @@ -17,7 +18,6 @@ namespace mx = sycl::ext::oneapi::experimental::matrix; // superblock into steps of this width. The sub-groups of a work-group each walk their own K range // and are summed at the end. static constexpr int FG_BK = QK4_NL; -static constexpr int FG_KSPLIT = 4; // Element traits of one joint_matrix operand type. The A stage and the B pack compute in f32 and // convert once, in registers, when they write the element, so any type costs the same one pass. @@ -113,6 +113,15 @@ using fg_half = sycl::half; using fg_bf16 = sycl::ext::oneapi::bfloat16; using fg_tf32 = mx::precision::tf32; +// The combinations the ESIMD grouped GEMM (fused-gemm-esimd.cpp) stands in for: 8 x SG x 16 with f16 +// or bf16 operands, the shape of one dpas, on sub-group 16 (Xe2, Xe-HPC) or 8 (Xe-HPG). Its B is +// packed and tiled as theirs is. +template static constexpr bool fg_esimd_combo() { + return S::TM == 8 && S::TN == S::SG && S::TK == 16 && (S::SG == 16 || S::SG == 8) && + std::is_same_v && + (std::is_same_v || std::is_same_v); +} + // One bit of GGML_SYCL_XMX_GATHER_SHAPES per combination. Only combinations some device lists in // matrix_combinations are built (appendix of sycl_ext_oneapi_matrix and the runtime's own list). template static void fg_visit_combo(int idx, F && f); @@ -152,29 +161,7 @@ template static void fg_visit_combo(int idx, F && f) { // size, since IGC fails on the other ones. A JIT build keeps them all, but each combination lands in // its own device image (joint_matrix is an optional kernel feature) and only a combination the // device reports is launched, so the runtime never asks IGC for the others. -#if defined(__SYCL_DEVICE_ONLY__) -# if __SYCL_TARGET_INTEL_GPU_ACM_G10__ || __SYCL_TARGET_INTEL_GPU_ACM_G11__ || __SYCL_TARGET_INTEL_GPU_ACM_G12__ || \ - __SYCL_TARGET_INTEL_GPU_ARL_H__ -# define FG_AOT_SG 8 -# elif __SYCL_TARGET_INTEL_GPU_PVC__ || __SYCL_TARGET_INTEL_GPU_PVC_VG__ || __SYCL_TARGET_INTEL_GPU_BMG_G21__ || \ - __SYCL_TARGET_INTEL_GPU_BMG_G31__ || __SYCL_TARGET_INTEL_GPU_LNL_M__ || __SYCL_TARGET_INTEL_GPU_PTL_H__ || \ - __SYCL_TARGET_INTEL_GPU_PTL_U__ || __SYCL_TARGET_INTEL_GPU_WCL__ || __SYCL_TARGET_INTEL_GPU_NVL_S__ || \ - __SYCL_TARGET_INTEL_GPU_NVL_U__ || __SYCL_TARGET_INTEL_GPU_NVL_P__ -# define FG_AOT_SG 16 -# elif __SYCL_TARGET_INTEL_GPU_TGLLP__ || __SYCL_TARGET_INTEL_GPU_RKL__ || __SYCL_TARGET_INTEL_GPU_ADL_S__ || \ - __SYCL_TARGET_INTEL_GPU_ADL_P__ || __SYCL_TARGET_INTEL_GPU_ADL_N__ || __SYCL_TARGET_INTEL_GPU_DG1__ || \ - __SYCL_TARGET_INTEL_GPU_MTL_U__ || __SYCL_TARGET_INTEL_GPU_MTL_H__ -# define FG_AOT_SG 0 // no XMX -# endif -#endif - -template static constexpr bool fg_built() { -#if defined(FG_AOT_SG) - return SG == FG_AOT_SG; -#else - return true; -#endif -} +// (FG_AOT_SG is defined in fused-gemm.hpp, which the ESIMD kernels share) // Upper bound on the tile count when total_rows rows are routed to n_as experts: the worst case gives // each expert one row and fills whole tiles with the rest. The bound depends only on the shape, not @@ -991,6 +978,15 @@ static void grouped_dequant_gemm_launch(const char * src0_dd, const size_t exper float * dst, const int M, const int Npad, const int K, const int64_t n_tiles, const int64_t groups_m, dpct::queue_ptr stream, ggml_sycl_grouped_gemm_rows dst_rows = {}) { + if constexpr (fg_esimd_combo() && ggml_sycl_grouped_gemm_esimd_has) { + // the register-operand ESIMD kernel, either weight layout: no SLM A image (GGML_SYCL_MMID_ESIMD) + if (ggml_sycl_grouped_gemm_esimd_enabled() && + ggml_sycl_grouped_gemm_esimd(src0_dd, expert_stride, tiles_ptr, packed, + dst, M, Npad, K, dst_rows, reordered, + n_tiles, stream)) { + return; + } + } stream->submit([&](sycl::handler & cgh) { sycl::local_accessor tile_a(FG_KSPLIT * S::SG_ROWS * FG_BK, cgh); sycl::local_accessor tile_c(FG_KSPLIT * S::SG_ROWS * S::BN, cgh); @@ -1087,6 +1083,45 @@ template static bool fg_visit_type(ggml_type type, bool reordered, } } +// The ESIMD grouped GEMM loads A straight into its dpas operands, so the joint_matrix tile shape +// means nothing to it; it runs on the fg_esimd_combo of the picked operand type and sub-group size. A +// grouped call whose weight it covers is moved there from any other shape of that type and sub-group +// size, if the device lists it, whatever GGML_SYCL_XMX_GATHER_SHAPES allows: the shape bits choose +// among joint_matrix tiles. +// A call the ESIMD kernel then declines (a shape it does not take) runs that combination's joint_matrix +// kernel. +static int fg_esimd_remap(dpct::queue_ptr stream, int combo, ggml_type src0_type, bool reordered) { + if (combo < 0 || !ggml_sycl_grouped_gemm_esimd_enabled()) { + return combo; + } + bool covered = false; + fg_visit_type(src0_type, reordered, [&](auto tag) { + using T = decltype(tag); + covered = ggml_sycl_grouped_gemm_esimd_has; + }); + if (!covered) { + return combo; + } + int target = -1; + fg_visit_combo(combo, [&](auto s) { + using S = decltype(s); + if constexpr (std::is_same_v) { + for (int idx = 0; idx < FG_N_COMBOS; ++idx) { + fg_visit_combo(idx, [&](auto t) { + using U = decltype(t); + if constexpr (fg_esimd_combo() && U::SG == S::SG && std::is_same_v) { + target = idx; + } + }); + } + } + }); + if (target < 0 || target == combo || !(fg_device_combos(stream->get_device()) & (1 << target))) { + return combo; + } + return target; +} + template static bool fg_fused_run(ggml_type src0_type, bool src0_reordered, const void * src0, const void * src1, ggml_type src1_type, float * dst, int64_t M, int64_t N, int64_t K, int64_t ldd, ggml_sycl_pool & pool, @@ -1201,7 +1236,7 @@ bool ggml_sycl_grouped_dequant_gemm(ggml_type src0_type, bool reordered, const v if (!ggml_sycl_grouped_dequant_gemm_shape_ok(src0_type, M, K, total_rows, n_active)) { return false; } - const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec); + const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered); if (combo < 0) { return false; } @@ -1407,7 +1442,7 @@ bool ggml_sycl_grouped_dequant_gemm_device_supported(ggml_type src0_type, bool r if (grouped_gemm_max_tiles(total_rows, n_as, GGML_SYCL_FG_BN) > INT32_MAX / GGML_SYCL_FG_BN) { return false; } - const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec); + const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered); if (combo < 0) { return false; } @@ -1428,7 +1463,7 @@ bool ggml_sycl_grouped_dequant_gemm_device(ggml_type src0_type, bool reordered, n_tokens, M, K, stream)) { return false; } - const int combo = fg_pick_combo(stream, GGML_TYPE_F32, src1_prec); + const int combo = fg_esimd_remap(stream, fg_pick_combo(stream, GGML_TYPE_F32, src1_prec), src0_type, reordered); bool launched = false; fg_visit_combo(combo, [&](auto s) { launched = fg_grouped_device_run(src0_type, reordered, src0_base, expert_stride, src1, dst, diff --git a/ggml/src/ggml-sycl/fused-gemm.hpp b/ggml/src/ggml-sycl/fused-gemm.hpp index 0e807a2c0ab9..e65e98fc8726 100644 --- a/ggml/src/ggml-sycl/fused-gemm.hpp +++ b/ggml/src/ggml-sycl/fused-gemm.hpp @@ -13,7 +13,34 @@ struct ggml_sycl_grouped_gemm_rows { size_t nb2; }; +// AOT: the sub-group size of the XMX combinations of the target, 0 for a target without XMX. +// Undefined in a JIT build, which keeps every combination. +#if defined(__SYCL_DEVICE_ONLY__) +# if __SYCL_TARGET_INTEL_GPU_ACM_G10__ || __SYCL_TARGET_INTEL_GPU_ACM_G11__ || __SYCL_TARGET_INTEL_GPU_ACM_G12__ || \ + __SYCL_TARGET_INTEL_GPU_ARL_H__ +# define FG_AOT_SG 8 +# elif __SYCL_TARGET_INTEL_GPU_PVC__ || __SYCL_TARGET_INTEL_GPU_PVC_VG__ || __SYCL_TARGET_INTEL_GPU_BMG_G21__ || \ + __SYCL_TARGET_INTEL_GPU_BMG_G31__ || __SYCL_TARGET_INTEL_GPU_LNL_M__ || __SYCL_TARGET_INTEL_GPU_PTL_H__ || \ + __SYCL_TARGET_INTEL_GPU_PTL_U__ || __SYCL_TARGET_INTEL_GPU_WCL__ || __SYCL_TARGET_INTEL_GPU_NVL_S__ || \ + __SYCL_TARGET_INTEL_GPU_NVL_U__ || __SYCL_TARGET_INTEL_GPU_NVL_P__ +# define FG_AOT_SG 16 +# elif __SYCL_TARGET_INTEL_GPU_TGLLP__ || __SYCL_TARGET_INTEL_GPU_RKL__ || __SYCL_TARGET_INTEL_GPU_ADL_S__ || \ + __SYCL_TARGET_INTEL_GPU_ADL_P__ || __SYCL_TARGET_INTEL_GPU_ADL_N__ || __SYCL_TARGET_INTEL_GPU_DG1__ || \ + __SYCL_TARGET_INTEL_GPU_MTL_U__ || __SYCL_TARGET_INTEL_GPU_MTL_H__ +# define FG_AOT_SG 0 // no XMX +# endif +#endif + +template static constexpr bool fg_built() { +#if defined(FG_AOT_SG) + return SG == FG_AOT_SG; +#else + return true; +#endif +} + static constexpr int GGML_SYCL_FG_BN = 32; +static constexpr int FG_KSPLIT = 4; static constexpr int64_t GGML_SYCL_MMID_SCHED_MAX_EXPERTS = 4096; // Shape and type gates for the kernels below. Device capability is separate: it needs a queue to ask. diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 9da436ced3c1..5b87fa024d5f 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -111,6 +111,7 @@ int g_ggml_sycl_memtrace_step = 64; int g_ggml_sycl_enable_vmm = 1; int g_ggml_sycl_enable_fusion = 1; int g_ggml_sycl_enable_esimd = 1; +int g_ggml_sycl_mmid_esimd = 1; int g_ggml_sycl_mmvq_wide = 1; int g_ggml_sycl_enable_xmx_esimd = 1; int g_ggml_sycl_xmx_max_cols = GGML_SYCL_XMX_MAX_COLS_DEFAULT; @@ -444,6 +445,7 @@ static void ggml_check_sycl() try { g_ggml_sycl_enable_vmm = ggml_sycl_get_env("GGML_SYCL_ENABLE_VMM", 1); g_ggml_sycl_enable_fusion = ggml_sycl_get_env("GGML_SYCL_ENABLE_FUSION", 1); g_ggml_sycl_enable_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_ESIMD", 1); + g_ggml_sycl_mmid_esimd = ggml_sycl_get_env("GGML_SYCL_MMID_ESIMD", 1); g_ggml_sycl_mmvq_wide = ggml_sycl_get_env("GGML_SYCL_MMVQ_WIDE", 1); g_ggml_sycl_enable_xmx_esimd = ggml_sycl_get_env("GGML_SYCL_ENABLE_XMX_ESIMD", 1); g_ggml_sycl_xmx_max_cols = std::max(0, ggml_sycl_get_env("GGML_SYCL_XMX_MAX_COLS", GGML_SYCL_XMX_MAX_COLS_DEFAULT)); @@ -578,6 +580,7 @@ static void ggml_check_sycl() try { GGML_LOG_INFO(" GGML_SYCL_ENABLE_OPT: %d\n", g_ggml_sycl_enable_optimize); GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_TYPES: %d\n", g_ggml_sycl_xmx_gather_types); GGML_LOG_INFO(" GGML_SYCL_MMID_SCHED: %d\n", g_ggml_sycl_mmid_sched); + GGML_LOG_INFO(" GGML_SYCL_MMID_ESIMD: %d\n", g_ggml_sycl_mmid_esimd); GGML_LOG_INFO(" GGML_SYCL_XMX_GATHER_SHAPES: %d\n", g_ggml_sycl_xmx_gather_shapes); GGML_LOG_INFO(" GGML_SYCL_DYNAMIC_PRECISION: %s\n", ggml_sycl_dynamic_precision_names[g_ggml_sycl_dynamic_precision]); From 6792507b7f611a6fc68bfae3eeae85e88017fc60 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Sat, 21 Nov 2026 13:22:36 +0800 Subject: [PATCH 008/401] llama : score only the k-pools of the ubatch sequences in QSA (#32519) --- src/llama-memory-hybrid-idx.cpp | 57 +++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 20 deletions(-) diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp index 2e19576f19fe..0199c734e341 100644 --- a/src/llama-memory-hybrid-idx.cpp +++ b/src/llama-memory-hybrid-idx.cpp @@ -353,6 +353,7 @@ struct llama_memory_hybrid_idx_context::kpool_state { uint32_t generation = 0; uint32_t n_pool_real = 0; + uint32_t n_pool_ub = 0; // pools of the ubatch's sequences, the only ones the indexer scores uint32_t n_new = 0; uint32_t n_new_g = 1; // graph size of the new pool list, stable across decode steps }; @@ -496,6 +497,7 @@ llama_memory_hybrid_idx_context::llama_memory_hybrid_idx_context(llama_memory_hy const uint64_t n_pool_max = uint64_t(idx->get_size() / mem->get_kpool()) * idx->get_n_seq_max(); GGML_ASSERT(n_pool_max <= UINT32_MAX - 64); st.n_pool_real = std::max(st.n_pool_real, uint32_t(n_pool_max)); + st.n_pool_ub = st.n_pool_real; st.n_new = st.n_pool_real; st.n_new_g = std::max(st.n_new, 1u); kpool_st = std::make_unique(std::move(st)); @@ -687,6 +689,12 @@ void llama_memory_hybrid_idx_context::kpool_build_state(const llama_ubatch & uba } GGML_ASSERT(ip == st.is_new.size()); + // the indexer scores only the pools of the ubatch's sequences + st.n_pool_ub = 0; + for (uint32_t i = 0; i < ubatch.n_seqs_unq; ++i) { + st.n_pool_ub += (uint32_t) lay.seqs[ubatch.seq_id_unq[i]].pools.size(); + } + // in order mode a token's cell gives its rank, and the rank its pool: positions cannot, as an image shares one const bool by_order = mem->get_kpool_by_order(); const auto * sinfo = by_order ? &sinfos_kpool[i_cur] : nullptr; @@ -731,7 +739,7 @@ const llama_memory_hybrid_idx_context::kpool_state & llama_memory_hybrid_idx_con } uint32_t llama_memory_hybrid_idx_context::get_n_kpool() const { - return kpool_pad(kpool_cur().n_pool_real); + return kpool_pad(kpool_cur().n_pool_ub); } uint32_t llama_memory_hybrid_idx_context::get_n_kpool_new() const { @@ -761,7 +769,7 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, const bool by_order = mem->get_kpool_by_order(); - GGML_ASSERT(n_pool == kpool_pad(st.n_pool_real)); + GGML_ASSERT(n_pool == kpool_pad(st.n_pool_ub)); GGML_ASSERT(st.is_new.size() == st.n_pool_real); GGML_ASSERT(pool_mask->ne[0] == (int64_t) n_pool && pool_mask->ne[1] == (int64_t) n_tokens); GGML_ASSERT(tail_idxs->ne[0] == (int64_t) kpool - 1 && tail_idxs->ne[1] == (int64_t) n_tokens); @@ -783,7 +791,7 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, return (int64_t) sq.strm*kv_size + cell; }; - // Sequences present in this ubatch, pools of absent sequences must fall on the scatter sentinel row. + // Sequences present in this ubatch, only their pools are scored. std::vector seq_in_ub(LLAMA_MAX_SEQ, 0); for (uint32_t i = 0; i < n_tokens; ++i) { for (int32_t k = 0; k < ubatch->n_seq_id[i]; ++k) { @@ -846,27 +854,26 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, std::fill(npos, npos + 4*n_new_g, 0); } - uint32_t i_new = 0; + // the reps of all pools, the padded new entries must not write them + const int64_t n_cells = (int64_t) kv_size*n_stream_kv; + std::vector is_rep(n_new_g > n_new ? n_cells : 0, 0); + + uint32_t i_new = 0; + uint32_t ip_all = 0; for (llama_seq_id s = 0; s < LLAMA_MAX_SEQ; ++s) { const auto & sq = lay.seqs[s]; seq_pool_start[s] = (uint32_t) pool_end.size(); - const bool inert = n_stream_kv > 1 && !seq_in_ub[s]; - - for (size_t pi = 0; pi < sq.pools.size(); ++pi) { - const uint32_t j = sq.pools[pi]; - const uint32_t ip = (uint32_t) pool_end.size(); - GGML_ASSERT(ip + 1 < n_pool); + for (size_t pi = 0; pi < sq.pools.size(); ++pi, ++ip_all) { + const uint32_t j = sq.pools[pi]; // The pooled key lives in the last member's row. const uint32_t rep = sq.cells[j + kpool - 1].second; - pcell[ip] = (int32_t) gcell(sq, rep); - - for (uint32_t k = 0; k < kpool; ++k) { - pidx[(size_t) ip*kpool + k] = inert ? sentinel : (int32_t) sq.cells[j + k].second; + if (!is_rep.empty()) { + is_rep[gcell(sq, rep)] = 1; } - if (st.is_new[ip] == st.generation) { + if (st.is_new[ip_all] == st.generation) { GGML_ASSERT(i_new < n_new); for (uint32_t k = 0; k < kpool; ++k) { nidx[(size_t) i_new*kpool + k] = (int32_t) gcell(sq, sq.cells[j + k].second); @@ -884,23 +891,33 @@ void llama_memory_hybrid_idx_context::set_input_kpool(ggml_tensor * pool_cells, ++i_new; } + if (!seq_in_ub[s]) { + continue; + } + + const uint32_t ip = (uint32_t) pool_end.size(); + GGML_ASSERT(ip + 1 < n_pool); + + pcell[ip] = (int32_t) gcell(sq, rep); + for (uint32_t k = 0; k < kpool; ++k) { + pidx[(size_t) ip*kpool + k] = (int32_t) sq.cells[j + k].second; + } + pool_end.push_back(sq.cells[j + kpool - 1].first); } } GGML_ASSERT(i_new == n_new); + GGML_ASSERT(ip_all == st.n_pool_real && pool_end.size() == st.n_pool_ub); // Padded entries re-pool cells whose pooled slot is never read: only the reps of complete pools are read. // Each entry takes its own cell, entries sharing one would write it from several threads in the scatter. if (n_new_g > n_new) { - std::vector reps(pcell, pcell + pool_end.size()); - std::sort(reps.begin(), reps.end()); - int64_t pad_cell = 0; for (uint32_t i = n_new; i < n_new_g; ++i, ++pad_cell) { - while (std::binary_search(reps.begin(), reps.end(), pad_cell)) { + while (pad_cell < n_cells && is_rep[pad_cell]) { ++pad_cell; } - GGML_ASSERT(pad_cell < (int64_t) kv_size*n_stream_kv); + GGML_ASSERT(pad_cell < n_cells); for (uint32_t k = 0; k < kpool; ++k) { nidx[(size_t) i*kpool + k] = (int32_t) pad_cell; } From 46eb1742db6d2caec1bfa848c5702b1bdcc815e5 Mon Sep 17 00:00:00 2001 From: Daniel Kuts Date: Sat, 21 Nov 2026 09:00:30 +0300 Subject: [PATCH 009/401] llama-grammar: Fix integer overflow (#32551) * llama-grammar: Fix integer overflow * Check incorrect values at parsing and bail out nicely * fix style --- src/llama-grammar.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/llama-grammar.cpp b/src/llama-grammar.cpp index bb853b1e5bea..9a0de14307e5 100644 --- a/src/llama-grammar.cpp +++ b/src/llama-grammar.cpp @@ -668,6 +668,9 @@ const char * llama_grammar_parser::parse_sequence( if (max_times != UINT64_MAX && max_times > MAX_REPETITION_THRESHOLD) { max_times = UINT64_MAX; } + if (max_times < min_times) { + throw std::runtime_error(std::string("incorrect number of repetitions")); + } handle_repetitions(min_times, max_times); } else { break; From 40b7a546defe1f60edd1338c719552ffc58c89a0 Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Sat, 21 Nov 2026 09:02:26 +0100 Subject: [PATCH 010/401] ci: temporary disable no realloc case for mtmd (#32708) --- .github/workflows/server-sanitize.yml | 2 ++ .github/workflows/server-self-hosted.yml | 2 ++ tools/server/tests/unit/test_realtime.py | 7 ++++++- tools/server/tests/utils.py | 5 +++++ 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/.github/workflows/server-sanitize.yml b/.github/workflows/server-sanitize.yml index 4202c31e7cc1..aececfe2f6d5 100644 --- a/.github/workflows/server-sanitize.yml +++ b/.github/workflows/server-sanitize.yml @@ -42,6 +42,8 @@ env: LLAMA_ARG_LOG_PREFIX: 1 LLAMA_ARG_LOG_TIMESTAMPS: 1 LLAMA_ARG_LOG_VERBOSITY: 10 + # [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc + GGML_SCHED_NO_REALLOC: ON concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }} diff --git a/.github/workflows/server-self-hosted.yml b/.github/workflows/server-self-hosted.yml index c5dd86449c5e..e54469964eac 100644 --- a/.github/workflows/server-self-hosted.yml +++ b/.github/workflows/server-self-hosted.yml @@ -39,6 +39,8 @@ env: LLAMA_ARG_LOG_PREFIX: 1 LLAMA_ARG_LOG_TIMESTAMPS: 1 LLAMA_ARG_LOG_VERBOSITY: 10 + # [TAG_MTMD_NO_REALLOC] must match -DGGML_SCHED_NO_REALLOC=ON below, skips tests that are known to realloc + GGML_SCHED_NO_REALLOC: ON concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref || github.run_id }} diff --git a/tools/server/tests/unit/test_realtime.py b/tools/server/tests/unit/test_realtime.py index 5af63a98e27d..c22d58128a22 100644 --- a/tools/server/tests/unit/test_realtime.py +++ b/tools/server/tests/unit/test_realtime.py @@ -81,11 +81,14 @@ def session_update(ws: Connection, **session) -> dict: # live transcription # +# [TAG_MTMD_NO_REALLOC] TODO: mtmd reallocs its graphs on audio stream steps +skip_no_realloc = pytest.mark.skipif(is_no_realloc(), reason="mtmd: graph realloc on audio stream step") + LIVE_ASR = [ # a chat model with an "asr" chat template, live only in sessions opened with ?intent=transcription ("tinylfm3omni", "/v1/realtime?intent=transcription"), # no chat, the text follows the audio by a few tokens - ("tinyvoxtralrt", "/v1/realtime"), + pytest.param("tinyvoxtralrt", "/v1/realtime", marks=skip_no_realloc), ] @@ -119,6 +122,7 @@ def test_live_asr(preset: str, path: str): assert all(len(text) > 0 for _, text in transcripts) +@skip_no_realloc @pytest.mark.parametrize("preset,path", LIVE_ASR) def test_live_asr_chunked_audio(preset: str, path: str): start_live_asr(preset) @@ -168,6 +172,7 @@ def test_live_asr_invalid_events(preset: str, path: str): assert len(get_transcripts(recv_all(ws))) == 1 +@skip_no_realloc def test_live_asr_depends_on_audio(): # the random weights of this model give a different text for each input start_live_asr("tinyvoxtralrt") diff --git a/tools/server/tests/utils.py b/tools/server/tests/utils.py index b32422182b92..6dbd540b94dc 100644 --- a/tools/server/tests/utils.py +++ b/tools/server/tests/utils.py @@ -902,6 +902,11 @@ def is_slow_test_allowed(): return os.environ.get("SLOW_TESTS") == "1" or os.environ.get("SLOW_TESTS") == "ON" +# [TAG_MTMD_NO_REALLOC] TODO @ngxson : remove when mtmd side is fixed +def is_no_realloc(): + return os.environ.get("GGML_SCHED_NO_REALLOC") in ("1", "ON") or os.environ.get("GGML_SCHED_DEBUG_REALLOC", "0") != "0" + + def make_pcm16(seconds: float = 1.0, rate: int = 16000, freq: float = 440.0) -> bytes: """ sine tone as raw PCM16 mono samples """ n = int(seconds * rate) From e412c6f468b7b9e0f16f2540244236f8ad68e9ae Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Sat, 21 Nov 2026 10:26:55 +0200 Subject: [PATCH 011/401] llama : remove fused lightning indexer gating (#32650) The fused lightning indexer is always used now, so drop the cparams flags, the auto probe and the non-fused fallbacks. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) --- src/llama-context.cpp | 15 ------------- src/llama-cparams.h | 2 -- src/llama-graph.cpp | 15 +++++-------- src/llama-graph.h | 1 - src/models/deepseek32.cpp | 42 ++--------------------------------- src/models/deepseek4.cpp | 28 ++--------------------- src/models/deepseek41.cpp | 3 +-- src/models/dots3note.cpp | 38 ++----------------------------- src/models/glm-dsa.cpp | 42 ++--------------------------------- src/models/glm5-next.cpp | 22 ++---------------- src/models/hy-v4.cpp | 20 ++--------------- src/models/kimi-k31.cpp | 21 ++---------------- src/models/mistral-large4.cpp | 42 ++--------------------------------- src/models/qwen4exp.cpp | 1 - 14 files changed, 23 insertions(+), 269 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index ea41283f99d2..7490cf3794d7 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -136,12 +136,6 @@ static const llm_fused_op_probe llm_fused_op_flash_attn_kv_rows_probe = { /*.n_tokens_per_seq =*/ 1, }; -static const llm_fused_op_probe llm_fused_op_lid_probe = { - /*.op =*/ LLM_FUSED_OP_LIGHTNING_INDEXER, - /*.name =*/ "Lightning Indexer", - /*.n_tokens_per_seq =*/ 1, -}; - static const llm_fused_op_probe llm_fused_op_dsv4_hc_pre_probe = { /*.op =*/ LLM_FUSED_OP_DSV4_HC_PRE, /*.name =*/ "fused DeepSeek V4 HC pre", @@ -334,9 +328,6 @@ llama_context::llama_context( cparams.auto_fa = false; } - cparams.fused_lid = true; - cparams.auto_flid = false; - cparams.fused_dsv4_hc_pre = true; cparams.fused_dsv4_hc_comb = true; cparams.fused_dsv4_hc_post = true; @@ -725,12 +716,6 @@ void llama_context::resolve_fused_ops(const llama_memory_context_i * mctx, uint3 cparams.auto_fkvr = false; } - if (cparams.auto_flid) { - LLAMA_LOG_INFO("%s: resolving fused Lightning Indexer support:\n", func); - resolve(llm_fused_op_lid_probe, cparams.fused_lid); - cparams.auto_flid = false; - } - if (cparams.auto_fhc) { LLAMA_LOG_INFO("%s: resolving fused DeepSeek V4 HC support:\n", func); resolve(llm_fused_op_dsv4_hc_pre_probe, cparams.fused_dsv4_hc_pre); diff --git a/src/llama-cparams.h b/src/llama-cparams.h index 1f890d6fa9c4..c93494fafeb1 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -39,8 +39,6 @@ struct llama_cparams { bool offload_kqv; bool flash_attn; bool auto_fa; - bool fused_lid; // use fused lightning indexer - bool auto_flid; bool fused_dsv4_hc_pre; bool fused_dsv4_hc_comb; bool fused_dsv4_hc_post; diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 269b920fb8e3..c5c9ddf014b9 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -34,13 +34,14 @@ static ggml_tensor * build_attn_inp_kq_mask( ggml_context * ctx, const llama_kv_cache_context * mctx, const llama_ubatch & ubatch, - const llama_cparams & cparams) { + const llama_cparams & cparams, + bool force_f16 = false) { const auto n_kv = mctx->get_n_kv(); const auto n_tokens = ubatch.n_tokens; const auto n_stream = cparams.kv_unified ? 1 : ubatch.n_seqs_unq; - // flash attention requires an f16 mask - const auto type = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32; + // flash attention and the lightning indexer require an f16 mask + const auto type = (cparams.flash_attn || force_f16) ? GGML_TYPE_F16 : GGML_TYPE_F32; ggml_tensor * res = ggml_new_tensor_4d(ctx, type, n_kv, n_tokens/n_stream, 1, n_stream); ggml_set_input(res); @@ -1146,7 +1147,7 @@ static void dsv4_build_comp_inputs( GGML_ASSERT(n_stream > 0); GGML_ASSERT(n_tokens%n_stream == 0); - inp.kq_mask = ggml_new_tensor_4d(ctx, (strcmp(name, "lid") != 0 && cparams.flash_attn) || (strcmp(name, "lid") == 0 && cparams.fused_lid) ? GGML_TYPE_F16 : GGML_TYPE_F32, plan.n_kv, n_tokens/n_stream, 1, n_stream); + inp.kq_mask = ggml_new_tensor_4d(ctx, (strcmp(name, "lid") == 0 || cparams.flash_attn) ? GGML_TYPE_F16 : GGML_TYPE_F32, plan.n_kv, n_tokens/n_stream, 1, n_stream); ggml_set_input(inp.kq_mask); ggml_set_name(inp.kq_mask, (std::string("dsv4_") + name + "_kq_mask").c_str()); } @@ -4034,11 +4035,7 @@ static std::unique_ptr build_attn_inp_k_dsa_impl( { inp->self_k_idxs_lid = mctx_cur->get_lid()->build_input_k_idxs(ctx0, ubatch); - // ensure that mask type matches fused lightning indexer use (requires f16 mask) - auto cparams_copy = cparams; - cparams_copy.flash_attn = cparams.fused_lid; - - inp->self_attn_mask_lid.raw = build_attn_inp_kq_mask(ctx0, mctx_cur->get_lid(), ubatch, cparams_copy); + inp->self_attn_mask_lid.raw = build_attn_inp_kq_mask(ctx0, mctx_cur->get_lid(), ubatch, cparams, true); inp->self_k_rot_lid = mctx_cur->get_lid()->get_k_rot(); } diff --git a/src/llama-graph.h b/src/llama-graph.h index b5956ead9120..a9f8e5ce0068 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -49,7 +49,6 @@ enum llm_graph_type { enum llm_fused_op { LLM_FUSED_OP_FLASH_ATTN, LLM_FUSED_OP_FLASH_ATTN_KV_ROWS, - LLM_FUSED_OP_LIGHTNING_INDEXER, LLM_FUSED_OP_DSV4_HC_PRE, LLM_FUSED_OP_DSV4_HC_COMB, LLM_FUSED_OP_DSV4_HC_POST, diff --git a/src/models/deepseek32.cpp b/src/models/deepseek32.cpp index fc6207f8b3d0..853389b88306 100644 --- a/src/models/deepseek32.cpp +++ b/src/models/deepseek32.cpp @@ -265,46 +265,8 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - // calculate indexer kq - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - // apply ReLU - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - // multiply scores by indexer weights - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - // mask indexer scores - ggml_tensor * indexer_kq_mask = inp_attn_dsa->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; diff --git a/src/models/deepseek4.cpp b/src/models/deepseek4.cpp index 69ebe5a603ec..dfc9858e7bea 100644 --- a/src/models/deepseek4.cpp +++ b/src/models/deepseek4.cpp @@ -642,32 +642,8 @@ ggml_tensor * llama_model_deepseek4::graph::build_lid_top_k( indexer_weights->ne[0], indexer_weights->ne[1]/n_stream, indexer_weights->ne[2], n_stream, indexer_weights->nb[1], indexer_weights->nb[2]/n_stream, indexer_weights->nb[3]/n_stream, 0); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_lid.kq_mask); - cb(indexer_score, "lid_score_masked", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "lid_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "lid_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "lid_kq", il); - - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "lid_kq", il); - - indexer_score = ggml_relu(ctx0, indexer_kq); - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - indexer_score = ggml_sum_rows(ctx0, indexer_score); - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "lid_score", il); - - indexer_score = ggml_add(ctx0, indexer_score, inp_lid.kq_mask); - cb(indexer_score, "lid_score_masked", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_lid.kq_mask); + cb(indexer_score, "lid_score_masked", il); const uint32_t n_top_k = indexer_score->ne[0] < hparams.indexer_top_k ? indexer_score->ne[0] : hparams.indexer_top_k; ggml_tensor * top_k = ggml_cont(ctx0, ggml_top_k(ctx0, indexer_score, n_top_k)); diff --git a/src/models/deepseek41.cpp b/src/models/deepseek41.cpp index 96de9041270c..ed93be5348e2 100644 --- a/src/models/deepseek41.cpp +++ b/src/models/deepseek41.cpp @@ -533,7 +533,7 @@ ggml_tensor * llama_model_deepseek41::graph::build_attention41( ggml_tensor * ik = ggml_view_4d(ctx0, comp_all, n_idx_embd, 1, n_comp, n_stream, comp_all->nb[1], comp_all->nb[2], comp_all->nb[3], ggml_row_size(comp_all->type, n_embd_head)); // the fused indexer reads the strided view in place, the unfused path needs it contiguous; CUDA has no same-type copy of quantized views, so dequantize them - const bool fused_idx = sparse && cparams.fused_lid && ci.kq_mask->type == GGML_TYPE_F16; + const bool fused_idx = sparse && ci.kq_mask->type == GGML_TYPE_F16; if (ggml_is_quantized(ik->type)) { ik = ggml_cast(ctx0, ik, GGML_TYPE_F32); } else if (!fused_idx) { @@ -572,7 +572,6 @@ ggml_tensor * llama_model_deepseek41::graph::build_attention41( ggml_tensor * score = nullptr; if (fused_idx) { score = ggml_lightning_indexer(ctx0, iq, ik, iw, ci.kq_mask); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); } else { ggml_tensor * iqc = ggml_view_4d(ctx0, iq, iq->ne[0], iq->ne[1], nc, n_stream, iq->nb[1], iq->nb[2], iq->nb[3], t0*iq->nb[2]); diff --git a/src/models/dots3note.cpp b/src/models/dots3note.cpp index a6fccd58f1d6..da16f24801fc 100644 --- a/src/models/dots3note.cpp +++ b/src/models/dots3note.cpp @@ -257,42 +257,8 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn->get_dsa()->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - ggml_tensor * indexer_kq_mask = inp_attn->get_dsa()->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn->get_dsa()->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; diff --git a/src/models/glm-dsa.cpp b/src/models/glm-dsa.cpp index 7007f427faeb..6daafd007caf 100644 --- a/src/models/glm-dsa.cpp +++ b/src/models/glm-dsa.cpp @@ -307,46 +307,8 @@ llama_model_glm_dsa::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - // calculate indexer kq - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - // apply ReLU - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - // multiply scores by indexer weights - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - // mask indexer scores - ggml_tensor * indexer_kq_mask = inp_attn_dsa->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp index 844a327b3dd2..51a26df3deaf 100644 --- a/src/models/glm5-next.cpp +++ b/src/models/glm5-next.cpp @@ -280,15 +280,12 @@ llama_model_glm5_next::llm_graph_input_kpool * llama_model_glm5_next::graph::bui // change shape every kpool tokens const uint32_t n_new = std::max(mctx_hyb->get_n_kpool_new(), 1u); - // the fused lightning indexer wants an f16 mask - const auto type_mask = cparams.fused_lid ? GGML_TYPE_F16 : GGML_TYPE_F32; - auto inp = std::make_unique(mctx_hyb, kpool); inp->k_idxs = mctx_idx->build_input_k_idxs(ctx0, ubatch); inp->pool_cells = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_pool); inp->pool_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool, n_pool); - inp->pool_mask = ggml_new_tensor_2d(ctx0, type_mask, n_pool, n_tokens); + inp->pool_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F16, n_pool, n_tokens); inp->tail_idxs = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, kpool - 1, n_tokens); ggml_set_input(inp->pool_cells); ggml_set_input(inp->pool_idxs); @@ -934,22 +931,7 @@ ggml_tensor * llama_model_glm5_next::graph::build_kpool_select( weights = ggml_scale(ctx0, weights, 1.0f / sqrtf(float(n_embd_indexer * n_indexer_head))); cb(weights, "indexer_weights", il); - ggml_tensor * score = nullptr; - if (cparams.fused_lid) { - score = ggml_lightning_indexer(ctx0, iq, pooled, weights, inp_kpool->pool_mask); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); - } else { - ggml_tensor * q_p = ggml_permute(ctx0, iq, 0, 2, 1, 3); // [head_dim, n_tokens, n_head] - ggml_tensor * k_p = ggml_permute(ctx0, pooled, 0, 2, 1, 3); // [head_dim, n_pool, 1] - - ggml_tensor * kq = ggml_mul_mat(ctx0, k_p, q_p); // [n_pool, n_tokens, n_head] - kq = ggml_cont(ctx0, ggml_permute(ctx0, kq, 2, 1, 0, 3)); // [n_head, n_tokens, n_pool] - score = ggml_relu(ctx0, kq); - score = ggml_mul(ctx0, score, weights); - score = ggml_sum_rows(ctx0, score); // [1, n_tokens, n_pool] - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); // [n_pool, n_tokens, 1] - score = ggml_add(ctx0, score, inp_kpool->pool_mask); - } + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, pooled, weights, inp_kpool->pool_mask); cb(score, "indexer_score", il); const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool); diff --git a/src/models/hy-v4.cpp b/src/models/hy-v4.cpp index 386d504bcde7..de7d87cd03ee 100644 --- a/src/models/hy-v4.cpp +++ b/src/models/hy-v4.cpp @@ -393,24 +393,8 @@ ggml_tensor * llama_model_hy_v4::graph::build_indexer_top_k( // fold both reference scale factors into the weights before the big score tensor iw = ggml_scale(ctx0, iw, 1.0f / sqrtf(float(n_embd_indexer * n_indexer_head))); - ggml_tensor * score = nullptr; - if (cparams.fused_lid) { - score = ggml_lightning_indexer(ctx0, iq, ik, iw, inp_attn_dsa->self_attn_mask_lid.raw); - cb(score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); - } else { - iq = ggml_permute(ctx0, iq, 0, 2, 1, 3); - ik = ggml_permute(ctx0, ik, 0, 2, 1, 3); - - score = ggml_mul_mat(ctx0, ik, iq); - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); - score = ggml_relu(ctx0, score); - score = ggml_mul(ctx0, score, iw); - score = ggml_sum_rows(ctx0, score); - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); - score = ggml_add(ctx0, score, inp_attn_dsa->self_attn_mask_lid.raw); - cb(score, "indexer_score", il); - } + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, ik, iw, inp_attn_dsa->self_attn_mask_lid.raw); + cb(score, "indexer_score", il); const uint32_t n_top_k = score->ne[0] < (int64_t) hparams.indexer_top_k ? score->ne[0] : hparams.indexer_top_k; diff --git a/src/models/kimi-k31.cpp b/src/models/kimi-k31.cpp index 0c0ca2af259d..3f99eca4a183 100644 --- a/src/models/kimi-k31.cpp +++ b/src/models/kimi-k31.cpp @@ -581,28 +581,11 @@ llama_model_kimi_k31::graph::build_dsa_layer( iw->nb[1], iw->nb[2]/n_stream, iw->nb[2]/n_stream, 0); ggml_tensor * kq_mask_lid = inp_attn->self_attn_mask.raw; - if (cparams.fused_lid && kq_mask_lid->type != GGML_TYPE_F16) { + if (kq_mask_lid->type != GGML_TYPE_F16) { kq_mask_lid = ggml_cast(ctx0, kq_mask_lid, GGML_TYPE_F16); } - ggml_tensor * score; - if (cparams.fused_lid) { - score = ggml_lightning_indexer(ctx0, iq, ik, iw, kq_mask_lid); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); - } else { - ggml_tensor * q_p = ggml_permute(ctx0, iq, 0, 2, 1, 3); // [n_idx_dim, n_tokens, n_idx_head] - ggml_tensor * k_p = ggml_permute(ctx0, ik, 0, 2, 1, 3); // [n_idx_dim, n_kv, 1] - - ggml_tensor * kq = ggml_mul_mat(ctx0, k_p, q_p); // [n_kv, n_tokens, n_idx_head] - kq = ggml_cont(ctx0, ggml_permute(ctx0, kq, 2, 1, 0, 3)); // [n_idx_head, n_tokens, n_kv] - - score = ggml_relu(ctx0, kq); - score = ggml_mul(ctx0, score, iw); - score = ggml_sum_rows(ctx0, score); // [1, n_tokens, n_kv] - score = ggml_cont(ctx0, ggml_permute(ctx0, score, 2, 1, 0, 3)); // [n_kv, n_tokens, 1] - - score = ggml_add(ctx0, score, kq_mask_lid); - } + ggml_tensor * score = ggml_lightning_indexer(ctx0, iq, ik, iw, kq_mask_lid); cb(score, "indexer_score", il); const int64_t n_top_k = std::min(score->ne[0], hparams.indexer_top_k); diff --git a/src/models/mistral-large4.cpp b/src/models/mistral-large4.cpp index a4315a9919e3..6407d7663637 100644 --- a/src/models/mistral-large4.cpp +++ b/src/models/mistral-large4.cpp @@ -290,46 +290,8 @@ llama_model_mistral_large4::graph::graph(const llm_graph_params & params) : indexer_weights = ggml_scale(ctx0, indexer_weights, 1.0f / sqrtf(float(n_embd_indexer_head * n_indexer_head))); cb(indexer_weights, "indexer_weights", il); - ggml_tensor * indexer_score = nullptr; - if (cparams.fused_lid) { - indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); - cb(indexer_score, "indexer_score", il); - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, indexer_score, il}); - } else { - // calculate indexer kq - indexer_q = ggml_permute(ctx0, indexer_q, 0, 2, 1, 3); - cb(indexer_q, "indexer_q", il); - indexer_k = ggml_permute(ctx0, indexer_k, 0, 2, 1, 3); - cb(indexer_k, "indexer_k", il); - - ggml_tensor * indexer_kq = ggml_mul_mat(ctx0, indexer_k, indexer_q); - cb(indexer_kq, "indexer_kq", il); - - // ReLU requires contiguous tensors - indexer_kq = ggml_cont(ctx0, ggml_permute(ctx0, indexer_kq, 2, 1, 0, 3)); - cb(indexer_kq, "indexer_kq", il); - - // apply ReLU - indexer_score = ggml_relu(ctx0, indexer_kq); - cb(indexer_score, "indexer_score", il); - - // multiply scores by indexer weights - indexer_score = ggml_mul(ctx0, indexer_score, indexer_weights); - cb(indexer_score, "indexer_score", il); - - // sum by q n_indexer_head dimension - indexer_score = ggml_sum_rows(ctx0, indexer_score); - cb(indexer_score, "indexer_score", il); - - // permute result to match KQ mask - indexer_score = ggml_cont(ctx0, ggml_permute(ctx0, indexer_score, 2, 1, 0, 3)); - cb(indexer_score, "indexer_score", il); - - // mask indexer scores - ggml_tensor * indexer_kq_mask = inp_attn_dsa->self_attn_mask_lid.raw; - indexer_score = ggml_add(ctx0, indexer_score, indexer_kq_mask); - cb(indexer_score, "indexer_score", il); - } + ggml_tensor * indexer_score = ggml_lightning_indexer(ctx0, indexer_q, indexer_k, indexer_weights, inp_attn_dsa->self_attn_mask_lid.raw); + cb(indexer_score, "indexer_score", il); // get indices of top k indexer scores uint32_t n_top_k = indexer_score->ne[0] < n_indexer_top_k ? indexer_score->ne[0] : n_indexer_top_k; diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index 7bf9b3fee8c9..63c918602547 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -872,7 +872,6 @@ ggml_tensor * llama_model_qwen4exp::graph::build_qsa_sel( // which is the lightning indexer with every head weight set to that scale ggml_tensor * weights = ggml_fill(ctx0, ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_idx_h, n_tokens), 1.0f/sqrtf((float) idx_dim)); ggml_tensor * score = ggml_lightning_indexer(ctx0, q, pooled, weights, inp_kpool->pool_mask); // [n_pool, n_tokens] - res->add_fused_node({LLM_FUSED_OP_LIGHTNING_INDEXER, score, il}); cb(score, "indexer_score", il); const int64_t n_top_pool = std::min(n_pool, hparams.indexer_top_k / kpool); From 1fdda89a4d16521152aa3ad65a5c51ca8d01b071 Mon Sep 17 00:00:00 2001 From: Aaron Teo Date: Sat, 21 Nov 2026 17:54:00 +0800 Subject: [PATCH 012/401] ci: switch ppc64le runners to ubuntu 26.04 (#32679) * ci: switch ppc64le runners to ubuntu 26.04 Signed-off-by: Aaron Teo * ci: rm problem matchers experiment Signed-off-by: Aaron Teo --------- Signed-off-by: Aaron Teo --- .github/workflows/build-ibm.yml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/.github/workflows/build-ibm.yml b/.github/workflows/build-ibm.yml index 67ca8b683e40..598b09be775a 100644 --- a/.github/workflows/build-ibm.yml +++ b/.github/workflows/build-ibm.yml @@ -137,8 +137,8 @@ jobs: -DCMAKE_CXX_FLAGS="-march=arch15" time cmake --build build --config Release -j $(nproc) - ubuntu-24-ppc64le: - runs-on: ubuntu-24.04-ppc64le + ubuntu-26-ppc64le: + runs-on: ubuntu-26.04-ppc64le steps: - name: Clone @@ -154,12 +154,6 @@ jobs: libjpeg-dev build-essential libssl-dev \ git-lfs - - name: Toolchain workaround (GCC 14) - run: | - sudo apt-get install -y gcc-14 g++-14 - echo "CC=gcc-14" >> "$GITHUB_ENV" - echo "CXX=g++-14" >> "$GITHUB_ENV" - - name: Python Dependencies id: python_depends run: | From 93cb37ea7b5f134cc500b1c5b91d971190600a1a Mon Sep 17 00:00:00 2001 From: shalinib-ibm Date: Sat, 21 Nov 2026 16:28:49 +0530 Subject: [PATCH 013/401] ggml-cpu: fix nc aligment in tinyBLAS_PPC_Q0 (#32659) Fixes https://github.com/ggml-org/llama.cpp/issues/31680 The matmul_tiled() implementation in tinyBLAS_Q0_PPC requires nc to be a multiple of 8 to perform matrix multiplication correctly. The previous alignment logic contained a special case for n == 4, which allowed n_aligned to be 4. Consequently, the tiled path could be selected with nc = 4, violating the kernel's tile-width requirement. This caused incorrect matrix multiplication results, observed as garbled inference output when running Flint Q4_K_M and Gemma 3 27B Instruct. --- ggml/src/ggml-cpu/llamafile/sgemm.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/ggml/src/ggml-cpu/llamafile/sgemm.cpp b/ggml/src/ggml-cpu/llamafile/sgemm.cpp index 5d660911316d..36b80051b65e 100644 --- a/ggml/src/ggml-cpu/llamafile/sgemm.cpp +++ b/ggml/src/ggml-cpu/llamafile/sgemm.cpp @@ -2981,8 +2981,6 @@ class tinyBLAS_Q0_PPC { int64_t n_aligned = 0; if (n % n_chunk == 0) { n_aligned = n; - } else if (n == 4) { - n_aligned = 4; } else if (n < n_chunk) { n_aligned = (n / 8) * 8; } else { From 3da11de1f1dde90c5e387b55683c7137a3ad4916 Mon Sep 17 00:00:00 2001 From: Aaron Teo Date: Sat, 21 Nov 2026 19:05:23 +0800 Subject: [PATCH 014/401] ggml-zdnn: fix ztensor load race condition (#32279) Signed-off-by: Aaron Teo --- ggml/src/ggml-zdnn/common.hpp | 3 +++ ggml/src/ggml-zdnn/mmf.cpp | 4 +--- ggml/src/ggml-zdnn/mmq.cpp | 4 +--- ggml/src/ggml-zdnn/utils.cpp | 14 ++++++++++++++ ggml/src/ggml-zdnn/utils.hpp | 2 ++ 5 files changed, 21 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-zdnn/common.hpp b/ggml/src/ggml-zdnn/common.hpp index e28e7608b6a2..3ab3b4b277b4 100644 --- a/ggml/src/ggml-zdnn/common.hpp +++ b/ggml/src/ggml-zdnn/common.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include @@ -50,6 +51,8 @@ struct ggml_backend_zdnn_buffer { std::vector scales; // per-row scales for quantized weights std::vector channel_scales; // per-input-channel scales for quantized weights, applied to the inputs + std::mutex mutex; + char name[GGML_MAX_NAME]; }; diff --git a/ggml/src/ggml-zdnn/mmf.cpp b/ggml/src/ggml-zdnn/mmf.cpp index acd443e5be59..0efb4821eb01 100644 --- a/ggml/src/ggml-zdnn/mmf.cpp +++ b/ggml/src/ggml-zdnn/mmf.cpp @@ -61,9 +61,7 @@ void ggml_zdnn_mul_mat_f( GGML_ASSERT(weights_extra->pre_tfm_desc.dim2 == weights->ne[1] && "weights_extra->pre_tfm_desc.dim2 must match weights->ne[1]"); // weights read straight into a host buffer skip set_tensor, so transform them on first use - if (!weights_extra->ztensor.is_transformed) { - ggml_zdnn_load_tensor(weights_extra->ztensor, weights->data); - } + ggml_zdnn_load_weights(weights_extra, weights); // the inputs can be in any host buffer or be a view, so transform them from their data on every call { diff --git a/ggml/src/ggml-zdnn/mmq.cpp b/ggml/src/ggml-zdnn/mmq.cpp index 285479b4184e..50acddb25c5d 100644 --- a/ggml/src/ggml-zdnn/mmq.cpp +++ b/ggml/src/ggml-zdnn/mmq.cpp @@ -190,9 +190,7 @@ void ggml_zdnn_mul_mat_q( ggml_backend_zdnn_buffer * weights_extra = (ggml_backend_zdnn_buffer *)weights->extra; // weights read straight into a host buffer skip set_tensor, so transform them on first use - if (!weights_extra->ztensor.is_transformed) { - ggml_zdnn_load_tensor_q(weights_extra, weights); - } + ggml_zdnn_load_weights(weights_extra, weights); // starting threads costs more than it saves for small inputs, e.g. during token generation const int32_t n_threads = ne10*ne11 >= 65536 ? ctx->n_threads : 1; diff --git a/ggml/src/ggml-zdnn/utils.cpp b/ggml/src/ggml-zdnn/utils.cpp index 18e9879d0906..d59ed4001f67 100644 --- a/ggml/src/ggml-zdnn/utils.cpp +++ b/ggml/src/ggml-zdnn/utils.cpp @@ -144,6 +144,20 @@ void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tenso ZDNN_CHECK(zdnn_transform_quantized_ztensor(&buffer->ztensor, false, -127, 127, q.data())); } +void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) { + std::lock_guard lock(buffer->mutex); + + if (buffer->ztensor.is_transformed) { + return; + } + + if (ggml_is_quantized(tensor->type)) { + ggml_zdnn_load_tensor_q(buffer, tensor); + } else { + ggml_zdnn_load_tensor(buffer->ztensor, tensor->data); + } +} + void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) { if (ggml_is_quantized(tensor->type)) { GGML_ASSERT(ggml_is_matrix(tensor)); diff --git a/ggml/src/ggml-zdnn/utils.hpp b/ggml/src/ggml-zdnn/utils.hpp index 20f5be5b4828..f610c216f5ef 100644 --- a/ggml/src/ggml-zdnn/utils.hpp +++ b/ggml/src/ggml-zdnn/utils.hpp @@ -18,6 +18,8 @@ int64_t ggml_zdnn_q_group_size(const ggml_tensor * tensor); void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor); +void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor); + void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor); #endif // GGML_ZDNN_UTILITIES_HPP From 838d942438e602a0d7b11153bf808746ed45f545 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigbj=C3=B8rn=20Skj=C3=A6ret?= Date: Sat, 21 Nov 2026 12:10:04 +0100 Subject: [PATCH 015/401] model : additional shortcut checks for OOB in hrm_text (#32720) [no ci] --- src/models/hrm-text.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/models/hrm-text.cpp b/src/models/hrm-text.cpp index 4c3d52e32702..1a800ee5b382 100644 --- a/src/models/hrm-text.cpp +++ b/src/models/hrm-text.cpp @@ -23,7 +23,7 @@ void llama_model_hrm_text::load_arch_hparams(llama_model_loader & ml) { // the GGUF block count is the expanded cache-slot count // 64-bit: a 32-bit product can wrap and match n_layer(), then load_arch_tensors() indexes past model.layers const uint64_t n_slot = (uint64_t) hparams.n_hrm_layers_per_stack * hparams.n_hrm_h_cycles * (hparams.n_hrm_l_cycles + 1); - if (hparams.n_hrm_layers_per_stack >= hparams.n_layer() || n_slot != hparams.n_layer()) { + if (hparams.n_hrm_layers_per_stack >= hparams.n_layer() || hparams.n_hrm_h_cycles > LLAMA_MAX_LAYERS/2 || hparams.n_hrm_l_cycles >= LLAMA_MAX_LAYERS || n_slot != hparams.n_layer()) { throw std::runtime_error(format( "hrm: cache-slot count %" PRIu64 " (layers_per_stack %u, h_cycles %u, l_cycles %u) " "does not match block_count %u", From 690b87d88151dbd775bb6eff5581663688785928 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 21 Nov 2026 03:10:38 -0800 Subject: [PATCH 016/401] model : inkling2_loop share the loop slots after the scale pass (#32704) The loop slots copied the physical layers at the end of load_arch_tensors, before the generic pass attaches the optional .scale tensors, so the later passes through the core ran NVFP4 experts without their per-expert scales. Add an optional post_arch_tensors hook that runs after the scale pass and share the slots there. --- src/llama-model.cpp | 1 + src/llama-model.h | 3 +++ src/models/inkling2-loop.cpp | 2 ++ src/models/models.h | 1 + 4 files changed, 7 insertions(+) diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 4c77f6f68f70..81e28b1c5454 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -2019,6 +2019,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { output_in_s = create_tensor(tn(LLM_TENSOR_OUTPUT, "input_scale"), {1}, TENSOR_NOT_REQUIRED); } } + post_arch_tensors(ml); } ml.done_getting_tensors(); diff --git a/src/llama-model.h b/src/llama-model.h index e86e5e54fd70..6473980a8db3 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -1070,6 +1070,9 @@ struct llama_model { virtual void load_arch_tensors(llama_model_loader & ml) = 0; virtual std::unique_ptr build_arch_graph(const llm_graph_params & params) const = 0; + // optional, runs after the scale pass + virtual void post_arch_tensors(llama_model_loader &) {} + protected: llama_model_params params; diff --git a/src/models/inkling2-loop.cpp b/src/models/inkling2-loop.cpp index 0de66baeec3c..8366a1191f25 100644 --- a/src/models/inkling2-loop.cpp +++ b/src/models/inkling2-loop.cpp @@ -60,7 +60,9 @@ void llama_model_inkling2_loop::load_arch_tensors(llama_model_loader & ml) { l.ctrl_forget[c] = create_tensor(tn(forget[c], "weight", il), {rank, n_embd}, 0); } } +} +void llama_model_inkling2_loop::post_arch_tensors(llama_model_loader &) { // share the physical weights, each cache slot keeps its own KV and conv state for (int il = n_phys; il < (int) hparams.n_layer(); ++il) { layers[il] = layers[layer_phys(il)]; diff --git a/src/models/models.h b/src/models/models.h index 636afeae9805..8d2a5882772e 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2547,6 +2547,7 @@ struct llama_model_inkling2_loop : public llama_model_inkling2 { llama_model_inkling2_loop(const struct llama_model_params & params) : llama_model_inkling2(params) {} void load_arch_hparams(llama_model_loader & ml) override; void load_arch_tensors(llama_model_loader & ml) override; + void post_arch_tensors(llama_model_loader & ml) override; int n_layer_phys() const override { return n_phys; } int layer_phys(int il) const; From fb7090df56da0e3deaf1f233994a2cc100521196 Mon Sep 17 00:00:00 2001 From: KaiFelixBennett <83428264+KaiFelixBennett@users.noreply.github.com> Date: Sat, 21 Nov 2026 12:41:55 +0100 Subject: [PATCH 017/401] vulkan: improve RDNA4 MMVQ performance for Q3_K, Q5_K and IQ4_XS (#31804) * vulkan: keep default MMVQ rows for Q3_K, Q5_K, IQ4_XS on RDNA4 AMD proprietary driver Assisted-by: Claude Opus 5.5 * clean up mmvq shader load logic --------- Co-authored-by: Ruben Ortlam --- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 57 ++++++++++++++++++---------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index cc007103366f..d4bbf99130d6 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -3278,9 +3278,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { rm_stdq = 2; rm_stdq_int = 2; } - // RDNA3/4: above four columns, static 4 rows for all types bench faster than the default const bool is_rdna3_or_4 = device->vendor_id == VK_VENDOR_ID_AMD && (device->architecture == AMD_RDNA3 || device->architecture == AMD_RDNA4); - auto const &rm_int_n = [&](uint32_t rows, uint32_t i) { return (is_rdna3_or_4 && i >= 4) ? 4u : rows; }; // RDNA3/4 and NVIDIA except pre-Turing: use 4 rows for MUL_MAT_ID MMVQ. auto const &rm_id = [&](uint32_t rows) { if (device->vendor_id == VK_VENDOR_ID_NVIDIA && @@ -3391,25 +3389,43 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const uint32_t subgroup_size_int = (device->vendor_id == VK_VENDOR_ID_INTEL && device->subgroup_size_control) ? device->subgroup_min_size : device->subgroup_size; const uint32_t wg_size_subgroup_int = (w == DMMV_WG_SIZE_SUBGROUP) ? subgroup_size_int : (subgroup_size_int * 4); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_0][i], "mul_mat_vec_q2_0_q8_1_f32", arr_dmmv_q2_0_q8_1_f32_len[reduc], arr_dmmv_q2_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_0][i], "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_1][i], "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_0][i], "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_1][i], "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q8_0][i], "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q2_K][i], "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(2*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(2*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q3_K][i], "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q4_K][i], "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q5_K][i], "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_Q6_K][i], "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_kq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_kq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); - - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_S][i], "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ1_M][i], "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1*rm_iq_int(i), 1, 1}, {wg_size_subgroup_int, 1*rm_iq_int(i), i+1}, 1, true, use_subgroups, subgroup_size_int); - ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][GGML_TYPE_IQ4_XS][i], "mul_mat_vec_iq4_xs_q8_1_f32", arr_dmmv_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_iq4_xs_q8_1_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_int_n(1*rm_stdq_int, i), 1, 1}, {wg_size_subgroup_int, rm_int_n(1*rm_stdq_int, i), i+1}, 1, true, use_subgroups, subgroup_size_int); + const struct { + ggml_type type; + const char * name; + size_t spv_size; + const void * spv_data; + uint32_t default_rows; + } shaders[] = { + {GGML_TYPE_Q2_0, "mul_mat_vec_q2_0_q8_1_f32", arr_dmmv_q2_0_q8_1_f32_len[reduc], arr_dmmv_q2_0_q8_1_f32_data[reduc], 2*rm_kq_int}, + {GGML_TYPE_Q4_0, "mul_mat_vec_q4_0_q8_1_f32", arr_dmmv_q4_0_q8_1_f32_len[reduc], arr_dmmv_q4_0_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q4_1, "mul_mat_vec_q4_1_q8_1_f32", arr_dmmv_q4_1_q8_1_f32_len[reduc], arr_dmmv_q4_1_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q5_0, "mul_mat_vec_q5_0_q8_1_f32", arr_dmmv_q5_0_q8_1_f32_len[reduc], arr_dmmv_q5_0_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q5_1, "mul_mat_vec_q5_1_q8_1_f32", arr_dmmv_q5_1_q8_1_f32_len[reduc], arr_dmmv_q5_1_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_Q8_0, "mul_mat_vec_q8_0_q8_1_f32", arr_dmmv_q8_0_q8_1_f32_len[reduc], arr_dmmv_q8_0_q8_1_f32_data[reduc], rm_stdq_int}, + {GGML_TYPE_MXFP4, "mul_mat_vec_mxfp4_q8_1_f32", arr_dmmv_mxfp4_q8_1_f32_len[reduc], arr_dmmv_mxfp4_q8_1_f32_data[reduc], 2*rm_stdq_int}, + {GGML_TYPE_Q2_K, "mul_mat_vec_q2_k_q8_1_f32", arr_dmmv_q2_k_q8_1_f32_len[reduc], arr_dmmv_q2_k_q8_1_f32_data[reduc], 2*rm_kq_int}, + {GGML_TYPE_Q3_K, "mul_mat_vec_q3_k_q8_1_f32", arr_dmmv_q3_k_q8_1_f32_len[reduc], arr_dmmv_q3_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_Q4_K, "mul_mat_vec_q4_k_q8_1_f32", arr_dmmv_q4_k_q8_1_f32_len[reduc], arr_dmmv_q4_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_Q5_K, "mul_mat_vec_q5_k_q8_1_f32", arr_dmmv_q5_k_q8_1_f32_len[reduc], arr_dmmv_q5_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_Q6_K, "mul_mat_vec_q6_k_q8_1_f32", arr_dmmv_q6_k_q8_1_f32_len[reduc], arr_dmmv_q6_k_q8_1_f32_data[reduc], rm_kq_int}, + {GGML_TYPE_IQ1_S, "mul_mat_vec_iq1_s_q8_1_f32", arr_dmmv_iq1_s_q8_1_f32_len[reduc], arr_dmmv_iq1_s_q8_1_f32_data[reduc], rm_iq_int(i)}, + {GGML_TYPE_IQ1_M, "mul_mat_vec_iq1_m_q8_1_f32", arr_dmmv_iq1_m_q8_1_f32_len[reduc], arr_dmmv_iq1_m_q8_1_f32_data[reduc], rm_iq_int(i)}, + {GGML_TYPE_IQ4_XS, "mul_mat_vec_iq4_xs_q8_1_f32", arr_dmmv_iq4_xs_q8_1_f32_len[reduc], arr_dmmv_iq4_xs_q8_1_f32_data[reduc], rm_stdq_int}, + }; + const bool use_four_rows = is_rdna3_or_4 && i >= 4; + const bool rdna4_amd_prop = device->architecture == AMD_RDNA4 && device->driver_id == vk::DriverId::eAmdProprietary; + for (const auto & shader : shaders) { + // Four rows can be slower for these quants on the AMD proprietary driver. + const bool use_default_rows = rdna4_amd_prop && + (shader.type == GGML_TYPE_Q3_K || shader.type == GGML_TYPE_Q5_K || shader.type == GGML_TYPE_IQ4_XS); + const uint32_t rows = use_four_rows && !use_default_rows ? 4u : shader.default_rows; + + ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_q8_1_f32[w][shader.type][i], + shader.name, shader.spv_size, shader.spv_data, "main", mul_mat_vec_num_bindings, + sizeof(vk_mat_vec_push_constants), {rows, 1, 1}, {wg_size_subgroup_int, rows, i+1}, + 1, true, use_subgroups, subgroup_size_int); + } } #endif // GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT } @@ -3477,7 +3493,6 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { GGML_UNUSED(rm_stdq_int); GGML_UNUSED(rm_kq_int); GGML_UNUSED(is_rdna3_or_4); - GGML_UNUSED(rm_int_n); GGML_UNUSED(rm_id); GGML_UNUSED(rm_iq_int); #endif From 362ac929749d56e433878585a8506f24968698b4 Mon Sep 17 00:00:00 2001 From: Ruben Ortlam Date: Sat, 21 Nov 2026 12:46:20 +0100 Subject: [PATCH 018/401] vulkan: unroll FA coopmat1 array due to a driver bug on AMD Windows (#32466) * vulkan: unroll FA coopmat1 array due to a driver bug on AMD Windows * simplify code to make it clearer --- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 7 +- .../vulkan-shaders/flash_attn_cm1.comp | 64 ++++++++++--------- 2 files changed, 39 insertions(+), 32 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index d4bbf99130d6..ae5a05c72e38 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1323,7 +1323,9 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device } // Br=32 spills registers, only prefill benefits - result.q_in_regs = result.block_rows == coopmat_block_rows && device->vendor_id == VK_VENDOR_ID_AMD && n_rows >= 64; + // AMD proprietary driver crashes compiling the loop-indexed Qreg array + result.q_in_regs = result.block_rows == coopmat_block_rows && device->vendor_id == VK_VENDOR_ID_AMD && n_rows >= 64 && + device->driver_id != vk::DriverId::eAmdProprietary; // Flipped ownership: each subgroup owns 16 Q rows. // uma, nvidia: K/V tiles staged in separate LDS buffers; discrete AMD GQA: K/V loaded directly from global memory. @@ -1355,6 +1357,9 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device result.limit_occupancy_shmem = 14 * 1024 / 16; } + // non-flip shader handles at most two row tiles + GGML_ASSERT(result.flip || result.block_rows <= 2 * coopmat_block_rows); + return result; } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp index bb9755ab8ac9..ea945ed075dc 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1.comp @@ -25,6 +25,7 @@ // These need to be supported N,M values for a MatBc x MatBr x 16 coopmatmuladd const uint32_t MatBr = 16; const uint32_t MatBc = 16; +const uint32_t q_tiles = Br / MatBr; const uint32_t rows_per_thread = Br / row_split; const uint32_t cols_per_iter = gl_WorkGroupSize.x / row_split; @@ -64,15 +65,14 @@ shared FLOAT_TYPEV4 kvsh[(kvsh_stride >= vsh_stride) ? (Bc * kvsh_stride) : (Bc shared ACC_TYPE slope[Br]; // row-tiled builds stage the PV result through sfsh -const bool PV_IN_SFSH = Br > MatBr; const uint32_t osh_stride = row_split * MatBr / 4; -shared O_TYPEV4 pvsh[PV_IN_SFSH ? 2 : Br * osh_stride]; +shared O_TYPEV4 pvsh[q_tiles > 1 ? 2 : Br * osh_stride]; shared vec4 occupancy_limiter[LIMIT_OCCUPANCY_SHMEM > 0 ? LIMIT_OCCUPANCY_SHMEM : 1]; #if defined(FLOAT16) && !defined(ACC_TYPE_MAX) const uint32_t pv_per_acc = 2; O_TYPEV4 pvsh_load(const uint32_t i) { - if (!PV_IN_SFSH) { + if (q_tiles == 1) { return pvsh[i]; } const uvec2 u = floatBitsToUint(vec2(sfsh[i / 2][(i % 2) * 2], sfsh[i / 2][(i % 2) * 2 + 1])); @@ -81,7 +81,7 @@ O_TYPEV4 pvsh_load(const uint32_t i) { #else const uint32_t pv_per_acc = 1; O_TYPEV4 pvsh_load(const uint32_t i) { - if (!PV_IN_SFSH) { + if (q_tiles == 1) { return pvsh[i]; } return O_TYPEV4(sfsh[i]); @@ -117,7 +117,6 @@ void main() { #define tile_row(r) (row_tid * rows_per_thread + (r)) - const uint32_t q_tiles = Br / MatBr; const uint32_t d_tiles = HSK_pad / 16; uint32_t q_offset = gqa_iq1*p.nb01 + (iq2*p.nb02+iq3*p.nb03) / 4; @@ -329,10 +328,9 @@ void main() { // K * Q^T -> S^T: Bc x HSK_pad * HSK_pad x Br -> Bc x Br // Bc split across workgroup (four subgroups), loop over HSK in chunks of 16: 16 x 16 * 16 x 16 -> 16 x 16 // This is written transposed in order to allow for N being 8 if implementations need it - coopmat SfMat[q_tiles]; - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - SfMat[q] = coopmat(0); - } + // No coopmat arrays: AMD's Windows compiler crashes on loop-indexed ones. q_tiles <= 2. + coopmat SfMat0 = coopmat(0); + coopmat SfMat1 = coopmat(0); coopmat KMat; coopmat QMat; @@ -386,19 +384,24 @@ void main() { coopMatLoad(KMat, kvsh, coord, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - if (Q_IN_REGS) { - SfMat[q] = coopMatMulAdd(KMat, Qreg[d * q_tiles + q], SfMat[q]); - } else { - coopMatLoad(QMat, Qf, d * 16 / 4 + q * MatBr * qstride, qstride, gl_CooperativeMatrixLayoutColumnMajor); - SfMat[q] = coopMatMulAdd(KMat, QMat, SfMat[q]); + if (Q_IN_REGS) { + SfMat0 = coopMatMulAdd(KMat, Qreg[d * q_tiles], SfMat0); + if (q_tiles > 1) { + SfMat1 = coopMatMulAdd(KMat, Qreg[d * q_tiles + 1], SfMat1); + } + } else { + coopMatLoad(QMat, Qf, d * 16 / 4, qstride, gl_CooperativeMatrixLayoutColumnMajor); + SfMat0 = coopMatMulAdd(KMat, QMat, SfMat0); + if (q_tiles > 1) { + coopMatLoad(QMat, Qf, d * 16 / 4 + MatBr * qstride, qstride, gl_CooperativeMatrixLayoutColumnMajor); + SfMat1 = coopMatMulAdd(KMat, QMat, SfMat1); } } } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - uint coord = gl_SubgroupID * MatBc * sfshstride + q * (MatBr / 4); - coopMatStore(SfMat[q], sfsh, coord, sfshstride, gl_CooperativeMatrixLayoutRowMajor); + coopMatStore(SfMat0, sfsh, gl_SubgroupID * MatBc * sfshstride, sfshstride, gl_CooperativeMatrixLayoutRowMajor); + if (q_tiles > 1) { + coopMatStore(SfMat1, sfsh, gl_SubgroupID * MatBc * sfshstride + MatBr / 4, sfshstride, gl_CooperativeMatrixLayoutRowMajor); } barrier(); @@ -516,10 +519,8 @@ void main() { [[unroll]] for (uint32_t hsv_tile = 0; hsv_tile < num_hsv_tiles; ++hsv_tile) { const uint hsv_offset = (hsv_tile * row_split + gl_SubgroupID) * 16; - coopmat PVMat[q_tiles]; - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - PVMat[q] = coopmat(0); - } + coopmat PVMat0 = coopmat(0); + coopmat PVMat1 = coopmat(0); // Preload V tiles for [Bc, 16 * num subgroups] const uint v_rows = Bc; @@ -584,18 +585,19 @@ void main() { coopMatLoad(QMat, kvsh, v_tile_offset, kvsh_stride, gl_CooperativeMatrixLayoutRowMajor); } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride + q * (MatBc / 4), psh_stride, gl_CooperativeMatrixLayoutColumnMajor); - PVMat[q] = coopMatMulAdd(KMat, QMat, PVMat[q]); + coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride, psh_stride, gl_CooperativeMatrixLayoutColumnMajor); + PVMat0 = coopMatMulAdd(KMat, QMat, PVMat0); + if (q_tiles > 1) { + coopMatLoad(KMat, Psh, bc_chunk * MatBc * psh_stride + MatBc / 4, psh_stride, gl_CooperativeMatrixLayoutColumnMajor); + PVMat1 = coopMatMulAdd(KMat, QMat, PVMat1); } } - [[unroll]] for (uint32_t q = 0; q < q_tiles; ++q) { - if (PV_IN_SFSH) { - coopMatStore(PVMat[q], sfsh, (o_offset + q * MatBc * osh_stride) / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor); - } else { - coopMatStore(PVMat[q], pvsh, o_offset + q * MatBc * osh_stride, osh_stride, gl_CooperativeMatrixLayoutRowMajor); - } + if (q_tiles > 1) { + coopMatStore(PVMat0, sfsh, o_offset / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor); + coopMatStore(PVMat1, sfsh, (o_offset + MatBc * osh_stride) / pv_per_acc, osh_stride / pv_per_acc, gl_CooperativeMatrixLayoutRowMajor); + } else { + coopMatStore(PVMat0, pvsh, o_offset, osh_stride, gl_CooperativeMatrixLayoutRowMajor); } } From b019be0c86e8adaf8b46627c091c24c1597b95f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20G=C3=A4=C3=9Fler?= Date: Sat, 21 Nov 2026 12:46:59 +0100 Subject: [PATCH 019/401] CUDA: abort on UB in fastdiv (#32698) --- ggml/src/ggml-cuda/common.cuh | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index 053ed60f798b..8cd2366ed907 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -1046,6 +1046,12 @@ static const uint3 init_fastdiv_values(uint64_t d_64) { uint32_t L = 0; while (L < 32 && (uint32_t{ 1 } << L) < d) { L++; + if (L == 32) { + // Shifting uint32_t by 32 to the right is undefined behavior. + // On NVIDIA it will produce 0. + // On AMD the value by which is shifted is masked with & 31 so it is shifting by 0 bits. + GGML_ABORT("undefined behavior in fastdiv"); + } } uint32_t mp = (uint32_t) ((uint64_t{ 1 } << 32) * ((uint64_t{ 1 } << L) - d) / d + 1); From a818a46f3df4b6dee7f59f174283deaeae083c4b Mon Sep 17 00:00:00 2001 From: Clemens Wasser Date: Sat, 21 Nov 2026 13:20:22 +0100 Subject: [PATCH 020/401] sycl: add fused ADD, RMS_NORM, MUL and vectorize rms norm (#31753) * sycl: vectorize contiguous rms norm * sycl: add fused ADD, RMS_NORM, MUL * tests: test fused ADD, RMS_NORM, MUL at decode widths --- ggml/src/ggml-sycl/fusion.cpp | 22 ++++ ggml/src/ggml-sycl/ggml-sycl.cpp | 6 + ggml/src/ggml-sycl/norm.cpp | 190 ++++++++++++++++++++++++++++--- ggml/src/ggml-sycl/norm.hpp | 5 + tests/test-backend-ops.cpp | 53 +++++++++ 5 files changed, 262 insertions(+), 14 deletions(-) diff --git a/ggml/src/ggml-sycl/fusion.cpp b/ggml/src/ggml-sycl/fusion.cpp index 9b553829be6d..9ea6af6b07db 100644 --- a/ggml/src/ggml-sycl/fusion.cpp +++ b/ggml/src/ggml-sycl/fusion.cpp @@ -121,6 +121,28 @@ bool ggml_sycl_can_fuse(const ggml_cgraph * cgraph, int node_idx, std::initializ return ggml_sycl_should_fuse_mul_mat_glu(gate, up, glu); } + // the residual sum stays materialised (a later residual add reads it), so ggml_can_fuse cannot + // express this either: the add and the mul are the subgraph's outputs + if (ops.size() == 3 && ops.begin()[0] == GGML_OP_ADD && ops.begin()[1] == GGML_OP_RMS_NORM && + ops.begin()[2] == GGML_OP_MUL) { + if (!ggml_can_fuse_subgraph(cgraph, node_idx, ops, { node_idx, node_idx + 2 })) { + return false; + } + + const ggml_tensor * add = cgraph->nodes[node_idx]; + if (cgraph->nodes[node_idx + 1]->src[0] != add) { + return false; + } + + // the fused kernel does not broadcast the add + if (add->src[0]->type != GGML_TYPE_F32 || add->src[1]->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32 || + !ggml_are_same_shape(add->src[0], add) || !ggml_are_same_shape(add->src[1], add)) { + return false; + } + + return ggml_sycl_can_fuse(cgraph, node_idx + 1, { GGML_OP_RMS_NORM, GGML_OP_MUL }, {}); + } + if (!ggml_can_fuse(cgraph, node_idx, ops)) { return false; } diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 5b87fa024d5f..3de5f1bd5888 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -6708,6 +6708,12 @@ static void ggml_backend_sycl_graph_compute_impl(ggml_backend_sycl_context * syc continue; } } + if (node->op == GGML_OP_ADD && + ggml_sycl_can_fuse(cgraph, i, { GGML_OP_ADD, GGML_OP_RMS_NORM, GGML_OP_MUL }, {}) && + ggml_sycl_op_add_rms_norm_fused(*sycl_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2])) { + i += 2; + continue; + } if (node->op == GGML_OP_RMS_NORM && ggml_sycl_can_fuse(cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD }, {})) { ggml_sycl_op_rms_norm_fused_add(*sycl_ctx, node, cgraph->nodes[i + 1], cgraph->nodes[i + 2]); diff --git a/ggml/src/ggml-sycl/norm.cpp b/ggml/src/ggml-sycl/norm.cpp index 36576e9c28c6..0cb30aa3550f 100644 --- a/ggml/src/ggml-sycl/norm.cpp +++ b/ggml/src/ggml-sycl/norm.cpp @@ -1,4 +1,6 @@ #include "norm.hpp" + +#include "fusion.hpp" #include "ggml-sycl/common.hpp" #include "ggml-sycl/presets.hpp" @@ -188,9 +190,28 @@ static void rms_norm_f32(const float* x, float* dst, const int ncols, float tmp = 0.0f; // partial sum for thread in warp - for (int col = tid; col < ncols; col += block_size) { - const float xi = x[col * src_stride_col]; - tmp += xi * xi; + // float4 path for contiguous, 16-byte aligned rows (decode), views and odd lengths stay strided + bool contig = src_stride_col == 1 && dst_stride_col == 1 && ncols % 4 == 0 && (uintptr_t) x % 16 == 0 && + (uintptr_t) dst % 16 == 0; + if constexpr (do_multiply) { + contig = contig && (uintptr_t) mul % 16 == 0; + } + if constexpr (do_add) { + contig = contig && (uintptr_t) add % 16 == 0; + } + const int n4 = ncols / 4; + + if (contig) { + const sycl::float4 * x4 = reinterpret_cast(x); + for (int i = tid; i < n4; i += block_size) { + const sycl::float4 v = x4[i]; + tmp += sycl::dot(v, v); + } + } else { + for (int col = tid; col < ncols; col += block_size) { + const float xi = x[col * src_stride_col]; + tmp += xi * xi; + } } // sum up partial sums @@ -216,17 +237,37 @@ static void rms_norm_f32(const float* x, float* dst, const int ncols, const float mean = tmp / ncols; const float scale = sycl::rsqrt(mean + eps); - for (int col = tid; col < ncols; col += block_size) { - if constexpr (do_multiply && do_add) { - dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col] + add[col]; - } else if constexpr (do_multiply) { - dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col]; - } else { - // folded epilogue of a fused GGML_OP_SCALE consumer (qwen35 GDN l2 norms); - // the explicit temporary keeps the float evaluation order identical to - // running rms_norm and scale as two separate kernels - const float v = scale * x[col * src_stride_col]; - dst[col * dst_stride_col] = v * scale_mul; + if (contig) { + const sycl::float4 * x4 = reinterpret_cast(x); + sycl::float4 * d4 = reinterpret_cast(dst); + const sycl::float4 * m4 = reinterpret_cast(mul); + const sycl::float4 * a4 = reinterpret_cast(add); + for (int i = tid; i < n4; i += block_size) { + const sycl::float4 v = x4[i]; + if constexpr (do_multiply && do_add) { + const sycl::float4 m = m4[i]; + const sycl::float4 a = a4[i]; + d4[i] = scale * v * m + a; + } else if constexpr (do_multiply) { + const sycl::float4 m = m4[i]; + d4[i] = scale * v * m; + } else { + d4[i] = scale * v * scale_mul; + } + } + } else { + for (int col = tid; col < ncols; col += block_size) { + if constexpr (do_multiply && do_add) { + dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col] + add[col]; + } else if constexpr (do_multiply) { + dst[col * dst_stride_col] = scale * x[col * src_stride_col] * mul[col]; + } else { + // folded epilogue of a fused GGML_OP_SCALE consumer (qwen35 GDN l2 norms); + // the explicit temporary keeps the float evaluation order identical to + // running rms_norm and scale as two separate kernels + const float v = scale * x[col * src_stride_col]; + dst[col * dst_stride_col] = v * scale_mul; + } } } } @@ -918,6 +959,127 @@ void ggml_sycl_op_rms_norm_fused_add(ggml_backend_sycl_context & ctx, ggml_tenso add_s01, add_s02, add_s03, add_nrows, add_nchannels, add_nsamples, eps, main_stream, ctx.device); } +// ADD(a, b) -> RMS_NORM -> MUL(w) in one launch. The sum (read by a later residual add) and +// normed * w are written after a barrier, as mul->data may alias a. +static void add_rms_norm_mul_f32(const float * a, + const float * b, + float * sum, + const float * mul, + float * dst, + const int ncols, + const float eps, + const sycl::nd_item<3> & item_ct1, + float * s_sum, + const int block_size) { + const int row = item_ct1.get_group(2); + const size_t off = (size_t) row * ncols; + const int tid = item_ct1.get_local_id(2); + const int n4 = ncols / 4; + + const sycl::float4 * a4 = reinterpret_cast(a + off); + const sycl::float4 * b4 = reinterpret_cast(b + off); + + sycl::float4 v[2]; + float tmp = 0.0f; +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int i = tid + k * block_size; + if (i < n4) { + const sycl::float4 va = a4[i]; + const sycl::float4 vb = b4[i]; + v[k] = va + vb; + tmp += sycl::dot(v[k], v[k]); + } + } + + const int nwarps = block_size / WARP_SIZE; + tmp = warp_reduce_sum(tmp, item_ct1); + if (block_size > WARP_SIZE) { + const auto sub_group = item_ct1.get_sub_group(); + if (sub_group.get_local_linear_id() == 0) { + s_sum[sub_group.get_group_linear_id()] = tmp; + } + item_ct1.barrier(sycl::access::fence_space::local_space); + const size_t nreduce = ceil_div(nwarps, WARP_SIZE); + tmp = 0.0f; + for (size_t i = 0; i < nreduce; i += 1) { + tmp += s_sum[sub_group.get_local_linear_id() + i * WARP_SIZE]; + } + tmp = warp_reduce_sum(tmp, item_ct1); + } + + const float mean = tmp / ncols; + const float scale = sycl::rsqrt(mean + eps); + + sycl::float4 * s4 = reinterpret_cast(sum + off); + sycl::float4 * d4 = reinterpret_cast(dst + off); + const sycl::float4 * m4 = reinterpret_cast(mul); +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int i = tid + k * block_size; + if (i < n4) { + const sycl::float4 m = m4[i]; + const sycl::float4 u = scale * v[k] * m; + s4[i] = v[k]; + d4[i] = u; + } + } +} + +static void add_rms_norm_mul_f32_sycl(const float * a, + const float * b, + float * sum, + const float * mul, + float * dst, + const int ncols, + const int nrows, + const float eps, + queue_ptr stream, + int device) { + const int work_group_size = ggml_sycl_info().max_work_group_sizes[device]; + GGML_ASSERT(work_group_size % (WARP_SIZE * WARP_SIZE) == 0); + const sycl::range<3> global_dims(1, 1, nrows); + const sycl::range<3> block_dims(1, 1, work_group_size); + stream->submit([&](sycl::handler & cgh) { + sycl::local_accessor s_sum(sycl::range<1>(work_group_size / WARP_SIZE), cgh); + cgh.parallel_for(sycl::nd_range<3>(global_dims * block_dims, block_dims), + [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { + add_rms_norm_mul_f32(a, b, sum, mul, dst, ncols, eps, item_ct1, get_pointer(s_sum), + work_group_size); + }); + }); +} + +bool ggml_sycl_op_add_rms_norm_fused(ggml_backend_sycl_context & ctx, + ggml_tensor * add, + ggml_tensor * rms, + ggml_tensor * mul) { + ggml_tensor * a = add->src[0]; + ggml_tensor * b = add->src[1]; + ggml_tensor * w = mul->src[0] == rms ? mul->src[1] : mul->src[0]; + const int64_t ncols = add->ne[0]; + const int wg = ggml_sycl_info().max_work_group_sizes[ctx.device]; + // whole rows of float4, at most two per work-item, from 16-byte aligned contiguous tensors + if (add->ne[2] != 1 || add->ne[3] != 1 || ncols < 1024 || ncols % 4 != 0 || ncols > 8 * (int64_t) wg || + w->ne[1] != 1) { + return false; + } + for (const ggml_tensor * t : { a, b, add, mul, w }) { + if (!ggml_is_contiguous(t) || (uintptr_t) t->data % 16 != 0) { + return false; + } + } + float eps = 0.0f; + memcpy(&eps, rms->op_params, sizeof(float)); + if (!(eps >= 0.0f)) { + return false; + } + add_rms_norm_mul_f32_sycl((const float *) a->data, (const float *) b->data, (float *) add->data, + (const float *) w->data, (float *) mul->data, (int) ncols, (int) add->ne[1], eps, + ctx.stream(), ctx.device); + return true; +} + void ggml_sycl_op_rms_norm_back(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/2); diff --git a/ggml/src/ggml-sycl/norm.hpp b/ggml/src/ggml-sycl/norm.hpp index fb667ac6b6e2..59a9ffd6fef2 100644 --- a/ggml/src/ggml-sycl/norm.hpp +++ b/ggml/src/ggml-sycl/norm.hpp @@ -25,6 +25,11 @@ void ggml_sycl_op_rms_norm_scale_fused(ggml_backend_sycl_context& ctx, ggml_tens void ggml_sycl_op_rms_norm_fused_add(ggml_backend_sycl_context& ctx, ggml_tensor* dst, ggml_tensor* mul_tensor, ggml_tensor* add_tensor); +bool ggml_sycl_op_add_rms_norm_fused(ggml_backend_sycl_context & ctx, + ggml_tensor * add, + ggml_tensor * rms, + ggml_tensor * mul); + void ggml_sycl_op_rms_norm_back(ggml_backend_sycl_context& ctx, ggml_tensor* dst); void ggml_sycl_op_group_norm(ggml_backend_sycl_context& ctx, ggml_tensor* dst); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 11bfa42a9aa7..fbf5c12d33de 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -4351,6 +4351,52 @@ struct test_add_rms_norm : public test_case { } }; +// GGML_OP_ADD + GGML_OP_RMS_NORM + GGML_OP_MUL (fused operation) +struct test_add_rms_norm_mul : public test_case { + const std::array ne; + const float eps; + + ggml_tensor * sum = nullptr; + ggml_tensor * out = nullptr; + + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "ADD_RMS_NORM_MUL"; + } + + bool run_whole_graph() override { return true; } + + std::vector fusion_test_nodes() override { return { sum, out }; } + + std::string vars() override { return VARS_TO_STR2(ne, eps); } + + test_add_rms_norm_mul(std::array ne = { 4096, 1, 1, 1 }, float eps = 1e-6f) : ne(ne), eps(eps) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * b = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne.data()); + ggml_tensor * w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ne[0]); + ggml_set_name(a, "a"); + ggml_set_name(b, "b"); + ggml_set_name(w, "w"); + + sum = ggml_add(ctx, a, b); + ggml_set_name(sum, "sum"); + ggml_tensor * normed = ggml_mul(ctx, ggml_rms_norm(ctx, sum, eps), w); + ggml_set_name(normed, "normed"); + + out = ggml_add(ctx, normed, sum); + ggml_set_name(out, "out"); + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + init_tensor_uniform(t, -10.f, 10.f); + } + } +}; + // GGML_OP_UNARY(RELU) + GGML_OP_SQR (fused operation) struct test_relu_sqr : public test_case { const ggml_type type; @@ -11801,6 +11847,13 @@ static std::vector> make_test_cases_eval() { } } + // decode-shaped residual rows: below, at and above the fused path's limits, odd row counts, batches + for (int64_t n : { 1020, 1024, 4096, 5120, 8192, 8196, 16384 }) { + for (int64_t rows : { 1, 3, 4 }) { + test_cases.emplace_back(new test_add_rms_norm_mul({ n, rows, 1, 1 }, 1e-6f)); + } + test_cases.emplace_back(new test_add_rms_norm_mul({ n, 2, 3, 1 }, 1e-6f)); + } for (uint32_t n : {64, 1025}) { test_cases.emplace_back(new test_add_add(GGML_TYPE_F32, GGML_TYPE_F32, { n, 5, 4, 3 }, false, false)); test_cases.emplace_back(new test_add_add(GGML_TYPE_F32, GGML_TYPE_F32, { n, 5, 4, 3 }, true, false)); From 80325823d47ce8d02ae487de4b5563b2695684e4 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Sat, 21 Nov 2026 13:21:47 +0100 Subject: [PATCH 021/401] ui: open the context gauge panel on click as a popover (#32685) * ui: open the context gauge panel on click as a popover Assisted-by: Claude (Opus 5.5 Medium) * ui: give the context gauge trigger the ghost button hover Assisted-by: Claude (Opus 5.5 Medium) --- .../app/chat/ChatForm/ChatForm.svelte | 6 +- .../ChatFormContextGauge.svelte | 94 +++++++++------- .../ContextGaugeDrawer.svelte | 20 ++++ ...ePopup.svelte => ContextGaugePanel.svelte} | 106 +++++------------- .../gauge-popup.svelte.ts | 98 +--------------- .../context-gauge-popup.constants.ts | 8 -- ui/apps/chat/src/lib/constants/index.ts | 1 - .../context-panel-mobile.svelte.test.ts | 42 ------- .../tests/client/context-panel.svelte.test.ts | 62 ++++++++++ .../form/ChatFormContextGauge.stories.svelte | 20 ++-- 10 files changed, 185 insertions(+), 272 deletions(-) create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDrawer.svelte rename ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/{ContextGaugePopup.svelte => ContextGaugePanel.svelte} (59%) delete mode 100644 ui/apps/chat/src/lib/constants/context-gauge-popup.constants.ts delete mode 100644 ui/apps/chat/tests/client/context-panel-mobile.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/context-panel.svelte.test.ts diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index 727ceccd7894..b9845cc866ba 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -1,5 +1,5 @@ + + + + + + Context + + + Context window usage of the model the chat runs + + + + + + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePanel.svelte similarity index 59% rename from ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte rename to ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePanel.svelte index fbd645720665..5a0501947378 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePanel.svelte @@ -2,54 +2,29 @@ import { colorLevelBgClass, colorLevelTextClass } from './context-gauge'; import ContextGaugeDetails from './ContextGaugeDetails.svelte'; import ContextGaugeLoadModel from './ContextGaugeLoadModel.svelte'; - import { - gaugeCardEnter, - gaugeCardLeave, - gaugePopup, - gaugePopupClose - } from './gauge-popup.svelte'; + import { gaugePopupClose } from './gauge-popup.svelte'; import { Button } from '@ggml-org/llama-ui/ui/button'; - import * as Drawer from '@ggml-org/llama-ui/ui/drawer'; import { FoldVertical, Loader2 } from '@lucide/svelte'; import { useContextGauge } from '#lib/hooks/use-context-gauge.svelte.ts'; - import { agenticStore, chatStore, conversationsStore, deviceStore } from '#lib/stores/index.ts'; + import { agenticStore, chatStore, conversationsStore } from '#lib/stores/index.ts'; import { formatParameters } from '#lib/utils/formatters.ts'; + interface Props { + /** The drawer brings its own title, so the panel drops the inline one there. */ + inDrawer?: boolean; + } + + let { inDrawer = false }: Props = $props(); + const gauge = useContextGauge(); // The gauge hook wraps a processing state instance that only follows the - // live stream while its own monitoring flag is set, so the card instance + // live stream while its own monitoring flag is set, so the panel instance // starts monitoring like the dial does. $effect(() => { gauge.startMonitoring(); }); - let cardEl = $state(null); - - // Any press outside the card and outside the dial closes the card. - // Presses on the dial are excluded because the dial handles its own - // toggle; the listener only exists while the card is open. A phone shows - // the panel in a drawer instead, which brings its own dismissal. - $effect(() => { - if (!gaugePopup.open || deviceStore.isMobile) return; - - const onPointerDown = (event: PointerEvent) => { - const target = event.target; - - if (!(target instanceof Node)) return; - - if (cardEl?.contains(target)) return; - - if (target instanceof Element && target.closest('[data-context-gauge-trigger]')) return; - - gaugePopupClose(); - }; - - document.addEventListener('pointerdown', onPointerDown, true); - - return () => document.removeEventListener('pointerdown', onPointerDown, true); - }); - const showProgressBar = $derived( gauge.contextTotal !== null && gauge.contextTotal > 0 && @@ -60,7 +35,7 @@ const activeConvId = $derived(conversationsStore.activeConversation?.id ?? null); - // A summary in flight keeps the card open for the numbers, so the action + // A summary in flight keeps the panel open for the numbers, so the action // reports the run instead of inviting a second one. const isCompacting = $derived(activeConvId !== null && chatStore.isCompacting(activeConvId)); @@ -149,47 +124,20 @@ {/if} {/snippet} -{#if deviceStore.isMobile} - - - - Context - - - Context window usage of the model the chat runs - - - -
- {@render usage()} - - {@render body()} - - {@render compactAction()} -
-
-
-{:else if gaugePopup.open} -
-
-
- Context - - · - - {@render usage()} -
- - {@render body()} - - {@render compactAction()} +
+ {#if inDrawer} + {@render usage()} + {:else} +
+ Context + + · + + {@render usage()}
-
-{/if} + {/if} + + {@render body()} + + {@render compactAction()} +
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts index 4885326fbdfb..9e2f50cd9429 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts @@ -1,99 +1,11 @@ -// Shared state for the context gauge popup. The dial and the card live in -// different DOM subtrees, so open state and placement are coordinated here. -// centerX and bottom place the card just above the dial: both are measured -// once at open time, relative to the closest form ancestor; the dial and -// the card share that positioning frame, so the values stay exact for the -// whole time the card is open. -// Mouse pointers open on hover with a short grace delay to travel from -// dial to card; touch pointers toggle on tap. -import { - CONTEXT_GAUGE_CARD_HALF_WIDTH_PX, - CONTEXT_GAUGE_CLOSE_GRACE_MS, - CONTEXT_GAUGE_DIAL_GAP_PX, - CONTEXT_GAUGE_EDGE_MARGIN_PX -} from '#lib/constants/index.ts'; +// Open state of the context panel, shared by the gauge's popover and the phone's drawer: the +// phone's corner key and the drawer live in different DOM subtrees. +export const gaugePopup = $state({ open: false }); -let closeTimer: ReturnType | undefined; -let lastPointerType = ''; - -export const gaugePopup = $state({ bottom: 0, centerX: 0, open: false }); - -function openFrom(trigger: HTMLElement): void { - clearTimeout(closeTimer); - const frame = trigger.closest('form'); - - if (frame) { - const frameRect = frame.getBoundingClientRect(); - const triggerRect = trigger.getBoundingClientRect(); - const centerX = triggerRect.left + triggerRect.width / 2 - frameRect.left; - const min = CONTEXT_GAUGE_CARD_HALF_WIDTH_PX + CONTEXT_GAUGE_EDGE_MARGIN_PX; - const max = frameRect.width - CONTEXT_GAUGE_CARD_HALF_WIDTH_PX - CONTEXT_GAUGE_EDGE_MARGIN_PX; - - gaugePopup.centerX = Math.min(Math.max(centerX, min), Math.max(min, max)); - gaugePopup.bottom = frameRect.bottom - triggerRect.top + CONTEXT_GAUGE_DIAL_GAP_PX; - } - - gaugePopup.open = true; -} - -function toggleFrom(trigger: HTMLElement): void { - if (gaugePopup.open) { - clearTimeout(closeTimer); - gaugePopup.open = false; - } else { - openFrom(trigger); - } +export function gaugePopupToggle(): void { + gaugePopup.open = !gaugePopup.open; } export function gaugePopupClose(): void { - clearTimeout(closeTimer); gaugePopup.open = false; } - -export function gaugeTriggerPointerDown(event: PointerEvent): void { - lastPointerType = event.pointerType; -} - -export function gaugeTriggerClick(event: MouseEvent): void { - if (lastPointerType !== 'touch') return; - - toggleFrom(event.currentTarget as HTMLElement); -} - -export function gaugeTriggerKeydown(event: KeyboardEvent): void { - if (event.key !== 'Enter' && event.key !== ' ') return; - - event.preventDefault(); - toggleFrom(event.currentTarget as HTMLElement); -} - -export function gaugeTriggerEnter(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - openFrom(event.currentTarget as HTMLElement); -} - -export function gaugeTriggerLeave(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - scheduleClose(); -} - -export function gaugeCardEnter(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - clearTimeout(closeTimer); -} - -export function gaugeCardLeave(event: PointerEvent): void { - if (event.pointerType !== 'mouse') return; - - scheduleClose(); -} - -function scheduleClose(): void { - clearTimeout(closeTimer); - closeTimer = setTimeout(() => { - gaugePopup.open = false; - }, CONTEXT_GAUGE_CLOSE_GRACE_MS); -} diff --git a/ui/apps/chat/src/lib/constants/context-gauge-popup.constants.ts b/ui/apps/chat/src/lib/constants/context-gauge-popup.constants.ts deleted file mode 100644 index fe2e6a1b5cf3..000000000000 --- a/ui/apps/chat/src/lib/constants/context-gauge-popup.constants.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Half of the card width, matching the w-64 class on the card. -export const CONTEXT_GAUGE_CARD_HALF_WIDTH_PX = 128; -// Minimum distance kept between the card and the form edges. -export const CONTEXT_GAUGE_EDGE_MARGIN_PX = 8; -// Gap between the top of the dial and the bottom edge of the card. -export const CONTEXT_GAUGE_DIAL_GAP_PX = 8; -// Grace delay before closing, letting the pointer travel from dial to card. -export const CONTEXT_GAUGE_CLOSE_GRACE_MS = 150; diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts index 6f6ac5a10c20..399e75ac7e22 100644 --- a/ui/apps/chat/src/lib/constants/index.ts +++ b/ui/apps/chat/src/lib/constants/index.ts @@ -14,7 +14,6 @@ export * from './icons.constants'; export * from './attachment-menu.constants'; export * from './auto-scroll.constants'; export * from './context-gauge-dial.constants'; -export * from './context-gauge-popup.constants'; export * from './conversation-import.constants'; export * from './conversation-search.constants'; export * from './binary-detection.constants'; diff --git a/ui/apps/chat/tests/client/context-panel-mobile.svelte.test.ts b/ui/apps/chat/tests/client/context-panel-mobile.svelte.test.ts deleted file mode 100644 index 5e385dc46555..000000000000 --- a/ui/apps/chat/tests/client/context-panel-mobile.svelte.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Guards the phone shape of the context panel: a phone shows it in a drawer, while a -// wider screen keeps the card anchored above the dial. - -import ContextGaugePopup from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte'; -import { gaugePopup } from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { page } from 'vitest/browser'; -import { render } from 'vitest-browser-svelte'; - -const PHONE = { height: 844, width: 390 }; -const DESKTOP = { height: 900, width: 1280 }; - -describe('context panel on a phone', () => { - beforeEach(async () => { - gaugePopup.open = false; - }); - - afterEach(async () => { - gaugePopup.open = false; - await page.viewport(DESKTOP.width, DESKTOP.height); - }); - - it('shows the panel in a drawer', async () => { - await page.viewport(PHONE.width, PHONE.height); - - const screen = render(ContextGaugePopup); - - gaugePopup.open = true; - - await expect.element(screen.getByRole('heading', { name: 'Context' })).toBeVisible(); - }); - - it('keeps the anchored card on a wider screen', async () => { - await page.viewport(DESKTOP.width, DESKTOP.height); - - const screen = render(ContextGaugePopup); - - gaugePopup.open = true; - - await expect.element(screen.getByRole('status')).toBeVisible(); - }); -}); diff --git a/ui/apps/chat/tests/client/context-panel.svelte.test.ts b/ui/apps/chat/tests/client/context-panel.svelte.test.ts new file mode 100644 index 000000000000..d9c46b6e4920 --- /dev/null +++ b/ui/apps/chat/tests/client/context-panel.svelte.test.ts @@ -0,0 +1,62 @@ +// Guards how the context panel opens: a phone shows it in a drawer, while a wider screen opens a +// popover from the gauge on click (not on hover) and closes it on Escape or a click outside. + +import ChatFormContextGauge from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte'; +import ContextGaugeDrawer from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDrawer.svelte'; +import { gaugePopup } from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { page, userEvent } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const PHONE = { height: 844, width: 390 }; +const DESKTOP = { height: 900, width: 1280 }; + +describe('context panel', () => { + beforeEach(async () => { + gaugePopup.open = false; + }); + + afterEach(async () => { + gaugePopup.open = false; + await page.viewport(DESKTOP.width, DESKTOP.height); + }); + + it('shows the panel in a drawer on a phone', async () => { + await page.viewport(PHONE.width, PHONE.height); + + const screen = render(ContextGaugeDrawer); + + gaugePopup.open = true; + + await expect.element(screen.getByRole('heading', { name: 'Context' })).toBeVisible(); + }); + + it('opens the popover on click, not on hover, on a wider screen', async () => { + await page.viewport(DESKTOP.width, DESKTOP.height); + + render(ChatFormContextGauge); + + const trigger = page.getByRole('button', { name: 'Context usage' }); + + await trigger.hover(); + expect(gaugePopup.open).toBe(false); + + await trigger.click(); + await expect.element(page.getByRole('dialog')).toBeVisible(); + + await userEvent.keyboard('{Escape}'); + await expect.poll(() => gaugePopup.open).toBe(false); + }); + + it('closes the popover on a click outside', async () => { + await page.viewport(DESKTOP.width, DESKTOP.height); + + render(ChatFormContextGauge); + + await page.getByRole('button', { name: 'Context usage' }).click(); + await expect.element(page.getByRole('dialog')).toBeVisible(); + + await userEvent.click(document.body, { position: { x: 5, y: 5 } }); + await expect.poll(() => gaugePopup.open).toBe(false); + }); +}); diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte index a0416fd5d03d..b5939a48ea9c 100644 --- a/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/form/ChatFormContextGauge.stories.svelte @@ -10,8 +10,9 @@ } from './fixtures'; import { defineMeta } from '@storybook/addon-svelte-csf'; import ChatFormContextGauge from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ChatFormContextGauge.svelte'; - import ContextGaugePopup from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugePopup.svelte'; + import ContextGaugeDrawer from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/ContextGaugeDrawer.svelte'; import { gaugePopupClose } from '#lib/components/app/chat/ChatForm/ChatFormContextGauge/gauge-popup.svelte.ts'; + import { deviceStore } from '#lib/stores/index.ts'; import { userEvent, within } from 'storybook/test'; const { Story } = defineMeta({ @@ -24,7 +25,7 @@ const N_CTX = 32768; - // the popup state is module-wide, so close it around each story + // the open state is module-wide, so close it around each story function seedUsage(promptTokens: number) { return () => { gaugePopupClose(); @@ -67,21 +68,22 @@ }; } + // the popover renders in a portal, so it is looked up on the whole page async function openPopup({ canvasElement }: { canvasElement: HTMLElement }) { - const canvas = within(canvasElement); - - canvas.getByRole('button', { name: 'Context usage' }).focus(); - await userEvent.keyboard('{Enter}'); - await canvas.findByRole('status'); + await userEvent.click(within(canvasElement).getByRole('button', { name: 'Context usage' })); + await within(document.body).findByRole('dialog'); } {#snippet frame()} - +
- + + {#if deviceStore.isMobile} + + {/if} {/snippet} From 44c20b1c0a1c77fd629fc5d032a5d7fa5843ebca Mon Sep 17 00:00:00 2001 From: Titaniumtown Date: Sat, 21 Nov 2026 04:38:00 -0800 Subject: [PATCH 022/401] sycl: column-blocked gated_delta_net kernel (#32456) --- ggml/src/ggml-sycl/gated_delta_net.cpp | 263 ++++++++++++++----------- tests/test-backend-ops.cpp | 29 ++- 2 files changed, 176 insertions(+), 116 deletions(-) diff --git a/ggml/src/ggml-sycl/gated_delta_net.cpp b/ggml/src/ggml-sycl/gated_delta_net.cpp index 8468bbf5bd07..63535a945e61 100644 --- a/ggml/src/ggml-sycl/gated_delta_net.cpp +++ b/ggml/src/ggml-sycl/gated_delta_net.cpp @@ -6,7 +6,13 @@ #include -template +// Warps per work-group. 2 is 13% faster than 4 at 4 columns per warp on Arc Pro B70. +static constexpr int gdn_warps = 2; +// State columns per warp when there are enough heads, see launch_gated_delta_net. +static constexpr int gdn_cols_wide = 4; + +// C is the number of state columns per warp: a token's q/k shard is loaded once and shared by these columns. +template void gated_delta_net_sycl(const float * q, const float * k, const float * v, @@ -34,9 +40,10 @@ void gated_delta_net_sycl(const float * q, auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>(); const uint32_t h_idx = item_ct1.get_group(2); const uint32_t sequence = item_ct1.get_group(1); - // each warp owns one column, using warp-level primitives to reduce across rows + // each warp owns C columns, using warp-level primitives to reduce across rows const int lane = item_ct1.get_local_id(2); - const int col = item_ct1.get_group(0) * item_ct1.get_local_range(1) + item_ct1.get_local_id(1); + const int warp = item_ct1.get_group(0) * item_ct1.get_local_range(1) + item_ct1.get_local_id(1); + const int col0 = warp * C; const uint32_t iq1 = fastmodulo(h_idx, neqk1_magic); const uint32_t iq3 = fastdiv(sequence, rq3_magic); @@ -48,94 +55,145 @@ void gated_delta_net_sycl(const float * q, const int64_t state_in_offset = sequence * H * S_v * S_v + h_idx * S_v * S_v; const int64_t state_out_offset = (sequence * H + h_idx) * S_v * S_v; state += state_out_offset; - curr_state += state_in_offset + col * S_v; + curr_state += state_in_offset; attn_data += (sequence * n_tokens * H + h_idx) * S_v; constexpr int warp_size = ggml_sycl_get_physical_warp_size() < S_v ? ggml_sycl_get_physical_warp_size() : S_v; static_assert(S_v % warp_size == 0, "S_v must be a multiple of warp_size"); + static_assert(S_v % (C * gdn_warps) == 0, "S_v must be a multiple of the columns per work-group"); + static_assert(C <= warp_size, "the attn store puts column c in lane c"); constexpr int rows_per_lane = (S_v + warp_size - 1) / warp_size; - float s_shard[rows_per_lane]; + float s_shard[C][rows_per_lane]; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - s_shard[r] = curr_state[i]; + for (int c = 0; c < C; c++) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + const int i = r * warp_size + lane; + s_shard[c][r] = curr_state[(col0 + c) * S_v + i]; + } } // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. // When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned. + const float * qp = q + iq3 * sq3 + iq1 * sq1 + lane; + const float * kp = k + iq3 * sq3 + iq1 * sq1 + lane; + const float * vp = v + sequence * sv3 + h_idx * sv1 + col0; + const float * bp = beta + sequence * sb3 + h_idx * sb1; + const float * gp = g + (sequence * sb3 + h_idx * sb1) * (KDA ? S_v : 1); + + // q/k of the next token are loaded one iteration ahead to hide the load latency. + float q_next[rows_per_lane]; + float k_next[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + q_next[r] = qp[r * warp_size]; + k_next[r] = kp[r * warp_size]; + } + for (int t = 0; t < n_tokens; t++) { - const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1; - const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1; - const float * v_t = v + sequence * sv3 + t * sv2 + h_idx * sv1; + const float beta_val = *bp; + const float * g_t = gp; + bp += sb2; + gp += sb2 * (KDA ? S_v : 1); + + float q_reg[rows_per_lane]; + float k_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + q_reg[r] = q_next[r]; + k_reg[r] = k_next[r]; + } + if (t + 1 < n_tokens) { + qp += sq2; + kp += sq2; + } + // Load outside the branch: the last token reads its own row again. + // A guarded load is 20% slower at 32 heads on Arc Pro B70. +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + q_next[r] = qp[r * warp_size]; + k_next[r] = kp[r * warp_size]; + } - const int64_t gb_offset = sequence * sb3 + t * sb2 + h_idx * sb1; - const float * beta_t = beta + gb_offset; - const float * g_t = g + gb_offset * (KDA ? S_v : 1); + float v_reg[C]; +#pragma unroll + for (int c = 0; c < C; c++) { + v_reg[c] = vp[c]; + } + vp += sv2; - const float beta_val = *beta_t; + // attn[col] = g * (S^T q)[col] + delta[col] * (k . q), so no reduction waits for delta + float kq_shard = 0.0f; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + kq_shard += k_reg[r] * q_reg[r]; + } + const float kq = warp_reduce_sum(kq_shard); + float out_lane = 0.0f; if constexpr (!KDA) { const float g_val = sycl::native::exp(*g_t); - // kv[col] = (S^T @ k)[col] = sum_i S[i][col] * k[i] - float kv_shard = 0.0f; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - kv_shard += s_shard[r] * k_t[i]; - } - float kv_col = warp_reduce_sum(kv_shard); + for (int c = 0; c < C; c++) { + // x: kv[col] = (S^T k)[col], y: (S^T q)[col] + sycl::float2 acc(0.0f, 0.0f); +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + acc.x() += s_shard[c][r] * k_reg[r]; + acc.y() += s_shard[c][r] * q_reg[r]; + } + acc = warp_reduce_sum(acc); - // delta[col] = (v[col] - g * kv[col]) * beta - float delta_col = (v_t[col] - g_val * kv_col) * beta_val; + // delta[col] = (v[col] - g * kv[col]) * beta + const float delta_col = (v_reg[c] - g_val * acc.x()) * beta_val; - // fused: S[i][col] = g * S[i][col] + k[i] * delta[col] - // attn[col] = (S^T @ q)[col] = sum_i S[i][col] * q[i] - float attn_partial = 0.0f; + // S[i][col] = g * S[i][col] + k[i] * delta[col] #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - s_shard[r] = g_val * s_shard[r] + k_t[i] * delta_col; - attn_partial += s_shard[r] * q_t[i]; - } - - float attn_col = warp_reduce_sum(attn_partial); + for (int r = 0; r < rows_per_lane; r++) { + s_shard[c][r] = g_val * s_shard[c][r] + k_reg[r] * delta_col; + } - if (lane == 0) { - attn_data[col] = attn_col * scale; + // the reductions broadcast, so lane c already holds column c's result + out_lane = (lane == c) ? (g_val * acc.y() + delta_col * kq) * scale : out_lane; } } else { - // kv[col] = sum_i g[i] * S[i][col] * k[i] - float kv_shard = 0.0f; + float g_reg[rows_per_lane]; #pragma unroll for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - kv_shard += sycl::native::exp(g_t[i]) * s_shard[r] * k_t[i]; + g_reg[r] = sycl::native::exp(g_t[r * warp_size + lane]); } - float kv_col = warp_reduce_sum(kv_shard); +#pragma unroll + for (int c = 0; c < C; c++) { + // x: kv[col] = sum_i g[i] * S[i][col] * k[i], y: sum_i g[i] * S[i][col] * q[i] + sycl::float2 acc(0.0f, 0.0f); +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + const float gs = g_reg[r] * s_shard[c][r]; + acc.x() += gs * k_reg[r]; + acc.y() += gs * q_reg[r]; + } + acc = warp_reduce_sum(acc); - // delta[col] = (v[col] - kv[col]) * beta - float delta_col = (v_t[col] - kv_col) * beta_val; + // delta[col] = (v[col] - kv[col]) * beta + const float delta_col = (v_reg[c] - acc.x()) * beta_val; - // fused: S[i][col] = g[i] * S[i][col] + k[i] * delta[col] - // attn[col] = (S^T @ q)[col] = sum_i S[i][col] * q[i] - float attn_partial = 0.0f; + // S[i][col] = g[i] * S[i][col] + k[i] * delta[col] #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - s_shard[r] = sycl::native::exp(g_t[i]) * s_shard[r] + k_t[i] * delta_col; - attn_partial += s_shard[r] * q_t[i]; - } - - float attn_col = warp_reduce_sum(attn_partial); + for (int r = 0; r < rows_per_lane; r++) { + s_shard[c][r] = g_reg[r] * s_shard[c][r] + k_reg[r] * delta_col; + } - if (lane == 0) { - attn_data[col] = attn_col * scale; + out_lane = (lane == c) ? (acc.y() + delta_col * kq) * scale : out_lane; } } + if (lane < C) { + attn_data[col0 + lane] = out_lane; + } + attn_data += S_v * H; @@ -143,21 +201,26 @@ void gated_delta_net_sycl(const float * q, if constexpr (keep_rs_t) { const int target_slot = (int) n_tokens - 1 - t; if (target_slot >= 0 && target_slot < K) { - float * curr_state = state + target_slot * state_slot_stride; + float * slot_col = state + target_slot * state_slot_stride + col0 * S_v + lane; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - curr_state[col * S_v + i] = s_shard[r]; + for (int c = 0; c < C; c++) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + slot_col[c * S_v + r * warp_size] = s_shard[c][r]; + } } } } } if constexpr (!keep_rs_t) { + float * out_col = state + col0 * S_v + lane; #pragma unroll - for (int r = 0; r < rows_per_lane; r++) { - const int i = r * warp_size + lane; - state[col * S_v + i] = s_shard[r]; + for (int c = 0; c < C; c++) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + out_col[c * S_v + r * warp_size] = s_shard[c][r]; + } } } } @@ -193,60 +256,36 @@ static void launch_gated_delta_net(const float * q_d, //TODO: Add chunked kernel for even faster pre-fill const int warp_size = ggml_sycl_info().devices[ggml_sycl_get_device()].warp_size; - const int num_warps = 4; - dpct::dim3 grid_dims(H, n_seqs, (S_v + num_warps - 1) / num_warps); - dpct::dim3 block_dims(warp_size <= S_v ? warp_size : S_v, num_warps, 1); - const sycl::uint3 neqk1_magic = init_fastdiv_values(neqk1); const sycl::uint3 rq3_magic = init_fastdiv_values(rq3); - switch (S_v) { - case 16: - { - constexpr int sv = 16; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, - sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2, - sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; - case 32: - { - constexpr int sv = 32; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, - sq1, sq2, sq3, sv1, sv2, sv3, sb1, sb2, - sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; - case 64: { - { - constexpr int sv = 64; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl( - q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, - sq3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; - } - case 128: { - { - constexpr int sv = 128; - stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), - [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { - gated_delta_net_sycl( - q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, - sq3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); - }); - } - break; + auto launch = [&](auto sv_c, auto c_c) { + constexpr int sv = decltype(sv_c)::value; + constexpr int C = decltype(c_c)::value; + dpct::dim3 grid_dims(H, n_seqs, sv / (C * gdn_warps)); + dpct::dim3 block_dims(warp_size <= sv ? warp_size : sv, gdn_warps, 1); + stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims), + [=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] { + gated_delta_net_sycl( + q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sv1, sv2, + sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + }); + }; + // gdn_cols_wide columns per warp cut the q/k loads but launch fewer warps, so with few heads 1 column is faster. + // The 1024-warp switch point is measured on Arc Pro B70. + auto launch_sv = [&](auto sv_c) { + if (H * n_seqs * S_v / gdn_cols_wide >= 1024) { + launch(sv_c, std::integral_constant{}); + } else { + launch(sv_c, std::integral_constant{}); } + }; + + switch (S_v) { + case 16: launch_sv(std::integral_constant{}); break; + case 32: launch_sv(std::integral_constant{}); break; + case 64: launch_sv(std::integral_constant{}); break; + case 128: launch_sv(std::integral_constant{}); break; default: GGML_ABORT("fatal error"); break; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index fbf5c12d33de..711674958542 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -5317,16 +5317,22 @@ struct test_gated_delta_net : public test_case { const bool padded_v; const bool padded_q; const bool permuted_k; + // lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence + const float g_min; std::string vars() override { - return VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); + std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); + if (g_min != -20.0f) { + s += "," + VAR_TO_STR(g_min); + } + return s; } test_gated_delta_net(ggml_type type = GGML_TYPE_F32, int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1, - int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false) + int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f) : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), - v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k) {} + v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q; @@ -5378,7 +5384,7 @@ struct test_gated_delta_net : public test_case { for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { if (ggml_is_view_op(t->op)) { continue; } if (strcmp(t->name, "g") == 0) { - init_tensor_uniform(t, correlated ? -1e-4f : -20.0f, -1e-4f); + init_tensor_uniform(t, correlated ? -1e-4f : g_min, -1e-4f); } else if (strcmp(t->name, "beta") == 0) { init_tensor_uniform(t, correlated ? 0.9f : 0.0f, correlated ? 0.9f : 1.0f); } else if (correlated && strcmp(t->name, "k") == 0) { @@ -13765,6 +13771,19 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true)); } + // mild decay keeps the state alive across the sequence; qwen35 prefill layout with K=5 snapshots + for (int64_t n : { 5, 300, 2048 }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + } + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + // a backend may pick its kernel by head count: few and many heads, per head size, plain and KDA + for (int64_t s : { 16, 32, 64, 128 }) { + for (int64_t h : { 4 * 128 / s, 64 * 128 / s }) { + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, /*K=*/4, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); + } + } // K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first // (slot 0 = final state, slot s = state s tokens back). @@ -13781,6 +13800,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1, 2)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1, 4)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2, 4)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1, 4)); test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1, 4)); #if 0 @@ -14444,6 +14464,7 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 3, false, false, 5)); // qwen35 PP-2048, K=5 // lightning_indexer for (int kv : { 256, 4096, 65536 }) { From c6610333490e1d28d2700982064b76baf2bcb08c Mon Sep 17 00:00:00 2001 From: Titaniumtown Date: Sat, 21 Nov 2026 05:11:14 -0800 Subject: [PATCH 023/401] sycl: add IQ4_NL and IQ4_XS weight reorder (#31998) --- ggml/src/ggml-sycl/convert.cpp | 22 +++++++- ggml/src/ggml-sycl/dequantize.hpp | 64 +++++++++++++++++++++ ggml/src/ggml-sycl/fused-gemm.cpp | 35 +++++++++--- ggml/src/ggml-sycl/getrows.cpp | 14 +++++ ggml/src/ggml-sycl/ggml-sycl.cpp | 26 ++++++++- ggml/src/ggml-sycl/mmvq.cpp | 80 +++++++++++++++++++-------- ggml/src/ggml-sycl/quants.hpp | 65 ++++++++++++++++++++++ ggml/src/ggml-sycl/vecdotq.hpp | 92 +++++++++++++++++++++++++++++++ tests/test-backend-ops.cpp | 12 ++-- 9 files changed, 372 insertions(+), 38 deletions(-) diff --git a/ggml/src/ggml-sycl/convert.cpp b/ggml/src/ggml-sycl/convert.cpp index 1e7edf3b8a82..e991e29e7129 100644 --- a/ggml/src/ggml-sycl/convert.cpp +++ b/ggml/src/ggml-sycl/convert.cpp @@ -516,6 +516,16 @@ static void dequantize_row_iq4_nl_sycl(const void *vx, dst_t *y, const int64_t k } } +template +static void dequantize_row_iq4_sycl_reorder(const void * vx, dst_t * y, const int64_t k, dpct::queue_ptr stream) { + // flat range<1>, four qs bytes (8 outputs) per item + GGML_ASSERT(k % ggml_sycl_reordered::block_q_t::traits::qk == 0); + stream->parallel_for(sycl::range<1>((size_t) (k / 8)), + [=](sycl::id<1> idx) { + dequantize_block_iq4_reorder_wide(vx, y, k, idx); + }); +} + template static void dequantize_row_mxfp4_sycl(const void * vx, dst_t * y, const int64_t k, dpct::queue_ptr stream) { const int nb = (k + QK_K - 1) / QK_K; @@ -743,9 +753,17 @@ static to_t_sycl_t ggml_get_dequant_sycl(ggml_type type, ggml_tensor * ds return dequantize_row_iq3_s_sycl; } case GGML_TYPE_IQ4_XS: - return dequantize_row_iq4_xs_sycl; + if (is_reordered_src0(dst)) { + return dequantize_row_iq4_sycl_reorder; + } else { + return dequantize_row_iq4_xs_sycl; + } case GGML_TYPE_IQ4_NL: - return dequantize_row_iq4_nl_sycl; + if (is_reordered_src0(dst)) { + return dequantize_row_iq4_sycl_reorder; + } else { + return dequantize_row_iq4_nl_sycl; + } case GGML_TYPE_MXFP4: if (is_reordered_src0(dst)) { return dequantize_row_mxfp4_sycl_reorder; diff --git a/ggml/src/ggml-sycl/dequantize.hpp b/ggml/src/ggml-sycl/dequantize.hpp index eb94771d673f..98f1aff6f3b8 100644 --- a/ggml/src/ggml-sycl/dequantize.hpp +++ b/ggml/src/ggml-sycl/dequantize.hpp @@ -15,6 +15,7 @@ #include "common.hpp" #include "convert.hpp" +#include "quants.hpp" typedef void (*dequantize_kernel_t)(const void * vx, const int64_t ib, const int iqs, dfloat2 & v); typedef void (*dequantize_kernel_t_reorder)(const void *d, const int64_t ib, const void *qs, @@ -674,6 +675,15 @@ static __dpct_inline__ void dequantize_iq4_nl(const void *vx, const int64_t ib, v.y() = dequantize_one(iqs + 1); } +static __dpct_inline__ void dequantize_iq4_nl_reorder(const void * d_ptr, const int64_t ib, const void * qs, + const int iqs, dfloat2 & v) { + const float d = (float) ((const sycl::half *) d_ptr)[ib]; + const uint8_t q = ((const uint8_t *) qs)[iqs]; + + v.x() = d * kvalues_iq4nl[q & 0xF]; + v.y() = d * kvalues_iq4nl[q >> 4]; +} + static __dpct_inline__ void dequantize_iq4_xs(const void *vx, const int64_t ib, const int iqs, dfloat2 &v) { #if QK_K == 256 @@ -1758,6 +1768,60 @@ dequantize_block_iq4_xs(const void *__restrict__ vx, dst_t *__restrict__ yy, } } +// reordered IQ4_NL / IQ4_XS: qs bytes iq .. iq + 3 of 32-value group g to y[iq + j] and y[iq + 16 + j], with y the +// group's first output, in two vec stores as for MXFP4; tail is the first byte after all qs +template +static __dpct_inline__ void dequantize_iq4_reorder_quad(const uint8_t * __restrict__ x, + const uint8_t * __restrict__ tail, const int64_t g, + const int iq, dst_t * __restrict__ y) { + const uint8_t * qs = x + 16 * g + iq; + const float d = ggml_sycl_reordered::iq4_group_scale(tail, g); + + sycl::vec lo, hi; +#pragma unroll + for (int j = 0; j < 4; ++j) { + lo[j] = d * kvalues_iq4nl[qs[j] & 0xf]; + hi[j] = d * kvalues_iq4nl[qs[j] >> 4]; + } + *reinterpret_cast *>(y + iq) = lo; + *reinterpret_cast *>(y + iq + 16) = hi; +} + +// flat range over k / 8 items: item i takes group i / 4 from qs byte 4 * (i % 4) +template +static void dequantize_block_iq4_reorder_wide(const void * __restrict__ vx, dst_t * __restrict__ yy, int64_t k, + const sycl::id<1> idx) { + const int64_t i = (int64_t) idx[0]; + const int64_t g = i / 4; + const uint8_t * x = (const uint8_t *) vx; + dequantize_iq4_reorder_quad(x, x + k / 2, g, (int) (4 * (i % 4)), yy + 32 * g); +} + +// item t (0..31) of block ib dequantizes four qs bytes of sub-block t/4 into y, the output of block ib +template +static __dpct_inline__ void dequantize_block_iq4_xs_reorder(const void * __restrict__ vx, dst_t * __restrict__ y, + const int64_t ib, const int t, const int64_t nb) { + const int ib32 = t / 4; + const int iq = 4 * (t % 4); + + const uint8_t * qs = (const uint8_t *) vx + ib * (QK_K / 2) + 16 * ib32 + iq; + const uint8_t * meta = (const uint8_t *) vx + nb * (QK_K / 2) + ib * offsetof(block_iq4_xs, qs); + const uint16_t scales_h = *(const uint16_t *) (meta + offsetof(block_iq4_xs, scales_h)); + const uint8_t scales_l = meta[offsetof(block_iq4_xs, scales_l) + ib32 / 2]; + const float d = (float) *(const ggml_half *) (meta + offsetof(block_iq4_xs, d)) * + ((((scales_l >> (4 * (ib32 % 2))) & 0xf) | (((scales_h >> (2 * ib32)) & 3) << 4)) - 32); + + sycl::vec lo, hi; +#pragma unroll + for (int j = 0; j < 4; ++j) { + lo[j] = d * kvalues_iq4nl[qs[j] & 0xf]; + hi[j] = d * kvalues_iq4nl[qs[j] >> 4]; + } + dst_t * yb = y + 32 * ib32 + iq; + *reinterpret_cast *>(yb) = lo; + *reinterpret_cast *>(yb + 16) = hi; +} + template static void dequantize_block_mxfp4(const void * __restrict__ vx, dst_t * __restrict__ yy, const sycl::nd_item<3> &item_ct1) { diff --git a/ggml/src/ggml-sycl/fused-gemm.cpp b/ggml/src/ggml-sycl/fused-gemm.cpp index d0525e3a0bb8..89096d561c41 100644 --- a/ggml/src/ggml-sycl/fused-gemm.cpp +++ b/ggml/src/ggml-sycl/fused-gemm.cpp @@ -1,5 +1,6 @@ #include "fused-gemm.hpp" #include "fused-gemm-esimd.hpp" +#include "quants.hpp" #include @@ -421,14 +422,10 @@ static __dpct_inline__ void fg_pack_quarter(const float * __restrict__ t, typena } } +// 32 values from 16 qs bytes, as in IQ4_NL blocks and IQ4_XS sub-blocks: the low nibbles fill the +// first half of the step and the high nibbles the second, so the halves land at a[0..7] and a[8..15] template -static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, const int kb, typename E::pair * a) { - FG_SUPERBLOCK(block_iq4_xs); - // low nibbles fill the first half of the step, high nibbles the second, so the two halves - // land at a[0..7] and a[8..15] and no quarter loop is needed - const float d = (float) blk->d * - ((((blk->scales_l[ib / 2] >> (4 * (ib % 2))) & 0xf) | (((blk->scales_h >> (2 * ib)) & 3) << 4)) - 32); - const uint8_t * q4 = blk->qs + 16 * ib; +static __dpct_inline__ void fg_decode_iq4(const uint8_t * __restrict__ q4, const float d, typename E::pair * a) { #pragma unroll for (int j = 0; j < 8; ++j) { a[j] = E::make(d * kvalues_iq4nl[q4[2 * j] & 0xf], d * kvalues_iq4nl[q4[2 * j + 1] & 0xf]); @@ -436,6 +433,14 @@ static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, c } } +template +static __dpct_inline__ void fg_stage_a(const block_iq4_xs * __restrict__ xrow, const int kb, typename E::pair * a) { + FG_SUPERBLOCK(block_iq4_xs); + const float d = (float) blk->d * + ((((blk->scales_l[ib / 2] >> (4 * (ib % 2))) & 0xf) | (((blk->scales_h >> (2 * ib)) & 3) << 4)) - 32); + fg_decode_iq4(blk->qs + 16 * ib, d, a); +} + template static __dpct_inline__ void fg_stage_a(const block_iq3_xxs * __restrict__ xrow, const int kb, typename E::pair * a) { FG_SUPERBLOCK(block_iq3_xxs); @@ -821,6 +826,22 @@ template <> struct fg_soa { } }; +template struct fg_soa_iq4 { + static constexpr bool supported = true; + // [qs][per-block records]; k step kb is 32-value group kb % groups of block ib + template + static __dpct_inline__ void stage(const uint8_t * x, const size_t nblocks, const size_t ib, const int kb, + typename E::pair * a) { + constexpr int groups = ggml_sycl_reordered::block_q_t::traits::qk / QK4_NL; + const int64_t g = (int64_t) ib * groups + kb % groups; + fg_decode_iq4(x + 16 * g, ggml_sycl_reordered::iq4_group_scale(x + nblocks * groups * 16, g), a); + } +}; + +template <> struct fg_soa : fg_soa_iq4 {}; + +template <> struct fg_soa : fg_soa_iq4 {}; + // one SG_ROWS x BN output tile: B columns [b0, b0 + BN) of packed_b go to dst columns [n0, n1), // n1 - n0 <= BN diff --git a/ggml/src/ggml-sycl/getrows.cpp b/ggml/src/ggml-sycl/getrows.cpp index 7b53e3dcca54..4830186d8243 100644 --- a/ggml/src/ggml-sycl/getrows.cpp +++ b/ggml/src/ggml-sycl/getrows.cpp @@ -588,10 +588,24 @@ void ggml_sycl_op_get_rows(ggml_backend_sycl_context & ctx, ggml_tensor * dst) { src1_i32, (float *)dst->data, ctx.stream()); break; case GGML_TYPE_IQ4_NL: + if (src0_reordered) { + get_rows_sycl_reorder(dst->src[0], dst->src[1], dst, dst->src[0]->data, + src1_i32, (float *)dst->data, ctx.stream()); + break; + } get_rows_sycl(ctx, dst->src[0], dst->src[1], dst, (const float *)dst->src[0]->data, src1_i32, (float *)dst->data, ctx.stream()); break; case GGML_TYPE_IQ4_XS: + if (src0_reordered) { + const void * vx = dst->src[0]->data; + get_rows_sycl_reorder_k<1, QK_K / 8, 1>(dst->src[0], dst->src[1], dst, src1_i32, (float *)dst->data, ctx.stream(), + [=](float * y, int64_t ib, uint8_t * scales_local, const sycl::nd_item<1> & item_ct1, int64_t nb) { + dequantize_block_iq4_xs_reorder(vx, y, ib, (int) item_ct1.get_local_id(0), nb); + GGML_UNUSED(scales_local); + }); + break; + } get_rows_sycl(ctx, dst->src[0], dst->src[1], dst, (const float *)dst->src[0]->data, src1_i32, (float *)dst->data, ctx.stream()); break; diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 3de5f1bd5888..7dda19dfd761 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -832,6 +832,8 @@ ggml_backend_sycl_buffer_init_tensor(ggml_backend_buffer_t buffer, case GGML_TYPE_Q6_K: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_NL: + case GGML_TYPE_IQ4_XS: case GGML_TYPE_MXFP4:{ ggml_tensor_extra_gpu * extra = new ggml_tensor_extra_gpu{}; tensor->extra = extra; @@ -4386,6 +4388,8 @@ inline bool ggml_sycl_supports_reorder_mmvq(enum ggml_type type) { case GGML_TYPE_Q6_K: case GGML_TYPE_IQ3_XXS: case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_NL: + case GGML_TYPE_IQ4_XS: return true; default: return false; @@ -4975,6 +4979,20 @@ static bool reorder_qw_iq3_xxs(uint8_t * data_device, size_t size, dpct::queue_p }, stream); } +// IQ4_NL / IQ4_XS: the qs go to the front, everything before them (d, plus the IQ4_XS scales) is the block's +// record in the tail +template +static bool reorder_qw_iq4(uint8_t * data_device, size_t size, dpct::queue_ptr stream) { + constexpr size_t record_size = offsetof(block_t, qs); + return reorder_qw_planar(__func__, data_device, size, record_size, sizeof(block_t) - record_size, + [](const block_t & x, int64_t ib, uint8_t * tail, int64_t) { + const uint8_t * record = reinterpret_cast(&x); + for (size_t j = 0; j < record_size; ++j) { + tail[ib * record_size + j] = record[j]; + } + }, stream); +} + static bool reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) { uint8_t * data_device = (uint8_t *) src0->data; size_t ncols = src0->ne[0]; @@ -5022,6 +5040,10 @@ static bool reorder_qw(const ggml_tensor * src0, dpct::queue_ptr stream) { return reorder_qw_iq3_xxs(data_device, size, stream); case GGML_TYPE_IQ3_S: return reorder_qw_iq3_s(data_device, size, stream); + case GGML_TYPE_IQ4_NL: + return reorder_qw_iq4(data_device, size, stream); + case GGML_TYPE_IQ4_XS: + return reorder_qw_iq4(data_device, size, stream); default: return false; } @@ -5384,8 +5406,8 @@ static bool ggml_sycl_mul_mat_glu_fused(ggml_backend_sycl_context & ctx, ggml_cg } // gate and up of one type the XMX kernel handles, it needs the reorder layout like the unfused mmvq path - if (wg->type == wu->type && gate->src[1] == act && act->ne[1] >= ggml_sycl_xmx_min_cols(wu->type) && - act->ne[1] <= g_ggml_sycl_xmx_glu_max_cols) { + if (wg->type == wu->type && ggml_sycl_xmx_supports_type(wu->type) && gate->src[1] == act && + act->ne[1] >= ggml_sycl_xmx_min_cols(wu->type) && act->ne[1] <= g_ggml_sycl_xmx_glu_max_cols) { opt_for_reorder(&ctx, wu, act, up, mul_mat_algo::MMVQ); opt_for_reorder(&ctx, wg, act, gate, mul_mat_algo::MMVQ); if (can_use_xmx_batch(ctx.device, wu, act) && can_use_xmx_batch(ctx.device, wg, act) && diff --git a/ggml/src/ggml-sycl/mmvq.cpp b/ggml/src/ggml-sycl/mmvq.cpp index 03464bfaed8f..614b38b2206d 100644 --- a/ggml/src/ggml-sycl/mmvq.cpp +++ b/ggml/src/ggml-sycl/mmvq.cpp @@ -1776,10 +1776,11 @@ static void mul_mat_vec_iq3_xxs_q8_1_sycl(const void *vx, const void *vy, } template -static void reorder_mul_mat_vec_iq3_q8_1_sycl(const void * vx, const void * vy, float * dst, const int ncols, - const int nrows, dpct::queue_ptr stream) { - static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S); - GGML_ASSERT(ncols % QK_K == 0); +static void reorder_mul_mat_vec_iq_q8_1_sycl(const void * vx, const void * vy, float * dst, const int ncols, + const int nrows, dpct::queue_ptr stream) { + static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || + type == GGML_TYPE_IQ4_XS); + GGML_ASSERT(ncols % ggml_sycl_reordered::block_q_t::traits::qk == 0); constexpr size_t num_subgroups = WARP_SIZE; const int block_num_y = ceil_div(nrows, GGML_SYCL_MMV_Y * (int) num_subgroups); const sycl::range<3> block_nums(1, 1, block_num_y); @@ -1795,13 +1796,14 @@ static void reorder_mul_mat_vec_iq3_q8_1_sycl(const void * vx, const void * vy, } template -static void reorder_mul_mat_vec_iq3_q8_1_sycl_ncols( +static void reorder_mul_mat_vec_iq_q8_1_sycl_ncols( const void * vx, const void * vy, float * dst, const int ncols, const int nrows, const int stride_col_y_bytes, const int stride_col_dst, dpct::queue_ptr stream) { - static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S); - GGML_ASSERT(ncols % QK_K == 0); + static_assert(type == GGML_TYPE_IQ3_XXS || type == GGML_TYPE_IQ3_S || type == GGML_TYPE_IQ4_NL || + type == GGML_TYPE_IQ4_XS); + GGML_ASSERT(ncols % ggml_sycl_reordered::block_q_t::traits::qk == 0); constexpr size_t num_subgroups = WARP_SIZE; const int block_num_y = ceil_div(nrows, GGML_SYCL_MMV_Y * (int) num_subgroups); const sycl::range<3> block_nums(1, 1, block_num_y); @@ -1818,21 +1820,21 @@ static void reorder_mul_mat_vec_iq3_q8_1_sycl_ncols( } template -static void reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols( +static void reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( const void * vx, const void * vy, float * dst, const int ncols, const int nrows, const int ncols_dst, const int stride_col_y_bytes, const int stride_col_dst, dpct::queue_ptr stream) { switch (ncols_dst) { - case 1: reorder_mul_mat_vec_iq3_q8_1_sycl(vx, vy, dst, ncols, nrows, stream); break; - case 2: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 3: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 4: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 5: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 6: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 7: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - case 8: reorder_mul_mat_vec_iq3_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; - default: GGML_ABORT("unsupported ncols_dst=%d for reordered IQ3 multi-col MMVQ", ncols_dst); + case 1: reorder_mul_mat_vec_iq_q8_1_sycl(vx, vy, dst, ncols, nrows, stream); break; + case 2: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 3: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 4: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 5: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 6: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 7: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + case 8: reorder_mul_mat_vec_iq_q8_1_sycl_ncols(vx, vy, dst, ncols, nrows, stride_col_y_bytes, stride_col_dst, stream); break; + default: GGML_ABORT("unsupported ncols_dst=%d for reordered IQ multi-col MMVQ", ncols_dst); } } @@ -2518,13 +2520,13 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; const int stride_col_dst = dst->ne[0]; GGML_SYCL_DEBUG("Calling reordered IQ3_XXS multi-col MMVQ ncols=%d\n", (int) src1_ncols); - reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols( + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, src1_ncols, stride_col_y_bytes, stride_col_dst, stream); return; } else { GGML_SYCL_DEBUG("Calling reordered IQ3_XXS MMVQ\n"); - reorder_mul_mat_vec_iq3_q8_1_sycl( + reorder_mul_mat_vec_iq_q8_1_sycl( src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); } } else { @@ -2539,13 +2541,13 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; const int stride_col_dst = dst->ne[0]; GGML_SYCL_DEBUG("Calling reordered IQ3_S multi-col MMVQ ncols=%d\n", (int) src1_ncols); - reorder_mul_mat_vec_iq3_q8_1_sycl_switch_ncols( + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, src1_ncols, stride_col_y_bytes, stride_col_dst, stream); return; } else { GGML_SYCL_DEBUG("Calling reordered IQ3_S MMVQ\n"); - reorder_mul_mat_vec_iq3_q8_1_sycl( + reorder_mul_mat_vec_iq_q8_1_sycl( src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); } } else if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { @@ -2561,10 +2563,42 @@ void ggml_sycl_op_mul_mat_vec_q(ggml_backend_sycl_context & ctx, const ggml_tens } break; case GGML_TYPE_IQ4_NL: - mul_mat_vec_iq4_nl_q8_1_sycl(src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + if ((ggml_tensor_extra_gpu *) dst->src[0]->extra && + ((ggml_tensor_extra_gpu *) dst->src[0]->extra)->optimized_feature.reorder) { + if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { + const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; + const int stride_col_dst = dst->ne[0]; + GGML_SYCL_DEBUG("Calling reordered IQ4_NL multi-col MMVQ ncols=%d\n", (int) src1_ncols); + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( + src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, + src1_ncols, stride_col_y_bytes, stride_col_dst, stream); + return; + } else { + GGML_SYCL_DEBUG("Calling reordered IQ4_NL MMVQ\n"); + reorder_mul_mat_vec_iq_q8_1_sycl( + src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + } + } else { + mul_mat_vec_iq4_nl_q8_1_sycl(src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + } break; case GGML_TYPE_IQ4_XS: - if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { + if ((ggml_tensor_extra_gpu *) dst->src[0]->extra && + ((ggml_tensor_extra_gpu *) dst->src[0]->extra)->optimized_feature.reorder) { + if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { + const int stride_col_y_bytes = src1_padded_col_size * q8_1_ts / q8_1_bs; + const int stride_col_dst = dst->ne[0]; + GGML_SYCL_DEBUG("Calling reordered IQ4_XS multi-col MMVQ ncols=%d\n", (int) src1_ncols); + reorder_mul_mat_vec_iq_q8_1_sycl_switch_ncols( + src0_dd_i, src1_ddq_i, dst_dd_i, ne00, row_diff, + src1_ncols, stride_col_y_bytes, stride_col_dst, stream); + return; + } else { + GGML_SYCL_DEBUG("Calling reordered IQ4_XS MMVQ\n"); + reorder_mul_mat_vec_iq_q8_1_sycl( + src0_dd_i, src1_ddq_i_bs, dst_dd_i_bs, ne00, row_diff, stream); + } + } else if (i == 0 && src1_ncols > 1 && src1_ncols <= 8) { const int stride_col_y = src1_padded_col_size / QK8_1; const int stride_col_dst = dst->ne[0]; GGML_SYCL_DEBUG("Calling mul_mat_vec_iq4_xs_q8_1_sycl_switch_ncols ncols=%d\n", (int)src1_ncols); diff --git a/ggml/src/ggml-sycl/quants.hpp b/ggml/src/ggml-sycl/quants.hpp index 9fdcc22f21c6..79b5c8de5d1f 100644 --- a/ggml/src/ggml-sycl/quants.hpp +++ b/ggml/src/ggml-sycl/quants.hpp @@ -14,6 +14,7 @@ #ifndef GGML_SYCL_QUANTS_HPP #define GGML_SYCL_QUANTS_HPP +#include #include #include "ggml-common.h" @@ -225,6 +226,70 @@ template <> struct block_q_t { static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; } }; +template <> struct block_q_t { + struct traits { + static constexpr uint32_t qk = QK4_NL; + static constexpr uint32_t qi = QI4_NL; + static constexpr uint32_t qr = QR4_NL; + static constexpr uint32_t vdr_mmvq = 4; + }; + + // Reordered layout: [qs (QK4_NL/2 per block)][d] + static constexpr int record_size = offsetof(block_iq4_nl, qs); + + static constexpr std::pair get_block_offset(const int block_index, const int /* nblocks */) { + return { block_index * (QK4_NL / 2), 0 }; + } + + static constexpr std::pair get_d_offset(int nrows, int ncols, const int block_index) { + return { (ncols / QR4_NL * nrows) + block_index * sizeof(ggml_half), 0 }; + } + + static float group_scale(const uint8_t * record, const int /* group */) { + return *reinterpret_cast(record); + } + + static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; } +}; + +template <> struct block_q_t { + struct traits { + static constexpr uint32_t qk = QK_K; + static constexpr uint32_t qi = QI4_XS; + static constexpr uint32_t qr = QR4_XS; + static constexpr uint32_t vdr_mmvq = 4; + }; + + // Reordered layout: [qs (QK_K/2 per block)][{d, scales_h, scales_l} per block, as in block_iq4_xs] + static constexpr int record_size = offsetof(block_iq4_xs, qs); + + static constexpr std::pair get_block_offset(const int block_index, const int /* nblocks */) { + return { block_index * (QK_K / 2), 0 }; + } + + static constexpr std::pair get_d_offset(int nrows, int ncols, const int block_index) { + const int nblocks = nrows * (ncols / QK_K); + return { nblocks * (QK_K / 2) + block_index * (int) offsetof(block_iq4_xs, qs), 0 }; + } + + static float group_scale(const uint8_t * record, const int group) { + const uint16_t scales_h = *reinterpret_cast(record + offsetof(block_iq4_xs, scales_h)); + const uint8_t scales_l = record[offsetof(block_iq4_xs, scales_l) + group / 2]; + const int ls = ((scales_l >> (4 * (group % 2))) & 0xf) | (((scales_h >> (2 * group)) & 3) << 4); + return (float) *reinterpret_cast(record + offsetof(block_iq4_xs, d)) * (ls - 32); + } + + static constexpr int block_to_q8_1_ratio() { return traits::qk / QK8_1; } +}; + +// IQ4_NL blocks and IQ4_XS sub-blocks are 32-value groups of 16 qs bytes, so in both layouts the qs of +// group g start at 16 * g; tail is the first byte after all qs, where the per-block records start +template inline float iq4_group_scale(const uint8_t * tail, const int64_t g) { + using block_t = block_q_t; + constexpr int64_t groups = block_t::traits::qk / QK4_NL; + return block_t::group_scale(tail + g / groups * block_t::record_size, (int) (g % groups)); +} + template <> struct block_q_t { struct traits { static constexpr uint32_t qk = QK8_0; // 32 diff --git a/ggml/src/ggml-sycl/vecdotq.hpp b/ggml/src/ggml-sycl/vecdotq.hpp index f547b20e687f..f2f34667a892 100644 --- a/ggml/src/ggml-sycl/vecdotq.hpp +++ b/ggml/src/ggml-sycl/vecdotq.hpp @@ -388,6 +388,14 @@ template <> struct reorder_vec_dot_shared_weights { static constexpr bool value = true; }; +template <> struct reorder_vec_dot_shared_weights { + static constexpr bool value = true; +}; + +template <> struct reorder_vec_dot_shared_weights { + static constexpr bool value = true; +}; + template struct reorder_vec_dot_shared_activations { static constexpr bool value = false; }; @@ -1956,4 +1964,88 @@ vec_dot_iq4_xs_q8_1(const void *__restrict__ vbq, #endif } +// IQ4_NL blocks and IQ4_XS sub-blocks are both 32 values in 16 qs bytes: the low nibbles pair with +// q8_1 ints 0..3 and the high nibbles with ints 4..7. A lane decodes them once for all columns. +struct reorder_vec_dot_iq4_32 { + struct weights { + int v[8]; + float d; + }; + + static __dpct_inline__ weights decode(const uint8_t * qs, const float d) { + const sycl::int4 q4 = *reinterpret_cast(qs); + const uint8_t * values = (const uint8_t *) kvalues_iq4nl; + + weights w; + get_int_from_table_16((uint32_t) q4.x(), values, w.v[0], w.v[4]); + get_int_from_table_16((uint32_t) q4.y(), values, w.v[1], w.v[5]); + get_int_from_table_16((uint32_t) q4.z(), values, w.v[2], w.v[6]); + get_int_from_table_16((uint32_t) q4.w(), values, w.v[3], w.v[7]); + w.d = d; + return w; + } + + static __dpct_inline__ float dot32(const weights & w, const int8_t * q8, const sycl::half2 ds8) { + const int * u = (const int *) q8; + int sumi1 = 0; + int sumi2 = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + sumi1 = dpct::dp4a(w.v[j + 0], u[j + 0], sumi1); + sumi2 = dpct::dp4a(w.v[j + 4], u[j + 4], sumi2); + } + return w.d * (float) ds8[0] * (sumi1 + sumi2); + } +}; + +template <> struct reorder_vec_dot_q_sycl : reorder_vec_dot_iq4_32 { + static constexpr ggml_type gtype = GGML_TYPE_IQ4_NL; + + // a lane holds a whole block, so iqs is always 0 + __dpct_inline__ static weights load(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int & /* iqs */) { + const uint8_t * base = static_cast(vbq); + return decode(base + ibx_offset.first, *reinterpret_cast(base + d_offset.first)); + } + + __dpct_inline__ static float dot(const weights & w, const int8_t * q8_1_quant_ptr, const sycl::half2 * q8_1_ds, + const int & /* iqs */) { + return dot32(w, q8_1_quant_ptr, *q8_1_ds); + } + + __dpct_inline__ float operator()(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int8_t * q8_1_quant_ptr, + const sycl::half2 * q8_1_ds, const int & iqs) { + return dot(load(vbq, ibx_offset, d_offset, iqs), q8_1_quant_ptr, q8_1_ds, iqs); + } +}; + +template <> struct reorder_vec_dot_q_sycl : reorder_vec_dot_iq4_32 { + static constexpr ggml_type gtype = GGML_TYPE_IQ4_XS; + + // iqs is the first qs int of the lane's sub-block + __dpct_inline__ static weights load(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int & iqs) { + const uint8_t * base = static_cast(vbq); + const uint8_t * meta = base + d_offset.first; + const int ib32 = iqs / 4; + const uint16_t scales_h = *reinterpret_cast(meta + offsetof(block_iq4_xs, scales_h)); + const uint8_t scales_l = meta[offsetof(block_iq4_xs, scales_l) + ib32 / 2]; + const int ls = ((scales_l >> (4 * (ib32 % 2))) & 0xf) | (((scales_h >> (2 * ib32)) & 3) << 4); + const float d = (float) *reinterpret_cast(meta + offsetof(block_iq4_xs, d)); + return decode(base + ibx_offset.first + sizeof(int) * iqs, d * (ls - 32)); + } + + __dpct_inline__ static float dot(const weights & w, const int8_t * q8_1_quant_ptr, const sycl::half2 * q8_1_ds, + const int & iqs) { + return dot32(w, q8_1_quant_ptr + (iqs / 4) * QK8_1, q8_1_ds[iqs / 4]); + } + + __dpct_inline__ float operator()(const void * __restrict__ vbq, const std::pair ibx_offset, + const std::pair d_offset, const int8_t * q8_1_quant_ptr, + const sycl::half2 * q8_1_ds, const int & iqs) { + return dot(load(vbq, ibx_offset, d_offset, iqs), q8_1_quant_ptr, q8_1_ds, iqs); + } +}; + #endif // GGML_SYCL_VECDOTQ_HPP diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 711674958542..a0d3349e65de 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -10948,10 +10948,10 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_get_rows(GGML_TYPE_F32, 1, 8, 2, 1, 1, false)); for (ggml_type type : {GGML_TYPE_Q4_0, GGML_TYPE_Q8_0, GGML_TYPE_Q2_K, GGML_TYPE_Q3_K, GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, - GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S}) { + GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) { test_cases.emplace_back(new test_get_rows_after_mul_mat(type)); } - for (ggml_type type : {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S}) { + for (ggml_type type : {GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) { test_cases.emplace_back(new test_mul_mat_reorder_then_big_batch(type)); } for (int n : {1, 3, 257}) { @@ -10959,6 +10959,10 @@ static std::vector> make_test_cases_eval() { } // many rows of a wide table, as a per-layer embedding lookup does test_cases.emplace_back(new test_get_rows(GGML_TYPE_F8_E4M3, 160, 100000, 32768, 1, 1, false)); + // past the fused dequant GEMM's column limit the reordered weight goes through the conversion kernels + for (ggml_type type : {GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS}) { + test_cases.emplace_back(new test_mul_mat_reorder_then_big_batch(type, 128)); + } for (ggml_type type : all_types) { for (int b : {1, 7}) { for (bool v : {false, true}) { @@ -12127,8 +12131,8 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 16, 8, 16*256, { 1, 1}, {1, 1})); } - // Multi-column MMVQ coverage for the Q4_K weight-reuse path and a Q5_K control. - for (ggml_type type_a : { GGML_TYPE_Q4_K, GGML_TYPE_Q5_K }) { + // Multi-column MMVQ coverage for the Q4_K and IQ4 weight-reuse paths and a Q5_K control. + for (ggml_type type_a : { GGML_TYPE_Q4_K, GGML_TYPE_Q5_K, GGML_TYPE_IQ4_NL, GGML_TYPE_IQ4_XS }) { for (int n = 1; n <= 8; ++n) { test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 4096, n, 1024, { 1, 1 }, { 1, 1 })); test_cases.emplace_back(new test_mul_mat(type_a, GGML_TYPE_F32, 1023, n, 4096, { 1, 1 }, { 1, 1 })); From c622f623fca9f0f085eb82f38874d1ab4a1791cd Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Sat, 21 Nov 2026 14:25:19 +0100 Subject: [PATCH 024/401] mtmd: support kyutai/hibiki realtime full-duplex (#32491) * mtmd: support hibiki realtime duplex * fix and clean up * fix long session quality * fix ci * tests : add the moshi fusion baseline for Metal The Metal fusion check found 5 RMS_NORM+MUL fusions in the new moshi arch and no baseline for them. --------- Co-authored-by: Pascal --- conversion/__init__.py | 2 + conversion/moshi.py | 378 +++++++++++++++++++++++++ conversion/pockettts.py | 144 +++++----- docs/multimodal/tts.md | 17 ++ gguf-py/gguf/constants.py | 18 ++ src/llama-arch.cpp | 1 + src/llama-arch.h | 1 + src/llama-model.cpp | 24 ++ src/models/models.h | 12 + src/models/moshi.cpp | 132 +++++++++ tests/fusion/MTL.csv | 1 + tools/mtmd/CMakeLists.txt | 1 + tools/mtmd/models/models.h | 59 +++- tools/mtmd/models/moshi.cpp | 265 +++++++++++++++++ tools/mtmd/models/pockettts-gen.cpp | 96 +------ tools/mtmd/models/pockettts-seanet.cpp | 122 +++++++- tools/mtmd/models/qwen3tts-gen.cpp | 35 ++- tools/mtmd/mtmd-cli.cpp | 4 + tools/mtmd/mtmd-graph.cpp | 18 ++ tools/mtmd/mtmd-helper-gen.cpp | 137 +++++++++ tools/mtmd/mtmd-helper.cpp | 1 + tools/mtmd/mtmd-helper.h | 1 + tools/mtmd/mtmd-impl.h | 4 + tools/mtmd/mtmd-model.cpp | 109 +++++-- tools/mtmd/mtmd-subcontext.cpp | 63 ++++- tools/mtmd/mtmd.cpp | 161 ++++++++++- tools/mtmd/mtmd.h | 2 + tools/server/README.md | 6 + tools/server/server-context.cpp | 2 +- tools/server/server-realtime.cpp | 245 ++++++++++++++-- tools/server/server-realtime.h | 15 +- 31 files changed, 1845 insertions(+), 231 deletions(-) create mode 100644 conversion/moshi.py create mode 100644 src/models/moshi.cpp create mode 100644 tools/mtmd/models/moshi.cpp diff --git a/conversion/__init__.py b/conversion/__init__.py index 8869b7252982..146c309e65a7 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -286,6 +286,7 @@ "Qwen3NextForCausalLM": "qwen", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "MoshiModel": "moshi", "KokoroModel": "kokoro", "TinyVocaModel": "tiny_voca", "Zonos3Model": "zonos3", @@ -432,6 +433,7 @@ "Qwen3ASRForConditionalGeneration": "qwen3vl", "Qwen3OmniMoeForConditionalGeneration": "qwen3vl", "PocketTTSModel": "pockettts", + "MoshiModel": "moshi", "KokoroModel": "kokoro", "TinyVocaModel": "tiny_voca", "SopranoModel": "soprano", diff --git a/conversion/moshi.py b/conversion/moshi.py new file mode 100644 index 000000000000..028319385a1c --- /dev/null +++ b/conversion/moshi.py @@ -0,0 +1,378 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Callable, Iterable, TYPE_CHECKING + +import torch + +if TYPE_CHECKING: + from torch import Tensor + +from .base import ModelBase, MmprojModel, SentencePieceTokenTypes, TextModel, gguf, logger +from .pockettts import mimi_seanet_tensors, mimi_tfm_tensors + +# Moshi family (Kyutai): a backbone over parallel streams (text + generated audio codes + input audio codes), +# one position per 80 ms frame. Only Hibiki (simultaneous speech translation) is supported for now. +# The checkpoint is not in the HF layout: a moshi-style config.json and two safetensors (LM + mimi). +# +# pipeline stage mapping: +# transformer + text_emb/text_linear --> normal libllama text model (arch moshi) +# mimi encoder + RVQ + emb[dep_q:] --> mtmd audio stream (projector moshi), rows of the input audio +# depformer + emb[:dep_q] --> MTMD_GEN_PROCESS_TYPE_GEN_CODE, codes of a frame + their backbone embedding +# RVQ decode + mimi decoder --> MTMD_GEN_PROCESS_TYPE_GEN_WAV +# +# Tricks: +# - the initial text token (text_card) is appended to the vocab as <|text_start|>, the head has no logit for it; +# it only opens the stream, the embeddings of the initial codes of the generated audio are folded into it +# - the condition of Hibiki ("very_good" description, added to every row) is folded into the text embeddings, +# every row has exactly one text embedding +# - Hibiki ignores an early EOS: the reference gives it the embedding of PAD, done here too +# - low-rank depformer embeddings are folded into full tables + +_MIMI_PREFIX = "mimi." +_COND_VALUE = "very_good" + + +def _read_config(dir_model: Path) -> dict[str, Any] | None: + path = dir_model / "config.json" + if not path.is_file(): + return None + with open(path, "r", encoding="utf-8") as f: + config = json.load(f) + return config if isinstance(config, dict) and "moshi_name" in config else None + + +def _tensor_shape(path: Path, name: str) -> tuple[int, ...]: + with gguf.utility.SafetensorsLocal(path) as part: + return tuple(part[name].shape) + + +@ModelBase.register_hparams_loader(lambda dir_model: _read_config(dir_model) is not None) +def _load_hparams(dir_model: Path) -> dict[str, Any]: + config = _read_config(dir_model) + assert config is not None + model_type = config.get("model_type", "moshi") + if model_type != "hibiki": + raise NotImplementedError(f"moshi checkpoint of type {model_type!r} is not supported yet") + logger.info(f"gguf: detected a moshi checkpoint ({model_type})") + + # mtmd has the layout of Hibiki: the acoustic codes lag by 2 frames, the depformer has no positional embedding, + # its steps past the last weight set reuse it, and the initial code is the extra entry after the mimi codebook + n_q = config["dep_q"] + schedule = config.get("depformer_weights_per_step_schedule") or list(range(n_q)) + # text, then the generated and the input codes + if config["delays"] != [0] + ([0] + [2] * (n_q - 1)) * 2: + raise NotImplementedError(f"unsupported delays {config['delays']}") + if schedule != [min(i, max(schedule)) for i in range(n_q)] or config.get("depformer_pos_emb", "none") != "none": + raise NotImplementedError("unsupported depformer layout") + if config["card"] != 2048 or config["n_q"] != 2 * n_q: + raise NotImplementedError("unsupported audio codebooks") + + lm_path = dir_model / config["moshi_name"] + # the gating hidden size is derived from dim_feedforward, read it back from the tensors + n_ff = _tensor_shape(lm_path, "transformer.layers.0.gating.linear_out.weight")[1] + n_ff_dep = _tensor_shape(lm_path, "depformer.layers.0.gating.0.linear_out.weight")[1] + return { + "architectures": ["MoshiModel"], + "model_type": "moshi", + "moshi_config": config, + "num_hidden_layers": config["num_layers"], + "hidden_size": config["dim"], + "intermediate_size": n_ff, + "num_attention_heads": config["num_heads"], + "num_key_value_heads": config["num_heads"], + "max_position_embeddings": config["context"], + "sliding_window": config["context"], + "rope_theta": config["max_period"], + "rms_norm_eps": 1e-8, # rms_norm_f32 + "vocab_size": config["text_card"] + 1, + "audio_config": { + # mimi encoder transformer, constant across the family + "num_hidden_layers": 8, + "hidden_size": 512, + "intermediate_size": 2048, + "num_attention_heads": 8, + }, + "depformer_config": { + "num_hidden_layers": config["depformer_num_layers"], + "hidden_size": config["depformer_dim"], + "intermediate_size": n_ff_dep, + "num_attention_heads": config["depformer_num_heads"], + }, + } + + +# the LM and mimi weights are in two files named by the config, mimi tensors get the "mimi." prefix +def _moshi_config(model: ModelBase) -> dict[str, Any]: + config = model.hparams.get("moshi_config") + if config is None and isinstance(model, MmprojModel): + config = model.global_config["moshi_config"] # the mmproj moves the hparams aside + assert config is not None + return config + + +def _index_moshi_tensors(model: ModelBase) -> dict[str, Callable[[], Tensor]]: + config = _moshi_config(model) + tensors = model.index_local_tensors(Path(config["moshi_name"]).stem) + for name, gen in model.index_local_tensors(Path(config["mimi_name"]).stem).items(): + tensors[_MIMI_PREFIX + name] = gen + return tensors + + +def _low_rank_embd(model: ModelBase, prefix: str) -> Tensor: + embd = model.model_tensors[prefix + ".weight"]().float() + proj = model.model_tensors.get(prefix + ".low_rank.weight") + return embd @ proj().float().T if proj is not None else embd + + +def _condition(model: ModelBase, value: str) -> Tensor: + # LUT conditioner: output_proj(embed[index of value]) + lut = _moshi_config(model)["conditioners"]["description"]["lut"] + prefix = "condition_provider.conditioners.description." + embed = model.model_tensors[prefix + "embed.weight"]().float() + proj = model.model_tensors[prefix + "output_proj.weight"]().float() + return embed[lut["possible_values"].index(value)] @ proj.T + + +@ModelBase.register("MoshiModel") +@ModelBase.example("kyutai/hibiki-1b-pytorch-bf16", "kyutai/hibiki-2b-pytorch-bf16") +class MoshiModel(TextModel): + model_arch = gguf.MODEL_ARCH.MOSHI + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + assert remote_hf_model_id is None + return _index_moshi_tensors(self) + + def set_vocab(self): + from sentencepiece import SentencePieceProcessor + + config = _moshi_config(self) + sp = SentencePieceProcessor() + sp.LoadFromFile(str(self.dir_model / config["tokenizer_name"])) + assert sp.vocab_size() == config["text_card"] + + tokens: list[bytes] = [] + scores: list[float] = [] + toktypes: list[int] = [] + for i in range(sp.vocab_size()): + toktype = SentencePieceTokenTypes.NORMAL + if sp.IsControl(i) or sp.IsUnknown(i): + # (0) is the end-of-padding marker of the text stream, it has no text + toktype = SentencePieceTokenTypes.CONTROL + elif sp.IsUnused(i): + toktype = SentencePieceTokenTypes.UNUSED + elif sp.IsByte(i): + toktype = SentencePieceTokenTypes.BYTE + tokens.append(sp.IdToPiece(i).encode("utf-8")) + scores.append(sp.GetScore(i)) + toktypes.append(toktype) + + # the initial token of the text stream + tokens.append(b"<|text_start|>") + scores.append(-1000.0) + toktypes.append(SentencePieceTokenTypes.CONTROL) + + self.gguf_writer.add_tokenizer_model("llama") + self.gguf_writer.add_tokenizer_pre("default") + self.gguf_writer.add_token_list(tokens) + self.gguf_writer.add_token_scores(scores) + self.gguf_writer.add_token_types(toktypes) + self.gguf_writer.add_unk_token_id(sp.unk_id()) + self.gguf_writer.add_bos_token_id(sp.bos_id()) + self.gguf_writer.add_eos_token_id(sp.eos_id()) + self.gguf_writer.add_pad_token_id(sp.pad_id()) + self.gguf_writer.add_add_bos_token(False) + self.gguf_writer.add_add_eos_token(False) + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_sliding_window(self.hparams["sliding_window"]) + + # sampling of the text tokens, the audio codes are sampled by mtmd + gen = _moshi_config(self).get("lm_gen_config", {}) + self.gguf_writer.add_sampling_temp(gen.get("temp_text", 0.7)) + self.gguf_writer.add_sampling_top_k(gen.get("top_k_text", 25)) + self.gguf_writer.add_sampling_top_p(1.0) + self.gguf_writer.add_sampling_min_p(0.0) + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + + if name == "text_emb.weight": + config = _moshi_config(self) + embd = data_torch.float().clone() + embd[2] = embd[3] # EOS -> PAD, see get_moshi() of the reference + embd += _condition(self, _COND_VALUE) + assert embd.shape[0] == config["text_card"] + 1 + # <|text_start|> only opens the stream, with the initial codes of the generated audio + for k in range(config["dep_q"]): + embd[-1] += self.model_tensors[f"emb.{k}.weight"]()[config["card"]].float() + yield (self.format_tensor_name(T.TOKEN_EMBD), embd) + return + if name == "text_linear.weight": + yield (self.format_tensor_name(T.OUTPUT), data_torch) + return + if name == "out_norm.alpha": + yield (self.format_tensor_name(T.OUTPUT_NORM), data_torch.reshape(-1)) + return + + if not name.startswith("transformer.layers."): + return # mimi, depformer and the audio embeddings go to the mmproj + assert bid is not None + key = name.split(f"layers.{bid}.", 1)[1] + + if key == "self_attn.in_proj_weight": + q, k, v = data_torch.chunk(3, dim=0) + yield (self.format_tensor_name(T.ATTN_Q, bid), q) + yield (self.format_tensor_name(T.ATTN_K, bid), k) + yield (self.format_tensor_name(T.ATTN_V, bid), v) + elif key == "self_attn.out_proj.weight": + yield (self.format_tensor_name(T.ATTN_OUT, bid), data_torch) + elif key == "norm1.alpha": + yield (self.format_tensor_name(T.ATTN_NORM, bid), data_torch.reshape(-1)) + elif key == "norm2.alpha": + yield (self.format_tensor_name(T.FFN_NORM, bid), data_torch.reshape(-1)) + elif key == "gating.linear_in.weight": + # silu(first half) * second half + gate, up = data_torch.chunk(2, dim=0) + yield (self.format_tensor_name(T.FFN_GATE, bid), gate) + yield (self.format_tensor_name(T.FFN_UP, bid), up) + elif key == "gating.linear_out.weight": + yield (self.format_tensor_name(T.FFN_DOWN, bid), data_torch) + else: + raise ValueError(f"unexpected tensor {name}") + + +@ModelBase.register("MoshiModel") +@ModelBase.example("kyutai/hibiki-1b-pytorch-bf16", "kyutai/hibiki-2b-pytorch-bf16") +class MoshiMmprojModel(MmprojModel): + has_audio_encoder = True + has_vision_encoder = False + + def index_tensors(self, remote_hf_model_id: str | None = None) -> dict[str, Callable[[], Tensor]]: + assert remote_hf_model_id is None + return _index_moshi_tensors(self) + + def _n_codebooks(self) -> int: + return _moshi_config(self)["dep_q"] + + def set_gguf_parameters(self): + self.gguf_writer.add_file_type(self.ftype) + assert self.hparams_audio is not None + dep = self.global_config["depformer_config"] + + # input audio: mimi encoder + RVQ + embeddings of the input codes + self.gguf_writer.add_clip_has_audio_encoder(True) + self.gguf_writer.add_clip_audio_projector_type(gguf.VisionProjectorType.MOSHI) + self.gguf_writer.add_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_audio_block_count(self.hparams_audio["num_hidden_layers"]) + self.gguf_writer.add_audio_embedding_length(self.hparams_audio["hidden_size"]) + self.gguf_writer.add_audio_feed_forward_length(self.hparams_audio["intermediate_size"]) + self.gguf_writer.add_audio_head_count(self.hparams_audio["num_attention_heads"]) + self.gguf_writer.add_audio_attention_layernorm_eps(1e-5) + # mimi convolves the waveform directly, it is passed around as a 1-row "mel" + self.gguf_writer.add_audio_num_mel_bins(1) + + # generation: depformer + mimi decoder, the mimi hparams are constant and held by mtmd + self.gguf_writer.add_clip_has_gen_audio_encoder(True) + self.gguf_writer.add_clip_gen_audio_projector_type(gguf.VisionProjectorType.MOSHI_GEN) + self.gguf_writer.add_gen_audio_projection_dim(self.n_embd_text) + self.gguf_writer.add_gen_audio_embedding_length(dep["hidden_size"]) + self.gguf_writer.add_gen_audio_feed_forward_length(dep["intermediate_size"]) + self.gguf_writer.add_gen_audio_block_count(dep["num_hidden_layers"]) + self.gguf_writer.add_gen_audio_head_count(dep["num_attention_heads"]) + self.gguf_writer.add_gen_audio_attention_layernorm_eps(1e-8) + self.gguf_writer.add_gen_audio_model_variant(_moshi_config(self)["model_type"]) + + def tensor_force_quant(self, name, new_name, bid, n_dims): + del name, bid, n_dims + # conv1d/conv1d_dw kernels must be F16, ggml_conv_1d(_dw) has no BF16 path + if ".seanet." in new_name or new_name in ("a.downsample.conv.weight", "a.gen.wav.upsample.weight"): + return gguf.GGMLQuantizationType.F16 + # nearest-code search and RVQ decode stay exact + if ".codebook" in new_name or new_name.startswith("a.codec.vq."): + return gguf.GGMLQuantizationType.F32 + return False + + def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: + del bid + T = gguf.MODEL_TENSOR + if name.startswith(("a.", "mm.a.")): + yield (name, data_torch) # already named by generate_extra_tensors() + return + if not name.startswith(_MIMI_PREFIX): + return # the LM tensors are stacked in generate_extra_tensors() + if name == "mimi.downsample.conv.conv.conv.weight": + yield (self.format_tensor_name(T.A_ENC_DOWNSAMPLE_CONV), data_torch) + elif name == "mimi.upsample.convtr.convtr.convtr.weight": + yield (self.format_tensor_name(T.A_GEN_WAV_UPSAMPLE), data_torch) + elif "_transformer.transformer.layers." in name: + # pocket-tts names it in_proj.weight + yield from mimi_tfm_tensors(self, name.replace(".in_proj_weight", ".in_proj.weight"), data_torch) + elif name.startswith(("mimi.encoder.model.", "mimi.decoder.model.")): + yield from mimi_seanet_tensors(self, name, data_torch, 4) + + def generate_extra_tensors(self) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + config = _moshi_config(self) + n_q = self._n_codebooks() + + def get(name: str) -> Tensor: + return self.model_tensors[name]() + + def stack(names: Iterable[str]) -> Tensor: + return torch.stack([get(n) for n in names], dim=0) + + # mimi RVQ: one semantic codebook, then n_q - 1 acoustic ones + def codebooks(prefix: str, n: int) -> Tensor: + books = [] + for i in range(n): + embedding_sum = get(f"{prefix}.vq.layers.{i}._codebook.embedding_sum").float() + cluster_usage = get(f"{prefix}.vq.layers.{i}._codebook.cluster_usage").float() + books.append(embedding_sum / cluster_usage.clamp_min(1e-5).unsqueeze(-1)) + return torch.stack(books, dim=0) if n > 1 else books[0] + + q = "mimi.quantizer." + cb_first = codebooks(q + "rvq_first", 1) + cb_rest = codebooks(q + "rvq_rest", n_q - 1) + yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_IN), get(q + "rvq_first.input_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_CODEC_VQ_FIRST_CB), cb_first) + yield (self.format_tensor_name(T.A_CODEC_VQ_REST_IN), get(q + "rvq_rest.input_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_CODEC_VQ_REST_CB), cb_rest) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_OUT), get(q + "rvq_first.output_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_FIRST_CB), cb_first) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_REST_OUT), get(q + "rvq_rest.output_proj.weight").squeeze(-1)) + yield (self.format_tensor_name(T.A_GEN_WAV_QUANT_REST_CB), cb_rest) + + # backbone embeddings of the audio codes: the generated stream first, then the input stream + assert config["n_q"] == 2 * n_q + yield (self.format_tensor_name(T.A_GEN_CODE_OUT_EMBD), stack(f"emb.{k}.weight" for k in range(n_q))) + yield (self.format_tensor_name(T.A_MM_CODE_EMBD), stack(f"emb.{k}.weight" for k in range(n_q, 2 * n_q))) + + # depformer: per-step weights are stacked on the last ggml dim, steps past the last weight set reuse it + dep = self.global_config["depformer_config"] + n_dim = dep["hidden_size"] + n_in = sum(1 for name in self.model_tensors if name.startswith("depformer_in.")) + yield (self.format_tensor_name(T.A_GEN_CODE_PROJ_IN), stack(f"depformer_in.{i}.weight" for i in range(n_in))) + yield (self.format_tensor_name(T.A_GEN_CODE_TOK_EMBD), _low_rank_embd(self, "depformer_text_emb")) + yield (self.format_tensor_name(T.A_GEN_CODE_EMBD), + torch.stack([_low_rank_embd(self, f"depformer_emb.{i}") for i in range(n_q - 1)], dim=0)) + yield (self.format_tensor_name(T.A_GEN_CODE_HEAD), stack(f"linears.{k}.weight" for k in range(n_q))) + + for il in range(dep["num_hidden_layers"]): + p = f"depformer.layers.{il}." + n_w = sum(1 for name in self.model_tensors if name.startswith(p + "gating.") and name.endswith(".linear_in.weight")) + assert n_w == n_in, "depformer_in and the per-step weights use the same schedule" + qkv = get(p + "self_attn.in_proj_weight").reshape(n_w, 3, n_dim, n_dim) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_Q, il), qkv[:, 0]) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_K, il), qkv[:, 1]) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_V, il), qkv[:, 2]) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_OUT, il), get(p + "self_attn.out_proj.weight").reshape(n_w, n_dim, n_dim)) + gate_up = stack(f"{p}gating.{i}.linear_in.weight" for i in range(n_w)) + gate, up = gate_up.chunk(2, dim=1) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_GATE, il), gate) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_UP, il), up) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_DOWN, il), stack(f"{p}gating.{i}.linear_out.weight" for i in range(n_w))) + yield (self.format_tensor_name(T.A_GEN_CODE_ATTN_NORM, il), get(p + "norm1.alpha").reshape(-1)) + yield (self.format_tensor_name(T.A_GEN_CODE_FFN_NORM, il), get(p + "norm2.alpha").reshape(-1)) diff --git a/conversion/pockettts.py b/conversion/pockettts.py index b0cddc685ca0..4a3d980cd34e 100644 --- a/conversion/pockettts.py +++ b/conversion/pockettts.py @@ -271,26 +271,84 @@ def _embd_table(self, embed: Tensor) -> Tensor: return torch.cat(rows, dim=0) +# mimi tensors (shared with moshi): the transformers of the encoder and the decoder, and the SEANet stacks +MIMI_TFM_MAP = { + "norm1": (gguf.MODEL_TENSOR.A_ENC_INPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_NORM), + "norm2": (gguf.MODEL_TENSOR.A_ENC_OUTPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_NORM), + "self_attn.out_proj": (gguf.MODEL_TENSOR.A_ENC_OUTPUT, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_OUT), + "linear1": (gguf.MODEL_TENSOR.A_ENC_FFN_UP, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_UP), + "linear2": (gguf.MODEL_TENSOR.A_ENC_FFN_DOWN, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_DOWN), + "layer_scale_1.scale": (gguf.MODEL_TENSOR.A_ENC_ATTN_SCALE, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_SCALE), + "layer_scale_2.scale": (gguf.MODEL_TENSOR.A_ENC_FFN_SCALE_LS, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_SCALE), +} +MIMI_TFM_QKV = ( + (gguf.MODEL_TENSOR.A_ENC_ATTN_Q, gguf.MODEL_TENSOR.A_ENC_ATTN_K, gguf.MODEL_TENSOR.A_ENC_ATTN_V), + (gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_Q, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_K, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_V), +) + + +def mimi_tfm_tensors(model: MmprojModel, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]: + is_decoder = name.startswith("mimi.decoder_transformer.") + bid = int(name.split("_transformer.transformer.layers.", 1)[1].split(".")[0]) + key_with_suffix = name.split(f".layers.{bid}.", 1)[1] + + if key_with_suffix == "self_attn.in_proj.weight": + q, k, v = data_torch.chunk(3, dim=0) + names = MIMI_TFM_QKV[1 if is_decoder else 0] + for tensor, part in zip(names, (q, k, v)): + yield (model.format_tensor_name(tensor, bid), part) + return + + key, suffix = key_with_suffix.rsplit(".", 1) + entry = MIMI_TFM_MAP.get(key) or MIMI_TFM_MAP.get(key_with_suffix) + if entry is None: + return + tensor = entry[1 if is_decoder else 0] + suffix = ".weight" if key_with_suffix.endswith(".scale") else "." + suffix + yield (model.format_tensor_name(tensor, bid, suffix=suffix), data_torch) + + +def mimi_seanet_tensors(model: MmprojModel, name: str, data_torch: Tensor, n_stages: int) -> Iterable[tuple[str, Tensor]]: + T = gguf.MODEL_TENSOR + is_decoder = name.startswith("mimi.decoder.") + idx = int(name.split(".model.", 1)[1].split(".")[0]) + suffix = "." + name.rsplit(".", 1)[1] + + conv_in, conv_out, res1, res2, scale = ( + (T.A_GEN_WAV_SEANET_CONV_IN, T.A_GEN_WAV_SEANET_CONV_OUT, T.A_GEN_WAV_SEANET_RES_CONV1, + T.A_GEN_WAV_SEANET_RES_CONV2, T.A_GEN_WAV_SEANET_SCALE_CONV) + if is_decoder else + (T.A_ENC_SEANET_CONV_IN, T.A_ENC_SEANET_CONV_OUT, T.A_ENC_SEANET_RES_CONV1, + T.A_ENC_SEANET_RES_CONV2, T.A_ENC_SEANET_SCALE_CONV) + ) + + if idx == 0: + yield (model.format_tensor_name(conv_in, suffix=suffix), data_torch) + return + if idx == 3 * n_stages + 2: + yield (model.format_tensor_name(conv_out, suffix=suffix), data_torch) + return + + for stage in range(n_stages): + res_idx = _DEC_RES_IDX(stage) if is_decoder else _ENC_RES_IDX(stage) + scale_idx = _DEC_SCALE_IDX(stage) if is_decoder else _ENC_SCALE_IDX(stage) + if idx == scale_idx: + yield (model.format_tensor_name(scale, stage, suffix=suffix), data_torch) + return + if idx == res_idx: + # block.1 is the dilated conv, block.3 the pointwise one (0 and 2 are ELU) + inner = int(name.split(".block.", 1)[1].split(".")[0]) + tensor = res1 if inner == 1 else res2 + yield (model.format_tensor_name(tensor, stage, suffix=suffix), data_torch) + return + + @ModelBase.register("PocketTTSModel") # [TAG_HF_EXAMPLE_MISSING] model is gated, and the checkpoint requires cd to subdir, not supported here class PocketTTSMmprojModel(MmprojModel): has_audio_encoder = True has_vision_encoder = False - _MIMI_TFM_MAP = { - "norm1": (gguf.MODEL_TENSOR.A_ENC_INPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_NORM), - "norm2": (gguf.MODEL_TENSOR.A_ENC_OUTPUT_NORM, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_NORM), - "self_attn.out_proj": (gguf.MODEL_TENSOR.A_ENC_OUTPUT, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_OUT), - "linear1": (gguf.MODEL_TENSOR.A_ENC_FFN_UP, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_UP), - "linear2": (gguf.MODEL_TENSOR.A_ENC_FFN_DOWN, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_DOWN), - "layer_scale_1.scale": (gguf.MODEL_TENSOR.A_ENC_ATTN_SCALE, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_SCALE), - "layer_scale_2.scale": (gguf.MODEL_TENSOR.A_ENC_FFN_SCALE_LS, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_FFN_SCALE), - } - _MIMI_TFM_QKV = ( - (gguf.MODEL_TENSOR.A_ENC_ATTN_Q, gguf.MODEL_TENSOR.A_ENC_ATTN_K, gguf.MODEL_TENSOR.A_ENC_ATTN_V), - (gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_Q, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_K, gguf.MODEL_TENSOR.A_GEN_WAV_TFM_ATTN_V), - ) - def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.has_audio_encoder = _has_voice_encoder(self.dir_model) @@ -419,11 +477,11 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter return if "_transformer.transformer.layers." in name: - yield from self._mimi_tfm_tensor(name, data_torch) + yield from mimi_tfm_tensors(self, name, data_torch) return if name.startswith("mimi.encoder.model.") or name.startswith("mimi.decoder.model."): - yield from self._seanet_tensor(name, data_torch) + yield from mimi_seanet_tensors(self, name, data_torch, _N_SEANET_STAGES) return return @@ -471,57 +529,3 @@ def _flow_net_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, if tensor is not None: yield (self.format_tensor_name(tensor, bid, suffix=suffix), data_torch) return - - def _mimi_tfm_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]: - is_decoder = name.startswith("mimi.decoder_transformer.") - bid = int(name.split("_transformer.transformer.layers.", 1)[1].split(".")[0]) - key_with_suffix = name.split(f".layers.{bid}.", 1)[1] - - if key_with_suffix == "self_attn.in_proj.weight": - q, k, v = data_torch.chunk(3, dim=0) - names = self._MIMI_TFM_QKV[1 if is_decoder else 0] - for tensor, part in zip(names, (q, k, v)): - yield (self.format_tensor_name(tensor, bid), part) - return - - key, suffix = key_with_suffix.rsplit(".", 1) - entry = self._MIMI_TFM_MAP.get(key) or self._MIMI_TFM_MAP.get(key_with_suffix) - if entry is None: - return - tensor = entry[1 if is_decoder else 0] - suffix = ".weight" if key_with_suffix.endswith(".scale") else "." + suffix - yield (self.format_tensor_name(tensor, bid, suffix=suffix), data_torch) - - def _seanet_tensor(self, name: str, data_torch: Tensor) -> Iterable[tuple[str, Tensor]]: - T = gguf.MODEL_TENSOR - is_decoder = name.startswith("mimi.decoder.") - idx = int(name.split(".model.", 1)[1].split(".")[0]) - suffix = "." + name.rsplit(".", 1)[1] - - conv_in, conv_out, res1, res2, scale = ( - (T.A_GEN_WAV_SEANET_CONV_IN, T.A_GEN_WAV_SEANET_CONV_OUT, T.A_GEN_WAV_SEANET_RES_CONV1, - T.A_GEN_WAV_SEANET_RES_CONV2, T.A_GEN_WAV_SEANET_SCALE_CONV) - if is_decoder else - (T.A_ENC_SEANET_CONV_IN, T.A_ENC_SEANET_CONV_OUT, T.A_ENC_SEANET_RES_CONV1, - T.A_ENC_SEANET_RES_CONV2, T.A_ENC_SEANET_SCALE_CONV) - ) - - if idx == 0: - yield (self.format_tensor_name(conv_in, suffix=suffix), data_torch) - return - if idx == 3 * _N_SEANET_STAGES + 2: - yield (self.format_tensor_name(conv_out, suffix=suffix), data_torch) - return - - for stage in range(_N_SEANET_STAGES): - res_idx = _DEC_RES_IDX(stage) if is_decoder else _ENC_RES_IDX(stage) - scale_idx = _DEC_SCALE_IDX(stage) if is_decoder else _ENC_SCALE_IDX(stage) - if idx == scale_idx: - yield (self.format_tensor_name(scale, stage, suffix=suffix), data_torch) - return - if idx == res_idx: - # block.1 is the dilated conv, block.3 the pointwise one (0 and 2 are ELU) - inner = int(name.split(".block.", 1)[1].split(".")[0]) - tensor = res1 if inner == 1 else res2 - yield (self.format_tensor_name(tensor, stage, suffix=suffix), data_torch) - return diff --git a/docs/multimodal/tts.md b/docs/multimodal/tts.md index e009566c0f9b..195c19fb7e2f 100644 --- a/docs/multimodal/tts.md +++ b/docs/multimodal/tts.md @@ -15,6 +15,7 @@ Supported models: - [Fish Audio S2 Pro](#fish-audio-s2-pro) - [YuE2](#yue2) (songs) - [MiniMax Music 3](#minimax-music-3) (songs) +- [Hibiki](#hibiki) (speech translation, `llama-server` realtime endpoint only) - [Kokoro](#kokoro) - [tiny-voca](#tiny-voca) - [VoxCPM2](#voxcpm2) @@ -367,6 +368,22 @@ python convert_hf_to_gguf.py MiniMax-Music3 --mmproj --outfile mmproj-minimax-mu The mmproj holds the depth decoder and the DiT layers (in the `--outtype` type), and the condition encoder, the small DiT projections and the DAC decoder, always in F32. +## Hibiki + +Hibiki (Kyutai) translates French speech to English speech in real time. It is a full duplex model: it only runs through the [realtime endpoint](../../tools/server/README.md#full-duplex) of `llama-server`, the audio goes in and comes out every 80 ms. + +The checkpoint is not in the HF layout, the converter reads its `config.json` and the LM and mimi files it names (Hibiki-1B `kyutai/hibiki-1b-pytorch-bf16`, Hibiki-2B `kyutai/hibiki-2b-pytorch-bf16`): + +```sh +python convert_hf_to_gguf.py path/to/hibiki-1b-pytorch-bf16 --outfile hibiki-1b.gguf +python convert_hf_to_gguf.py path/to/hibiki-1b-pytorch-bf16 --mmproj --outfile mmproj-hibiki-1b.gguf + +llama-server -m hibiki-1b.gguf --mmproj mmproj-hibiki-1b.gguf -c 1500 +``` + +- The voice of the output is conditioned like the reference (`very_good`), classifier-free guidance is not supported yet +- The audio codes are sampled with the settings of the checkpoint (temperature 0.8, top-k 250), so is the text (temperature 0.8, top-k 50) unless the server sampling options override it + ## Kokoro Available params: diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index cc0347bbacf2..0592f5e016f5 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -778,6 +778,7 @@ class MODEL_ARCH(IntEnum): NANBEIGE = auto() QWEN3TTS = auto() POCKETTTS = auto() + MOSHI = auto() ZONOS3 = auto() KOKORO = auto() TINY_VOCA = auto() @@ -1793,6 +1794,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.NANBEIGE: "nanbeige", MODEL_ARCH.QWEN3TTS: "qwen3tts", MODEL_ARCH.POCKETTTS: "pockettts", + MODEL_ARCH.MOSHI: "moshi", MODEL_ARCH.ZONOS3: "zonos3", MODEL_ARCH.KOKORO: "kokoro", MODEL_ARCH.TINY_VOCA: "tiny-voca", @@ -6957,6 +6959,20 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.FFN_DOWN, MODEL_TENSOR.FFN_UP, ], + MODEL_ARCH.MOSHI: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE, + MODEL_TENSOR.FFN_DOWN, + MODEL_TENSOR.FFN_UP, + ], MODEL_ARCH.TINY_VOCA: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, @@ -7514,6 +7530,8 @@ class VisionProjectorType: QWEN3TTS_GEN = "qwen3tts_gen" # audio generation: code_predictor POCKETTTS_SPKENC = "pockettts_spkenc" # audio: mimi encoder as voice-prompt encoder POCKETTTS_GEN = "pockettts_gen" # audio generation: flow-matching decoder + mimi decoder + MOSHI = "moshi" # audio: streaming mimi encoder, input audio codes -> backbone rows + MOSHI_GEN = "moshi_gen" # audio generation: depformer + mimi decoder CHATTERBOX_SPKENC = "chatterbox_spkenc" # audio: CAMPPlus speaker encoder CHATTERBOX = "chatterbox" # audio generation: s3gen flow matching + HiFT vocoder SOPRANO = "soprano" # audio generation: Vocos decoder diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index 3cda4f7fb725..cdb1f3794fe1 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -176,6 +176,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_NANBEIGE, "nanbeige" }, { LLM_ARCH_QWEN3TTS, "qwen3tts" }, { LLM_ARCH_POCKETTTS, "pockettts" }, + { LLM_ARCH_MOSHI, "moshi" }, { LLM_ARCH_ZONOS3, "zonos3" }, { LLM_ARCH_KOKORO, "kokoro" }, { LLM_ARCH_TINY_VOCA, "tiny-voca" }, diff --git a/src/llama-arch.h b/src/llama-arch.h index 1ac22ecee67c..6517a3ea7ea9 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -177,6 +177,7 @@ enum llm_arch { LLM_ARCH_NANBEIGE, LLM_ARCH_QWEN3TTS, LLM_ARCH_POCKETTTS, + LLM_ARCH_MOSHI, LLM_ARCH_ZONOS3, LLM_ARCH_KOKORO, LLM_ARCH_TINY_VOCA, diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 81e28b1c5454..11c4569470a9 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -126,6 +126,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_qwen3tts(params); case LLM_ARCH_POCKETTTS: return new llama_model_pockettts(params); + case LLM_ARCH_MOSHI: + return new llama_model_moshi(params); case LLM_ARCH_ZONOS3: return new llama_model_zonos3(params); case LLM_ARCH_KOKORO: @@ -3154,6 +3156,27 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* filter_recr */ std::move(filter_recr), /* filter_idx */ std::move(filter_idx)); } break; + case LLM_ARCH_MOSHI: + { + // every layer attends to the same sliding window: one cache that masks it, the cells past the window are reused + res = new llama_kv_cache( + *this, + params.no_alloc, + hparams, + params.type_k, + params.type_v, + !cparams.flash_attn, + cparams.offload_kqv, + cparams.kv_unified, + cparams.n_ctx_seq, + cparams.n_seq_max, + hparams.n_swa, + LLAMA_SWA_TYPE_STANDARD, + nullptr, + nullptr, + nullptr, + nullptr); + } break; case LLM_ARCH_HY_V4: { if (hparams.indexer_top_k == 0) { @@ -3789,6 +3812,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_DOTS3NOTE: case LLM_ARCH_NANBEIGE: case LLM_ARCH_POCKETTTS: + case LLM_ARCH_MOSHI: case LLM_ARCH_ZONOS3: case LLM_ARCH_LIMITE: case LLM_ARCH_TINY_VOCA: diff --git a/src/models/models.h b/src/models/models.h index 8d2a5882772e..0f49b8ae05b1 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -770,6 +770,18 @@ struct llama_model_pockettts : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; +struct llama_model_moshi : public llama_model_base { + llama_model_moshi(const struct llama_model_params & params) : llama_model_base(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + struct graph : public llm_graph_context { + graph(const llm_graph_params & params); + }; + + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; + struct llama_model_kokoro : public llama_model_base { llama_model_kokoro(const struct llama_model_params & params) : llama_model_base(params) {} void load_arch_hparams(llama_model_loader & ml) override; diff --git a/src/models/moshi.cpp b/src/models/moshi.cpp new file mode 100644 index 000000000000..5cb63cd7e855 --- /dev/null +++ b/src/models/moshi.cpp @@ -0,0 +1,132 @@ +#include "models.h" + +// backbone of the Moshi family (e.g. Hibiki): one position per audio frame, the input rows (text + audio codes) +// are built by mtmd, the head predicts the next text token. Every layer attends to the same sliding window, see create_memory(). + +void llama_model_moshi::load_arch_hparams(llama_model_loader & ml) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + + // the window of every layer, it is applied by the KV cache, see create_memory() + ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa); + + switch (hparams.n_layer()) { + case 16: type = LLM_TYPE_1B; break; // Hibiki-M + case 24: type = LLM_TYPE_2B; break; // Hibiki + default: type = LLM_TYPE_UNKNOWN; + } +} + +void llama_model_moshi::load_arch_tensors(llama_model_loader & ml) { + LLAMA_LOAD_LOCALS; + + // the last vocab entries are input-only (e.g. the initial text token), the head has no logits for them + // a model built from metadata only has no tensor to read it from + const ggml_tensor * meta = ml.get_tensor_meta(tn(LLM_TENSOR_OUTPUT, "weight").str().c_str()); + const int64_t n_vocab_out = meta ? meta->ne[1] : n_vocab; + if (n_vocab_out < 1 || n_vocab_out > n_vocab) { + throw std::runtime_error(format("tensor 'output.weight' has invalid head size %lld (vocab size %lld)", (long long) n_vocab_out, (long long) n_vocab)); + } + + tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0); + + output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab_out}, 0); + + for (int i = 0; i < n_layer; ++i) { + auto & layer = layers[i]; + + layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0); + + create_tensor_qkv(layer, i, n_embd, n_embd, n_embd_gqa, n_embd_gqa, 0); + layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0); + + layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); + layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0); + layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); + } +} + +std::unique_ptr llama_model_moshi::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +llama_model_moshi::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { + const int64_t n_embd_head = hparams.n_embd_head_v(); + + GGML_ASSERT(n_embd_head == hparams.n_embd_head_k()); + GGML_ASSERT(n_embd_head == n_rot); + + ggml_tensor * cur; + ggml_tensor * inpL = build_inp_embd(model.tok_embd); + + ggml_tensor * inp_pos = build_inp_pos(); + + auto * inp_attn = build_attn_inp_kv(); + + ggml_tensor * inp_out_ids = build_inp_out_ids(); + + for (int il = 0; il < n_layer; ++il) { + cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + { + auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il); + + Qcur = build_rope(Qcur, inp_pos, il); + Kcur = build_rope(Kcur, inp_pos, il); + + cb(Qcur, "Qcur", il); + cb(Kcur, "Kcur", il); + cb(Vcur, "Vcur", il); + + cur = build_attn(inp_attn, + model.layers[il].wo, NULL, model.layers[il].wo_s, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il); + } + + if (il == n_layer - 1 && inp_out_ids) { + cur = ggml_get_rows(ctx0, cur, inp_out_ids); + inpL = ggml_get_rows(ctx0, inpL, inp_out_ids); + } + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpL); + cb(ffn_inp, "ffn_inp", il); + + cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + cur = build_ffn(cur, + model.layers[il].ffn_up, NULL, NULL, + model.layers[il].ffn_gate, NULL, NULL, + model.layers[il].ffn_down, NULL, NULL, + NULL, + LLM_FFN_SILU, LLM_FFN_PAR, il); + cb(cur, "ffn_out", il); + + cur = ggml_add(ctx0, cur, ffn_inp); + + cur = build_cvec(cur, il); + cb(cur, "l_out", il); + + inpL = cur; + } + + cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1); + + cb(cur, "result_norm", -1); + res->t_embd = cur; + + cur = build_lora_mm(model.output, cur, model.output_s); + + // pad the logits of the input-only tokens with -inf + const int64_t pad = model.tok_embd->ne[1] - model.output->ne[1]; + if (pad > 0) { + ggml_tensor * neg_inf = ggml_scale_bias(ctx0, ggml_view_1d(ctx0, model.output_norm, 1, 0), 0.0f, -INFINITY); + neg_inf = ggml_repeat_4d(ctx0, neg_inf, pad, cur->ne[1], 1, 1); + cur = ggml_concat(ctx0, cur, neg_inf, 0); + } + + cb(cur, "result_output", -1); + res->t_logits = cur; +} diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index b939d6683e6d..9bd4b82bfed5 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -253,6 +253,7 @@ mistral4 ,0 ,any ,ADD+ADD , 1 mistral4 ,0 ,any ,MUL+ADD , 2 mistral4 ,0 ,any ,RMS_NORM+MUL , 9 mistral4 ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +moshi ,0 ,any ,RMS_NORM+MUL , 5 mpt ,0 ,any ,NORM+MUL+ADD , 5 muse-glimmer ,0 ,any ,RMS_NORM+MUL , 10 muse-glimmer ,0 ,any ,RMS_NORM+MUL+ADD , 3 diff --git a/tools/mtmd/CMakeLists.txt b/tools/mtmd/CMakeLists.txt index 9c37d60ed0a9..cd9810e6d714 100644 --- a/tools/mtmd/CMakeLists.txt +++ b/tools/mtmd/CMakeLists.txt @@ -96,6 +96,7 @@ add_library(mtmd models/pockettts-seanet.cpp models/pockettts-spkenc.cpp models/pockettts-gen.cpp + models/moshi.cpp models/soprano.cpp models/kokoro.cpp models/tiny-voca.cpp diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index fb75270adb19..278fcdb27eb3 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -433,7 +433,11 @@ struct mtmd_graph_qwen3tts_gen : mtmd_graph { // MTMD_SUBCTX_GEN_PROCESS_TOKENIZE: reference clip -> codes and their talker input rows ggml_cgraph * build_ref_encoder(); - ggml_tensor * nearest_code(ggml_tensor * x, ggml_tensor * codebook) const; + static ggml_tensor * nearest_code(ggml_context * ctx0, ggml_tensor * x, ggml_tensor * codebook); + // split RVQ (mimi): the first codebook on x_first, the residual ones on x_rest, cb_rest is stacked on dim 2 + // x_first, x_rest: [dim, T] -> one [T] code tensor per codebook; also used by the moshi encoder + static std::vector rvq_encode(ggml_context * ctx0, ggml_tensor * x_first, ggml_tensor * cb_first, + ggml_tensor * x_rest, ggml_tensor * cb_rest); // reference encoder transformer, see encoder_config in speech_tokenizer/config.json static constexpr int ref_enc_n_head = 8; @@ -529,6 +533,8 @@ struct mtmd_graph_qwen3tts_gen : mtmd_graph { // pocket-tts: SEANet convolution stack, shared by the voice encoder and the mimi decoder. // stateless unless state_in is populated: convs then pad instead of carrying left-context. // +struct c2w_state_slot; + struct mtmd_graph_pockettts_seanet : mtmd_graph { mtmd_graph_pockettts_seanet(const mtmd_graph & parent) : mtmd_graph(parent) {} ggml_cgraph * build() override { GGML_ABORT("call encode()/decode() instead"); } @@ -542,6 +548,10 @@ struct mtmd_graph_pockettts_seanet : mtmd_graph { std::map state_in; mutable std::vector> state_out; + // the "state_in_" inputs of the slots, then the "state_out_" outputs written by the graph + void state_inputs(const std::vector & slots); + void state_outputs(ggml_cgraph * graph) const; + ggml_tensor * conv1d(ggml_tensor * x, ggml_tensor * w, ggml_tensor * b, int stride, int dilation, bool pad_replicate = false, const std::string & state_name = "") const; ggml_tensor * conv_transpose1d(ggml_tensor * x, ggml_tensor * w, ggml_tensor * b, int stride, @@ -549,10 +559,15 @@ struct mtmd_graph_pockettts_seanet : mtmd_graph { ggml_tensor * res_unit(ggml_tensor * x, const mtmd_seanet::stage & stage, int dilation, const std::string & state_prefix = "") const; - // x: [T, C] -> [T / hop, dim] + // x: [T, C] -> [T / hop, dim], streams when state_in is populated ggml_tensor * encode(ggml_tensor * x) const; // x: [T, dim] -> [T * hop, 1], streams when state_in is populated ggml_tensor * decode(ggml_tensor * x) const; + + // mimi transformer, always streams (see list_pockettts_state_slots): x: [dim, n_pos] -> [dim, n_pos] + ggml_tensor * transformer(ggml_tensor * x, const std::vector & layers, int n_head, float eps) const; + // mimi decoder: upsample, transformer, SEANet decoder; x: [dim, n_frames] -> [n_samples, 1] + ggml_tensor * mimi_decode(ggml_tensor * x, int n_head, float eps) const; }; // mimi encoder + speaker_proj: reference waveform -> voice conditioning rows @@ -594,6 +609,43 @@ struct mtmd_graph_pockettts_gen : mtmd_graph { ggml_tensor * flow_forward(ggml_tensor * cond, ggml_tensor * x, float s, float t) const; }; +// +// moshi family (e.g. Hibiki): streaming mimi encoder + RVQ, rows of the input audio codes +// output: [n_embd, n_q * (n_frames + 1)], the embedding of each code of each frame, then of the initial codes +// +struct mtmd_graph_moshi : mtmd_graph { + mtmd_graph_moshi(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} + ggml_cgraph * build() override; + + static constexpr int n_samples_per_frame = 1920; // 80 ms at 24 kHz +}; + +// +// moshi generation: +// GEN_CODE = depformer, the codes of one frame + their backbone embedding; with all codes known, only the embedding +// GEN_WAV = RVQ decode + mimi decoder +// +struct mtmd_graph_moshi_gen : mtmd_graph { + mtmd_graph_moshi_gen(mtmd_subcontext * ctx, const mtmd_image_f32 & img, mtmd_subctx_gen_process gen_process, bool fb_only, + int n_frames, int top_k, float temp) + : mtmd_graph(ctx, img), gen_process(gen_process), fb_only(fb_only), n_frames(n_frames), top_k(top_k), temp(temp) {} + ggml_cgraph * build() override; + + static constexpr int mimi_n_layer = 8; + static constexpr int mimi_n_head = 8; + static constexpr float mimi_eps = 1e-5f; + static constexpr int n_q_max = 32; + + mtmd_subctx_gen_process gen_process; + bool fb_only; + int n_frames; + int top_k; + float temp; + + ggml_tensor * dep_step(ggml_tensor * x, int64_t iw, std::vector & k_all, std::vector & v_all); + ggml_tensor * feedback(const std::vector & codes); +}; + // one persisted state buffer used by code2wav, see qwen3tts-gen.cpp struct c2w_state_slot { std::string name; @@ -609,6 +661,9 @@ std::vector list_drama3_state_slots(const mtmd_hparams & hparams // same, for the streaming mimi decoder (pocket-tts GEN_WAV) std::vector list_pockettts_state_slots(const mtmd_hparams & hparams, const mtmd_model & model); +// streaming mimi encoder of moshi, "pos" leads +std::vector list_moshi_state_slots(const mtmd_hparams & hparams, const mtmd_model & model); + // // drama3 generation: // GEN_CODE = one codebook tower row, each layer attends over the whole sequence (KV in gen state) diff --git a/tools/mtmd/models/moshi.cpp b/tools/mtmd/models/moshi.cpp new file mode 100644 index 000000000000..ff99f10a07a9 --- /dev/null +++ b/tools/mtmd/models/moshi.cpp @@ -0,0 +1,265 @@ +#include "models.h" + +// Moshi family (e.g. Hibiki), see conversion/moshi.py +// +// encoder (audio stream): streaming mimi encoder -> RVQ -> backbone embeddings of the input codes +// GEN_CODE: depformer, the codes of one frame from the backbone hidden state and the text token, then their embedding +// GEN_WAV : RVQ decode -> streaming mimi decoder + +// 2D slice i of a tensor stacked on dim 2 +static ggml_tensor * moshi_slice(ggml_context * ctx0, ggml_tensor * w, int64_t i) { + return ggml_view_2d(ctx0, w, w->ne[0], w->ne[1], w->nb[1], (size_t) i * w->nb[2]); +} + +std::vector list_moshi_state_slots(const mtmd_hparams & hparams, const mtmd_model & model) { + std::vector slots; + const auto & seanet = model.seanet; + + slots.push_back({"pos", 1, 1}); + + const int64_t n_embd_a = model.layers[0].q_w->ne[1]; + const int64_t prefix = hparams.mimi_tfm_context - 1; + for (size_t il = 0; il < model.layers.size(); il++) { + slots.push_back({"tfm_k_" + std::to_string(il), n_embd_a, prefix}); + slots.push_back({"tfm_v_" + std::to_string(il), n_embd_a, prefix}); + } + + // left context of the causal convs, [kernel - stride, in channels] + slots.push_back({"enc_in", seanet.conv_in_w->ne[0] - 1, seanet.conv_in_w->ne[1]}); + for (int i = 0; i < hparams.seanet_n_stage; i++) { + const auto & stage = seanet.stages[i]; + slots.push_back({"enc_res_" + std::to_string(i), stage.res_conv1_w->ne[0] - 1, stage.res_conv1_w->ne[1]}); + slots.push_back({"enc_down_" + std::to_string(i), stage.scale_conv_w->ne[0] - hparams.seanet_ratios[i], stage.scale_conv_w->ne[1]}); + } + slots.push_back({"enc_out", seanet.conv_out_w->ne[0] - 1, seanet.conv_out_w->ne[1]}); + slots.push_back({"down", model.downsample_w->ne[0] - hparams.mimi_downsample, model.downsample_w->ne[1]}); + + return slots; +} + +// waveform of whole frames -> [n_embd, n_q, n_frames + 1]: the embedding of each input code, then of the initial codes +ggml_cgraph * mtmd_graph_moshi::build() { + // the waveform comes in as a single-row "mel", [n_samples, 1] + ggml_tensor * inp_raw = build_inp_raw(1); + ggml_tensor * cur = ggml_reshape_2d(ctx0, inp_raw, inp_raw->ne[0], inp_raw->ne[1]); + GGML_ASSERT(cur->ne[0] % n_samples_per_frame == 0); + + // the graph always streams, a zero state encodes a clip from its start + mtmd_graph_pockettts_seanet seanet(*this); + seanet.state_inputs(list_moshi_state_slots(hparams, model)); + ggml_tensor * pos_in = seanet.state_in.at("pos"); + + cur = seanet.encode(cur); + cb(cur, "mimi_enc", -1); + + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + cur = seanet.transformer(cur, model.layers, hparams.n_head, hparams.eps); + cb(cur, "mimi_enc_tfm", -1); + + // the downsample conv repeats the first frame on its left at the stream start, the state is zero then + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + { + const int64_t n_left = seanet.state_in.at("down")->ne[0]; + ggml_tensor * first = ggml_repeat_4d(ctx0, ggml_view_2d(ctx0, cur, 1, cur->ne[1], cur->nb[1], 0), n_left, cur->ne[1], 1, 1); + ggml_tensor * is_first = ggml_step(ctx0, ggml_scale_bias(ctx0, pos_in, -1.0f, 0.5f)); + seanet.state_in["down"] = ggml_add(ctx0, seanet.state_in.at("down"), ggml_mul(ctx0, first, is_first)); + } + cur = seanet.conv1d(cur, model.downsample_w, nullptr, hparams.mimi_downsample, 1, false, "down"); + cb(cur, "mimi_downsample", -1); + + seanet.state_outputs(gf); + + // split RVQ: the semantic codebook, then the residual acoustic ones, all from the same latent + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); // [512, n_frames] + const auto & c2w = model.c2w; + const int64_t n_frames = cur->ne[1]; + const int64_t n_q = model.mm_a_code_embd->ne[2]; + const int64_t n_embd = model.mm_a_code_embd->ne[0]; + + const std::vector codes = mtmd_graph_qwen3tts_gen::rvq_encode(ctx0, + build_mm(c2w.quant_first_in_w, cur), c2w.quant_first_cb_w, build_mm(c2w.quant_rest_in_w, cur), c2w.quant_rest_cb_w); + GGML_ASSERT((int64_t) codes.size() == n_q); + + // [n_embd, n_frames, n_q] -> [n_embd, n_q, n_frames] + ggml_tensor * embd = nullptr; + for (int64_t k = 0; k < n_q; k++) { + cb(codes[k], "in_code", (int) k); + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, model.mm_a_code_embd, k), codes[k]); + e = ggml_reshape_3d(ctx0, e, n_embd, n_frames, 1); + embd = embd ? ggml_concat(ctx0, embd, e, 2) : e; + } + embd = ggml_cont(ctx0, ggml_permute(ctx0, embd, 0, 2, 1, 3)); + + // the initial code is the last entry of every table + const float code_initial = (float) (model.mm_a_code_embd->ne[1] - 1); + ggml_tensor * idx_initial = ggml_cast(ctx0, ggml_arange(ctx0, code_initial, code_initial + 1.0f, 1.0f), GGML_TYPE_I32); + ggml_tensor * init = nullptr; + for (int64_t k = 0; k < n_q; k++) { + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, model.mm_a_code_embd, k), idx_initial); + init = init ? ggml_concat(ctx0, init, e, 1) : e; + } + embd = ggml_concat(ctx0, embd, ggml_reshape_3d(ctx0, init, n_embd, n_q, 1), 2); + + embd = ggml_reshape_2d(ctx0, embd, n_embd, n_q * (n_frames + 1)); + cb(embd, "moshi_in_embd", -1); + ggml_build_forward_expand(gf, embd); + + return gf; +} + +// one depformer step: input row x [n_dep, 1], the K/V of the steps so far grow by one row per layer +ggml_tensor * mtmd_graph_moshi_gen::dep_step(ggml_tensor * x, int64_t iw, std::vector & k_all, std::vector & v_all) { + const int64_t n_dep = x->ne[0]; + const int64_t d_head = n_dep / n_head; + + for (size_t il = 0; il < model.layers.size(); il++) { + const auto & layer = model.layers[il]; + ggml_tensor * inp = x; + + ggml_tensor * cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, x, eps), layer.ln_1_w); + ggml_tensor * q = ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.q_w, iw), cur); + ggml_tensor * k = ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.k_w, iw), cur); + ggml_tensor * v = ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.v_w, iw), cur); + + // no positional embedding, causal over the steps of this frame + k_all[il] = k_all[il] ? ggml_concat(ctx0, k_all[il], k, 1) : k; + v_all[il] = v_all[il] ? ggml_concat(ctx0, v_all[il], v, 1) : v; + const int64_t n_kv = k_all[il]->ne[1]; + + cur = build_attn(nullptr, nullptr, + ggml_reshape_4d(ctx0, q, d_head, n_head, 1, 1), + ggml_reshape_4d(ctx0, k_all[il], d_head, n_head, n_kv, 1), + ggml_reshape_4d(ctx0, v_all[il], d_head, n_head, n_kv, 1), + nullptr, 1.0f / sqrtf((float) d_head), (int) il); + x = ggml_add(ctx0, inp, ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.o_w, iw), cur)); + + cur = ggml_mul(ctx0, ggml_rms_norm(ctx0, x, eps), layer.ln_2_w); + cur = ggml_swiglu_split(ctx0, ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.ff_gate_w, iw), cur), + ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.ff_up_w, iw), cur)); + x = ggml_add(ctx0, x, ggml_mul_mat(ctx0, moshi_slice(ctx0, layer.ff_down_w, iw), cur)); + } + return x; +} + +// backbone input of the next frame: sum of the embeddings of the generated codes +ggml_tensor * mtmd_graph_moshi_gen::feedback(const std::vector & codes) { + ggml_tensor * fb = nullptr; + for (size_t k = 0; k < codes.size(); k++) { + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, model.gen_code_out_embd_w, (int64_t) k), codes[k]); + fb = fb ? ggml_add(ctx0, fb, e) : e; + } + return fb; +} + +ggml_cgraph * mtmd_graph_moshi_gen::build() { + const int64_t n_q = model.gen_code_head_w->ne[2]; + + if (gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_WAV) { + // codebook-major: row k holds codebook k of every frame + ggml_tensor * inp_codes = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, n_frames, n_q); + ggml_set_name(inp_codes, "inp_codes"); + ggml_set_input(inp_codes); + + auto codes_of = [&](int64_t k) { + return ggml_view_1d(ctx0, inp_codes, n_frames, (size_t) k * inp_codes->nb[1]); + }; + + // RVQ decode: output_proj(sum of the codebook entries) of the semantic and acoustic parts + const auto & c2w = model.c2w; + ggml_tensor * rest = nullptr; + for (int64_t k = 1; k < n_q; k++) { + ggml_tensor * e = ggml_get_rows(ctx0, moshi_slice(ctx0, c2w.quant_rest_cb_w, k - 1), codes_of(k)); + rest = rest ? ggml_add(ctx0, rest, e) : e; + } + ggml_tensor * cur = build_mm(c2w.quant_first_out_w, ggml_get_rows(ctx0, c2w.quant_first_cb_w, codes_of(0))); + cur = ggml_add(ctx0, cur, build_mm(c2w.quant_rest_out_w, rest)); + cb(cur, "rvq_decode", -1); + + mtmd_graph_pockettts_seanet seanet(*this); + seanet.state_inputs(list_pockettts_state_slots(hparams, model)); + + cur = seanet.mimi_decode(cur, mimi_n_head, mimi_eps); + + seanet.state_outputs(gf); + + cur = ggml_reshape_1d(ctx0, cur, cur->ne[0]); + ggml_set_name(cur, "out_audio"); + ggml_set_output(cur); + ggml_build_forward_expand(gf, cur); + return gf; + } + + // GEN_CODE with all codes known: only their embedding + if (fb_only) { + ggml_tensor * inp_codes = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_q); + ggml_set_name(inp_codes, "inp_codes"); + ggml_set_input(inp_codes); + + std::vector codes; + for (int64_t k = 0; k < n_q; k++) { + codes.push_back(ggml_view_1d(ctx0, inp_codes, 1, (size_t) k * sizeof(int32_t))); + } + ggml_tensor * fb = feedback(codes); + cb(fb, "gen_audio_out", -1); + ggml_build_forward_expand(gf, fb); + return gf; + } + + // the backbone hidden state arrives as the single batch entry + ggml_tensor * h = ggml_reshape_2d(ctx0, build_inp_raw(1), n_mmproj_embd, 1); + + ggml_tensor * inp_code0 = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1); // the sampled text token + ggml_set_name(inp_code0, "inp_code0"); + ggml_set_input(inp_code0); + + ggml_tensor * inp_rand = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, n_q); + ggml_set_name(inp_rand, "inp_rand"); + ggml_set_input(inp_rand); + + mtmd_graph_qwen3tts_gen::code_gen cg(*this, top_k, 1.0f); + + // steps past the last weight set reuse it + const int64_t n_w = model.gen_code_proj_in_w->ne[2]; + + std::vector k_all(model.layers.size(), nullptr); + std::vector v_all(model.layers.size(), nullptr); + std::vector codes; + ggml_tensor * out_codes = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, 1, n_q); + + for (int64_t k = 0; k < n_q; k++) { + const int64_t iw = std::min(k, n_w - 1); + + // the previous token: the text token, then the codes of this frame + ggml_tensor * prev = k == 0 ? ggml_get_rows(ctx0, model.gen_code_tok_embd_w, inp_code0) + : ggml_get_rows(ctx0, moshi_slice(ctx0, model.gen_code_embd_w, k - 1), codes.back()); + ggml_tensor * x = ggml_add(ctx0, ggml_mul_mat(ctx0, moshi_slice(ctx0, model.gen_code_proj_in_w, iw), h), prev); + + x = dep_step(x, iw, k_all, v_all); + + ggml_tensor * logits = ggml_mul_mat(ctx0, moshi_slice(ctx0, model.gen_code_head_w, k), x); + cb(logits, "dep_logits", (int) k); + + ggml_tensor * code; + if (temp <= 0.0f) { + code = ggml_argmax(ctx0, logits); + } else { + if (temp != 1.0f) { + logits = ggml_scale(ctx0, logits, 1.0f / temp); + } + code = cg.do_sampling(logits, ggml_view_1d(ctx0, inp_rand, 1, (size_t) k * sizeof(float))); + } + codes.push_back(code); + out_codes = cg.cache_set(out_codes, (int) k, code); + } + + out_codes = ggml_cont(ctx0, out_codes); + ggml_set_name(out_codes, "out_codes"); + ggml_set_output(out_codes); + ggml_build_forward_expand(gf, out_codes); + + ggml_tensor * fb = feedback(codes); + cb(fb, "gen_audio_out", -1); + ggml_build_forward_expand(gf, fb); + + return gf; +} diff --git a/tools/mtmd/models/pockettts-gen.cpp b/tools/mtmd/models/pockettts-gen.cpp index c5f340656d6a..db38b8b69dd4 100644 --- a/tools/mtmd/models/pockettts-gen.cpp +++ b/tools/mtmd/models/pockettts-gen.cpp @@ -112,7 +112,7 @@ std::vector list_pockettts_state_slots(const mtmd_hparams & hpar GGML_ASSERT((int) hparams.seanet_ratios.size() >= hparams.seanet_n_stage); GGML_ASSERT(hparams.mimi_tfm_context > 1 && hparams.mimi_downsample > 0); - slots.push_back({"tfm_pos", 1, 1}); + slots.push_back({"pos", 1, 1}); const int64_t n_embd_a = model.gen_tfm_layers[0].q_w->ne[1]; const int64_t prefix = hparams.mimi_tfm_context - 1; @@ -189,99 +189,11 @@ ggml_cgraph * mtmd_graph_pockettts_gen::build() { cb(cur, "quant_out", -1); mtmd_graph_pockettts_seanet seanet(*this); - for (const auto & slot : list_pockettts_state_slots(hparams, model)) { - ggml_tensor * t = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, slot.ne0, slot.ne1); - ggml_set_name(t, ("state_in_" + slot.name).c_str()); - ggml_set_input(t); - seanet.state_in[slot.name] = t; - } - - // model frame rate -> encoder frame rate, depthwise transposed conv - cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); - cur = seanet.conv_transpose1d(cur, model.gen_upsample_w, nullptr, hparams.mimi_downsample, "up"); - cb(cur, "mimi_upsample", -1); - - cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); - - // positions continue across calls, the counter lives in the state - const int64_t n_pos = cur->ne[1]; - const int64_t prefix = hparams.mimi_tfm_context - 1; - const int64_t n_kv = prefix + n_pos; - - ggml_tensor * base = ggml_reshape_1d(ctx0, seanet.state_in.at("tfm_pos"), 1); - ggml_tensor * inp_pos = ggml_cast(ctx0, ggml_add(ctx0, ggml_arange(ctx0, 0.0f, (float) n_pos, 1.0f), base), - GGML_TYPE_I32); - seanet.state_out.push_back({"tfm_pos", ggml_scale_bias(ctx0, seanet.state_in.at("tfm_pos"), 1.0f, (float) n_pos)}); - - // banded causal mask over [cached prefix | this chunk] - // the last factor masks out cache rows that hold no real frame yet - ggml_tensor * pos_k = ggml_reshape_2d(ctx0, ggml_arange(ctx0, 0.0f, (float) n_kv, 1.0f), n_kv, 1); - ggml_tensor * pos_q = ggml_reshape_2d(ctx0, ggml_arange(ctx0, (float) prefix, (float) (prefix + n_pos), 1.0f), 1, n_pos); - ggml_tensor * diff = ggml_sub(ctx0, ggml_repeat_4d(ctx0, pos_q, n_kv, n_pos, 1, 1), pos_k); - - ggml_tensor * keep = ggml_mul(ctx0, - ggml_step(ctx0, ggml_scale_bias(ctx0, diff, 1.0f, 0.5f)), // delta >= 0 - ggml_step(ctx0, ggml_scale_bias(ctx0, diff, -1.0f, (float) hparams.mimi_tfm_context - 0.5f))); // delta < context - keep = ggml_mul(ctx0, keep, - ggml_step(ctx0, ggml_scale_bias(ctx0, ggml_add(ctx0, pos_k, base), 1.0f, 0.5f - (float) prefix))); - ggml_tensor * kq_mask = ggml_reshape_4d(ctx0, ggml_log(ctx0, keep), n_kv, n_pos, 1, 1); - if (flash_attn_type == MTMD_FLASH_ATTN_TYPE_ENABLED) { - kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); - } + seanet.state_inputs(list_pockettts_state_slots(hparams, model)); - for (int il = 0; il < n_layer; il++) { - const auto & layer = model.gen_tfm_layers[il]; - ggml_tensor * inp = cur; - - cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, NORM_TYPE_NORMAL, eps, il); - - ggml_tensor * Qcur = build_mm(layer.q_w, cur); - ggml_tensor * Kcur = build_mm(layer.k_w, cur); - ggml_tensor * Vcur = build_mm(layer.v_w, cur); - - Qcur = ggml_reshape_3d(ctx0, Qcur, d_head, n_head, n_pos); - Kcur = ggml_reshape_3d(ctx0, Kcur, d_head, n_head, n_pos); - - Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, - hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); - Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, - hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); - - // prepend the cached window, then keep this chunk's tail for the next call - const std::string k_name = "tfm_k_" + std::to_string(il); - const std::string v_name = "tfm_v_" + std::to_string(il); - ggml_tensor * k_full = ggml_concat(ctx0, seanet.state_in.at(k_name), - ggml_reshape_2d(ctx0, Kcur, d_head * n_head, n_pos), 1); - ggml_tensor * v_full = ggml_concat(ctx0, seanet.state_in.at(v_name), Vcur, 1); - seanet.state_out.push_back({k_name, ggml_cont(ctx0, ggml_view_2d(ctx0, k_full, k_full->ne[0], prefix, - k_full->nb[1], (size_t) n_pos * k_full->nb[1]))}); - seanet.state_out.push_back({v_name, ggml_cont(ctx0, ggml_view_2d(ctx0, v_full, v_full->ne[0], prefix, - v_full->nb[1], (size_t) n_pos * v_full->nb[1]))}); - - ggml_tensor * q_cur = ggml_reshape_4d(ctx0, Qcur, d_head, n_head, n_pos, 1); - ggml_tensor * k_cur = ggml_reshape_4d(ctx0, k_full, d_head, n_head, n_kv, 1); - ggml_tensor * v_cur = ggml_reshape_4d(ctx0, v_full, d_head, n_head, n_kv, 1); - - cur = build_attn(layer.o_w, nullptr, q_cur, k_cur, v_cur, kq_mask, kq_scale, il); - cur = ggml_mul(ctx0, cur, layer.ls_1_w); - cur = ggml_add(ctx0, cur, inp); - - inp = cur; - cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, NORM_TYPE_NORMAL, eps, il); - cur = build_ffn(cur, layer.ff_up_w, nullptr, nullptr, nullptr, layer.ff_down_w, nullptr, FFN_GELU, il); - cur = ggml_mul(ctx0, cur, layer.ls_2_w); - cur = ggml_add(ctx0, cur, inp); - } - cb(cur, "mimi_dec_tfm", -1); - - cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); - cur = seanet.decode(cur); + cur = seanet.mimi_decode(cur, n_head, eps); - for (const auto & s : seanet.state_out) { - ggml_set_name(s.second, ("state_out_" + s.first).c_str()); - ggml_set_output(s.second); - ggml_build_forward_expand(gf, s.second); - } + seanet.state_outputs(gf); // [n_samples, 1] -> [n_samples], clamped like the reference output cur = ggml_reshape_1d(ctx0, cur, cur->ne[0]); diff --git a/tools/mtmd/models/pockettts-seanet.cpp b/tools/mtmd/models/pockettts-seanet.cpp index f1073c8442ff..e0a97bdc6a5b 100644 --- a/tools/mtmd/models/pockettts-seanet.cpp +++ b/tools/mtmd/models/pockettts-seanet.cpp @@ -125,22 +125,27 @@ ggml_tensor * mtmd_graph_pockettts_seanet::res_unit(ggml_tensor * x, const mtmd_ ggml_tensor * mtmd_graph_pockettts_seanet::encode(ggml_tensor * x) const { const auto & seanet = model.seanet; + const bool stream = !state_in.empty(); - ggml_tensor * cur = conv1d(x, seanet.conv_in_w, seanet.conv_in_b, 1, 1); + ggml_tensor * cur = conv1d(x, seanet.conv_in_w, seanet.conv_in_b, 1, 1, false, + stream ? "enc_in" : ""); cb(cur, "seanet_enc_in", -1); for (int i = 0; i < hparams.seanet_n_stage; i++) { const auto & stage = seanet.stages[i]; const int stride = hparams.seanet_ratios[i]; + const std::string id = std::to_string(i); - cur = res_unit(cur, stage, 1); + cur = res_unit(cur, stage, 1, stream ? "enc_res_" + id : ""); cur = ggml_elu(ctx0, cur); - cur = conv1d(cur, stage.scale_conv_w, stage.scale_conv_b, stride, 1); + cur = conv1d(cur, stage.scale_conv_w, stage.scale_conv_b, stride, 1, false, + stream ? "enc_down_" + id : ""); cb(cur, "seanet_enc_stage", i); } cur = ggml_elu(ctx0, cur); - cur = conv1d(cur, seanet.conv_out_w, seanet.conv_out_b, 1, 1); + cur = conv1d(cur, seanet.conv_out_w, seanet.conv_out_b, 1, 1, false, + stream ? "enc_out" : ""); cb(cur, "seanet_enc_out", -1); return cur; @@ -174,3 +179,112 @@ ggml_tensor * mtmd_graph_pockettts_seanet::decode(ggml_tensor * x) const { return cur; } + +// pre-norm blocks with layer scale on both residual paths, see mimi_transformer.py +// causal over a window of mimi_tfm_context frames, streams through the slots pos, tfm_k_, tfm_v_ +// x: [dim, n_pos] -> [dim, n_pos] +ggml_tensor * mtmd_graph_pockettts_seanet::transformer(ggml_tensor * cur, const std::vector & layers, int n_head, float eps) const { + const int64_t n_pos = cur->ne[1]; + const int64_t d_head = cur->ne[0] / n_head; + const int64_t prefix = hparams.mimi_tfm_context - 1; + const int64_t n_kv = prefix + n_pos; + const float scale = 1.0f / sqrtf((float) d_head); + + // positions continue across calls, the counter lives in the state + ggml_tensor * base = ggml_reshape_1d(ctx0, state_in.at("pos"), 1); + ggml_tensor * inp_pos = ggml_cast(ctx0, ggml_add(ctx0, ggml_arange(ctx0, 0.0f, (float) n_pos, 1.0f), base), + GGML_TYPE_I32); + state_out.push_back({"pos", ggml_scale_bias(ctx0, state_in.at("pos"), 1.0f, (float) n_pos)}); + + // banded causal mask over [cached prefix | this chunk] + // the last factor masks out cache rows that hold no real frame yet + ggml_tensor * pos_k = ggml_reshape_2d(ctx0, ggml_arange(ctx0, 0.0f, (float) n_kv, 1.0f), n_kv, 1); + ggml_tensor * pos_q = ggml_reshape_2d(ctx0, ggml_arange(ctx0, (float) prefix, (float) (prefix + n_pos), 1.0f), 1, n_pos); + ggml_tensor * diff = ggml_sub(ctx0, ggml_repeat_4d(ctx0, pos_q, n_kv, n_pos, 1, 1), pos_k); + + ggml_tensor * keep = ggml_mul(ctx0, + ggml_step(ctx0, ggml_scale_bias(ctx0, diff, 1.0f, 0.5f)), // delta >= 0 + ggml_step(ctx0, ggml_scale_bias(ctx0, diff, -1.0f, (float) hparams.mimi_tfm_context - 0.5f))); // delta < context + keep = ggml_mul(ctx0, keep, + ggml_step(ctx0, ggml_scale_bias(ctx0, ggml_add(ctx0, pos_k, base), 1.0f, 0.5f - (float) prefix))); + ggml_tensor * kq_mask = ggml_reshape_4d(ctx0, ggml_log(ctx0, keep), n_kv, n_pos, 1, 1); + if (flash_attn_type == MTMD_FLASH_ATTN_TYPE_ENABLED) { + kq_mask = ggml_cast(ctx0, kq_mask, GGML_TYPE_F16); + } + + for (size_t il = 0; il < layers.size(); il++) { + const auto & layer = layers[il]; + ggml_tensor * inp = cur; + + cur = build_norm(cur, layer.ln_1_w, layer.ln_1_b, NORM_TYPE_NORMAL, eps, il); + + ggml_tensor * Qcur = build_mm(layer.q_w, cur); + ggml_tensor * Kcur = build_mm(layer.k_w, cur); + ggml_tensor * Vcur = build_mm(layer.v_w, cur); + + Qcur = ggml_reshape_3d(ctx0, Qcur, d_head, n_head, n_pos); + Kcur = ggml_reshape_3d(ctx0, Kcur, d_head, n_head, n_pos); + + Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, + hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, nullptr, d_head, GGML_ROPE_TYPE_NORMAL, 0, + hparams.rope_theta, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f); + + // prepend the cached window, then keep this chunk's tail for the next call + const std::string k_name = "tfm_k_" + std::to_string(il); + const std::string v_name = "tfm_v_" + std::to_string(il); + ggml_tensor * k_full = ggml_concat(ctx0, state_in.at(k_name), + ggml_reshape_2d(ctx0, Kcur, d_head * n_head, n_pos), 1); + ggml_tensor * v_full = ggml_concat(ctx0, state_in.at(v_name), Vcur, 1); + state_out.push_back({k_name, ggml_cont(ctx0, ggml_view_2d(ctx0, k_full, k_full->ne[0], prefix, + k_full->nb[1], (size_t) n_pos * k_full->nb[1]))}); + state_out.push_back({v_name, ggml_cont(ctx0, ggml_view_2d(ctx0, v_full, v_full->ne[0], prefix, + v_full->nb[1], (size_t) n_pos * v_full->nb[1]))}); + + ggml_tensor * q_cur = ggml_reshape_4d(ctx0, Qcur, d_head, n_head, n_pos, 1); + ggml_tensor * k_cur = ggml_reshape_4d(ctx0, k_full, d_head, n_head, n_kv, 1); + ggml_tensor * v_cur = ggml_reshape_4d(ctx0, v_full, d_head, n_head, n_kv, 1); + + cur = build_attn(layer.o_w, nullptr, q_cur, k_cur, v_cur, kq_mask, scale, il); + cur = ggml_mul(ctx0, cur, layer.ls_1_w); + cur = ggml_add(ctx0, cur, inp); + + inp = cur; + cur = build_norm(cur, layer.ln_2_w, layer.ln_2_b, NORM_TYPE_NORMAL, eps, il); + cur = build_ffn(cur, layer.ff_up_w, nullptr, nullptr, nullptr, layer.ff_down_w, nullptr, FFN_GELU, il); + cur = ggml_mul(ctx0, cur, layer.ls_2_w); + cur = ggml_add(ctx0, cur, inp); + } + return cur; +} + +ggml_tensor * mtmd_graph_pockettts_seanet::mimi_decode(ggml_tensor * x, int n_head, float eps) const { + // model frame rate -> encoder frame rate, depthwise transposed conv + ggml_tensor * cur = ggml_cont(ctx0, ggml_transpose(ctx0, x)); + cur = conv_transpose1d(cur, model.gen_upsample_w, nullptr, hparams.mimi_downsample, "up"); + cb(cur, "mimi_upsample", -1); + + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + cur = transformer(cur, model.gen_tfm_layers, n_head, eps); + cb(cur, "mimi_dec_tfm", -1); + + cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); + return decode(cur); +} + +void mtmd_graph_pockettts_seanet::state_inputs(const std::vector & slots) { + for (const auto & slot : slots) { + ggml_tensor * t = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, slot.ne0, slot.ne1); + ggml_set_name(t, ("state_in_" + slot.name).c_str()); + ggml_set_input(t); + state_in[slot.name] = t; + } +} + +void mtmd_graph_pockettts_seanet::state_outputs(ggml_cgraph * graph) const { + for (const auto & s : state_out) { + ggml_set_name(s.second, ("state_out_" + s.first).c_str()); + ggml_set_output(s.second); + ggml_build_forward_expand(graph, s.second); + } +} diff --git a/tools/mtmd/models/qwen3tts-gen.cpp b/tools/mtmd/models/qwen3tts-gen.cpp index a453b09f515a..8cee94407bb0 100644 --- a/tools/mtmd/models/qwen3tts-gen.cpp +++ b/tools/mtmd/models/qwen3tts-gen.cpp @@ -665,7 +665,7 @@ std::vector list_c2w_state_slots(const mtmd_hparams & hparams, c } // x: [dim, T], codebook: [dim, n_entries] -> [T] index of the nearest entry -ggml_tensor * mtmd_graph_qwen3tts_gen::nearest_code(ggml_tensor * x, ggml_tensor * codebook) const { +ggml_tensor * mtmd_graph_qwen3tts_gen::nearest_code(ggml_context * ctx0, ggml_tensor * x, ggml_tensor * codebook) { // argmin |x - e|^2 = argmax 2 x.e - |e|^2 ggml_tensor * dots = ggml_mul_mat(ctx0, codebook, x); // [n_entries, T] ggml_tensor * norms = ggml_sum_rows(ctx0, ggml_sqr(ctx0, codebook)); // [1, n_entries] @@ -673,6 +673,24 @@ ggml_tensor * mtmd_graph_qwen3tts_gen::nearest_code(ggml_tensor * x, ggml_tensor return ggml_argmax(ctx0, ggml_sub(ctx0, ggml_scale(ctx0, dots, 2.0f), norms)); } +std::vector mtmd_graph_qwen3tts_gen::rvq_encode(ggml_context * ctx0, ggml_tensor * x_first, ggml_tensor * cb_first, + ggml_tensor * x_rest, ggml_tensor * cb_rest) { + std::vector codes; + codes.push_back(nearest_code(ctx0, x_first, cb_first)); + + const int64_t n_rest = cb_rest->ne[2]; + ggml_tensor * residual = x_rest; + for (int64_t i = 0; i < n_rest; i++) { + ggml_tensor * codebook = ggml_view_2d(ctx0, cb_rest, cb_rest->ne[0], cb_rest->ne[1], cb_rest->nb[1], (size_t) i * cb_rest->nb[2]); + ggml_tensor * code = nearest_code(ctx0, residual, codebook); + codes.push_back(code); + if (i + 1 < n_rest) { + residual = ggml_sub(ctx0, residual, ggml_get_rows(ctx0, codebook, code)); + } + } + return codes; +} + // the mimi encoder of the speech tokenizer, then its RVQ: one semantic codebook and n_acoustic acoustic ones ggml_cgraph * mtmd_graph_qwen3tts_gen::build_ref_encoder() { // the waveform comes in as a single-row "mel", [n_samples, 1] @@ -694,20 +712,9 @@ ggml_cgraph * mtmd_graph_qwen3tts_gen::build_ref_encoder() { cur = mimi.encode(seanet, cur, model.ref_enc_layers); cur = ggml_cont(ctx0, ggml_transpose(ctx0, cur)); // [512, T] - std::vector codes; - codes.push_back(nearest_code(build_mm(model.ref_quant_first_in_w, cur), model.ref_quant_first_cb)); - + const std::vector codes = rvq_encode(ctx0, build_mm(model.ref_quant_first_in_w, cur), model.ref_quant_first_cb, + build_mm(model.ref_quant_rest_in_w, cur), model.ref_quant_rest_cb); const int64_t n_acoustic = model.ref_quant_rest_cb->ne[2]; - ggml_tensor * residual = build_mm(model.ref_quant_rest_in_w, cur); - for (int64_t i = 0; i < n_acoustic; i++) { - ggml_tensor * codebook = ggml_view_2d(ctx0, model.ref_quant_rest_cb, model.ref_quant_rest_cb->ne[0], model.ref_quant_rest_cb->ne[1], - model.ref_quant_rest_cb->nb[1], (size_t) i * model.ref_quant_rest_cb->nb[2]); - ggml_tensor * code = nearest_code(residual, codebook); - codes.push_back(code); - if (i + 1 < n_acoustic) { - residual = ggml_sub(ctx0, residual, ggml_get_rows(ctx0, codebook, code)); - } - } // talker input rows of the reference frames: codebook 0 from the talker table, the rest from the code predictor's ggml_tensor * rows = ggml_get_rows(ctx0, model.gen_code_out_embd_w, codes[0]); diff --git a/tools/mtmd/mtmd-cli.cpp b/tools/mtmd/mtmd-cli.cpp index 4534527fc8a7..8fc8d1b892ce 100644 --- a/tools/mtmd/mtmd-cli.cpp +++ b/tools/mtmd/mtmd-cli.cpp @@ -120,6 +120,10 @@ struct mtmd_cli_context { init_vision_context(params); mtmd_cap = mtmd_helper_get_capabilities(model, ctx_vision.get()); + if (mtmd_cap.audio_duplex) { + LOG_ERR("Full duplex models only run in llama-server, see the /v1/realtime endpoint\n"); + exit(1); + } // a realtime transcription model has no chat, it streams the audio below if (!mtmd_cap.chat && !mtmd_cap.audio_stream) { LOG_ERR("Model does not support chat mode\n"); diff --git a/tools/mtmd/mtmd-graph.cpp b/tools/mtmd/mtmd-graph.cpp index 81ae155acefd..a22f41d372da 100644 --- a/tools/mtmd/mtmd-graph.cpp +++ b/tools/mtmd/mtmd-graph.cpp @@ -1000,6 +1000,24 @@ std::unique_ptr mtmd_get_graph_builder(mtmd_subcontext * ctx, const { builder = std::make_unique(ctx, img); } break; + case PROJECTOR_TYPE_MOSHI: + { + builder = std::make_unique(ctx, img); + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + const auto gen_process = params ? params->gen_process : MTMD_SUBCTX_GEN_PROCESS_GEN_CODE; + const int64_t n_q = ctx->model.gen_code_head_w->ne[2]; + const bool has_codes = params && params->codes; + if (has_codes) { + GGML_ASSERT(params->codes->size() % (size_t) n_q == 0); + } + const int n_frames = has_codes ? (int) (params->codes->size() / n_q) : 1; + const int top_k = params ? params->top_k : 250; + const float temp = params ? params->temp : 0.8f; + const bool fb_only = gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_CODE && has_codes; + builder = std::make_unique(ctx, img, gen_process, fb_only, n_frames, top_k, temp); + } break; case PROJECTOR_TYPE_CHATTERBOX: { const auto gen_process = params ? params->gen_process : MTMD_SUBCTX_GEN_PROCESS_GEN_CODE; diff --git a/tools/mtmd/mtmd-helper-gen.cpp b/tools/mtmd/mtmd-helper-gen.cpp index 3c33eff3aebd..03ab766d9f8d 100644 --- a/tools/mtmd/mtmd-helper-gen.cpp +++ b/tools/mtmd/mtmd-helper-gen.cpp @@ -5459,6 +5459,141 @@ class voxcpm2_gen_audio_pipeline : public mtmd_gen_audio_pipeline { bool wav_header_sent = false; }; +// Moshi family (e.g. Hibiki): full duplex, the caller drives the backbone with the rows of an audio stream (mtmd_audio_stream) +// per frame: the caller decodes the stream row + h_state_out of the previous step, samples the text token from it, +// then step_gen() turns the text token and the hidden state into the codes of the frame (depformer) and decodes their audio +// h_state_out is the backbone embedding of the generated codes, to be added to the next stream row (zero before the first step) +class moshi_gen_audio_pipeline : public mtmd_gen_audio_pipeline { +public: + using mtmd_gen_audio_pipeline::mtmd_gen_audio_pipeline; + + // the acoustic codes lag the semantic one by this many frames, see "delays" of the checkpoint + static constexpr int acoustic_delay = 2; + + int32_t max_frames() const override { return 0; } + + void reset() override { + n_step = 0; + cb0_hist.clear(); + audio_pcm.clear(); + pcm_sent = 0; + h_state_buf.clear(); + gen_state.reset(); + } + + int32_t set_input(const mtmd_helper_gen_audio_inp * inp) override { + reset(); + if (inp->prompt_len > 0 || inp->speaker_ref) { + LOG_ERR("mtmd_helper_gen_audio: the model answers an audio stream, it takes no prompt or speaker\n"); + return 2; + } + if (!inp->stream || inp->out_type != MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM) { + LOG_ERR("mtmd_helper_gen_audio: the model only streams PCM\n"); + return 2; + } + const mtmd_gen_inp def = mtmd_gen_inp_default(mctx); + temp = inp->temp >= 0.0f ? inp->temp : def.temp; + top_k = def.top_k; + return init_gen_state(inp->seed) ? 0 : 1; + } + + int32_t step_prompt(int32_t n_batch) override { + GGML_UNUSED(n_batch); + return 0; + } + + bool next_is_text() const override { + return true; + } + + int32_t step_gen(llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop) override { + if (out_stop) { + *out_stop = false; + } + mtmd_gen_inp inp = mtmd_gen_inp_default(mctx); + inp.type = MTMD_GEN_PROCESS_TYPE_GEN_CODE; + inp.embd = const_cast(h_state_in); + inp.code0 = sampled; + inp.top_k = top_k; + inp.temp = temp; + mtmd_gen_out out{}; + if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0 || out.n_codes == 0) { + LOG_ERR("mtmd_helper_gen_audio: depformer failed\n"); + return 1; + } + const std::vector codes(out.codes, out.codes + out.n_codes); + const int n_q = (int) codes.size(); + h_state_buf.assign(out.embd, out.embd + n_embd); + + // the next row is position n_step + 1, its acoustic codes are still the initial ones at the start + if (n_step + 1 <= acoustic_delay) { + std::vector fb = codes; + std::fill(fb.begin() + 1, fb.end(), code_initial); + inp.codes = fb.data(); + inp.n_codes = fb.size(); + if (mtmd_gen_audio_process(mctx, gen_state.get(), &inp, &out) != 0) { + LOG_ERR("mtmd_helper_gen_audio: code embedding failed\n"); + return 1; + } + h_state_buf.assign(out.embd, out.embd + n_embd); + } + + // frame f has the semantic code of step f and the acoustic codes of step f + acoustic_delay + cb0_hist.push_back(codes[0]); + if ((int) cb0_hist.size() > acoustic_delay) { + std::vector frame = codes; + frame[0] = cb0_hist.front(); + cb0_hist.erase(cb0_hist.begin()); + + mtmd_gen_inp winp = mtmd_gen_inp_default(mctx); + winp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV; + winp.codes = frame.data(); + winp.n_codes = (size_t) n_q; + mtmd_gen_out wout{}; + if (mtmd_gen_audio_process(mctx, gen_state.get(), &winp, &wout) != 0) { + LOG_ERR("mtmd_helper_gen_audio: mimi decode failed\n"); + return 1; + } + audio_pcm.insert(audio_pcm.end(), wout.audio, wout.audio + wout.n_samples); + } + + n_step++; + *h_state_out = h_state_buf.data(); + return 0; + } + + int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples) override { + *out_sample_rate = info.sample_rate; + // the audio delivered by the previous call is not needed again + audio_pcm.erase(audio_pcm.begin(), audio_pcm.begin() + pcm_sent); + if (out_n_samples) { + *out_n_samples = (int64_t) audio_pcm.size(); + } + *out_data = (const char *) audio_pcm.data(); + *out_data_len = audio_pcm.size() * sizeof(float); + pcm_sent = audio_pcm.size(); + return 0; + } + + // every frame is decoded as soon as its codes are known + int32_t flush() override { + return 0; + } + +private: + // the extra entry after the mimi codebook, see _get_initial_token() of the reference + static constexpr int32_t code_initial = 2048; + + float temp = 0.8f; + int32_t top_k = 250; + + int64_t n_step = 0; + std::vector cb0_hist; // semantic codes waiting for the acoustic codes of their frame + std::vector audio_pcm; + size_t pcm_sent = 0; + std::vector h_state_buf; +}; + static std::unique_ptr make_pipeline(llama_context * lctx, mtmd_context * mctx) { switch (mtmd_gen_audio_get_info(mctx).type) { case MTMD_GEN_AUDIO_TYPE_QWEN3TTS: @@ -5485,6 +5620,8 @@ static std::unique_ptr make_pipeline(llama_context * lc return std::unique_ptr(new music3_gen_audio_pipeline(lctx, mctx)); case MTMD_GEN_AUDIO_TYPE_FISH_S2: return std::unique_ptr(new fish_s2_gen_audio_pipeline(lctx, mctx)); + case MTMD_GEN_AUDIO_TYPE_MOSHI: + return std::unique_ptr(new moshi_gen_audio_pipeline(lctx, mctx)); case MTMD_GEN_AUDIO_TYPE_VOXCPM2: return std::unique_ptr(new voxcpm2_gen_audio_pipeline(lctx, mctx)); default: diff --git a/tools/mtmd/mtmd-helper.cpp b/tools/mtmd/mtmd-helper.cpp index bce73a74e6de..165936d80c1a 100644 --- a/tools/mtmd/mtmd-helper.cpp +++ b/tools/mtmd/mtmd-helper.cpp @@ -1048,6 +1048,7 @@ mtmd_helper_cap mtmd_helper_get_capabilities(const llama_model * model, const mt cap.audio_gen = gen_audio_type != MTMD_GEN_AUDIO_TYPE_NONE; cap.audio_gen_spk_ref = gen_audio_type == MTMD_GEN_AUDIO_TYPE_QWEN3TTS || gen_audio_type == MTMD_GEN_AUDIO_TYPE_POCKETTTS; + cap.audio_duplex = cap.audio_stream && gen_audio_type == MTMD_GEN_AUDIO_TYPE_MOSHI; // a tts model without a chat template only outputs audio, it cannot be used for chat // neither can a realtime transcription model (e.g. Voxtral Realtime): its text follows the audio by a token delay diff --git a/tools/mtmd/mtmd-helper.h b/tools/mtmd/mtmd-helper.h index 3fb75e5a30df..c20cb0a20bbd 100644 --- a/tools/mtmd/mtmd-helper.h +++ b/tools/mtmd/mtmd-helper.h @@ -260,6 +260,7 @@ struct mtmd_helper_cap { // realtime capabilities bool audio_stream; // realtime transcription, see mtmd_audio_stream_init() + bool audio_duplex; // full duplex (e.g. Hibiki): the model speaks while it listens, see the moshi pipeline of mtmd_helper_gen_audio // output capabilities bool text_gen; // false for an audio-only model (tts-only, no chat template) diff --git a/tools/mtmd/mtmd-impl.h b/tools/mtmd/mtmd-impl.h index 582b11365fef..12bc9728da53 100644 --- a/tools/mtmd/mtmd-impl.h +++ b/tools/mtmd/mtmd-impl.h @@ -614,6 +614,8 @@ enum projector_type { PROJECTOR_TYPE_QWEN3TTS_GEN, PROJECTOR_TYPE_POCKETTTS_SPKENC, PROJECTOR_TYPE_POCKETTTS_GEN, + PROJECTOR_TYPE_MOSHI, + PROJECTOR_TYPE_MOSHI_GEN, PROJECTOR_TYPE_SOPRANO, PROJECTOR_TYPE_KOKORO, PROJECTOR_TYPE_TINY_VOCA, @@ -714,6 +716,8 @@ static std::map PROJECTOR_TYPE_NAMES = { { PROJECTOR_TYPE_QWEN3TTS_GEN, "qwen3tts_gen"}, { PROJECTOR_TYPE_POCKETTTS_SPKENC, "pockettts_spkenc"}, { PROJECTOR_TYPE_POCKETTTS_GEN, "pockettts_gen"}, + { PROJECTOR_TYPE_MOSHI, "moshi"}, + { PROJECTOR_TYPE_MOSHI_GEN, "moshi_gen"}, { PROJECTOR_TYPE_SOPRANO, "soprano"}, { PROJECTOR_TYPE_KOKORO, "kokoro"}, { PROJECTOR_TYPE_TINY_VOCA, "tiny_voca"}, diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index 2f4f40591220..570750b9b988 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -1151,6 +1151,20 @@ struct mtmd_model_loader { hparams.flow_n_step = 1; hparams.gen_eos_threshold = -4.0f; } break; + case PROJECTOR_TYPE_MOSHI: + case PROJECTOR_TYPE_MOSHI_GEN: + { + // mimi of the moshi family, see _seanet_kwargs and _transformer_kwargs of the reference + hparams.audio_sample_rate = 24000; + // seanet ratios are [8,6,5,4] in the config, the encoder reverses them + hparams.seanet_ratios = { 4, 5, 6, 8 }; + hparams.seanet_n_stage = (int32_t) hparams.seanet_ratios.size(); + hparams.mimi_downsample = 2; + hparams.mimi_tfm_context = 250; + hparams.rope_theta = 10000.0f; + // one step of the audio stream + hparams.warmup_audio_size = 4 * mtmd_graph_moshi::n_samples_per_frame; + } break; case PROJECTOR_TYPE_VOXCPM2_SPKENC: { // AudioVAE encoder, one backbone row per patch of latents (checked against the strides at load) @@ -1429,6 +1443,7 @@ struct mtmd_model_loader { model.proj_type != PROJECTOR_TYPE_MUSE_SPARK_AUDIO && model.proj_type != PROJECTOR_TYPE_VIBEVOICE_ASR && model.proj_type != PROJECTOR_TYPE_POCKETTTS_SPKENC && + model.proj_type != PROJECTOR_TYPE_MOSHI && model.proj_type != PROJECTOR_TYPE_FISH_S2_SPKENC && model.proj_type != PROJECTOR_TYPE_VOXCPM2_SPKENC; @@ -1527,6 +1542,29 @@ struct mtmd_model_loader { } }; + // mimi decoder: upsample, transformer, SEANet decoder + auto load_mimi_decoder = [&](int n_tfm_layer) { + model.gen_upsample_w = get_tensor(mtmd_format(TN_A_GEN_WAV_UPSAMPLE, "weight")); + load_seanet(model.seanet, true); + model.gen_tfm_layers.resize(n_tfm_layer); + for (int il = 0; il < n_tfm_layer; il++) { + auto & layer = model.gen_tfm_layers[il]; + const char * p = "a.gen.wav.tfm"; + layer.ln_1_w = get_tensor(mtmd_format(TN_LN_1, p, il, "weight")); + layer.ln_1_b = get_tensor(mtmd_format(TN_LN_1, p, il, "bias")); + layer.q_w = get_tensor(mtmd_format(TN_ATTN_Q, p, il, "weight")); + layer.k_w = get_tensor(mtmd_format(TN_ATTN_K, p, il, "weight")); + layer.v_w = get_tensor(mtmd_format(TN_ATTN_V, p, il, "weight")); + layer.o_w = get_tensor(mtmd_format(TN_ATTN_OUTPUT, p, il, "weight")); + layer.ls_1_w = get_tensor(mtmd_format(TN_LS_1, p, il, "weight")); + layer.ln_2_w = get_tensor(mtmd_format(TN_LN_2, p, il, "weight")); + layer.ln_2_b = get_tensor(mtmd_format(TN_LN_2, p, il, "bias")); + layer.ff_up_w = get_tensor(mtmd_format(TN_FFN_UP, p, il, "weight")); + layer.ff_down_w = get_tensor(mtmd_format(TN_FFN_DOWN, p, il, "weight")); + layer.ls_2_w = get_tensor(mtmd_format(TN_LS_2, p, il, "weight")); + } + }; + auto get_vector = [&](const std::string & name) { std::vector result; auto it = tensor_offset.find(name); @@ -2759,25 +2797,7 @@ struct mtmd_model_loader { // mimi decoder model.gen_quant_out_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_OUT, "weight")); - model.gen_upsample_w = get_tensor(mtmd_format(TN_A_GEN_WAV_UPSAMPLE, "weight")); - load_seanet(model.seanet, true); - model.gen_tfm_layers.resize(hparams.n_layer); - for (int il = 0; il < hparams.n_layer; il++) { - auto & layer = model.gen_tfm_layers[il]; - const char * p = "a.gen.wav.tfm"; - layer.ln_1_w = get_tensor(mtmd_format(TN_LN_1, p, il, "weight")); - layer.ln_1_b = get_tensor(mtmd_format(TN_LN_1, p, il, "bias")); - layer.q_w = get_tensor(mtmd_format(TN_ATTN_Q, p, il, "weight")); - layer.k_w = get_tensor(mtmd_format(TN_ATTN_K, p, il, "weight")); - layer.v_w = get_tensor(mtmd_format(TN_ATTN_V, p, il, "weight")); - layer.o_w = get_tensor(mtmd_format(TN_ATTN_OUTPUT, p, il, "weight")); - layer.ls_1_w = get_tensor(mtmd_format(TN_LS_1, p, il, "weight")); - layer.ln_2_w = get_tensor(mtmd_format(TN_LN_2, p, il, "weight")); - layer.ln_2_b = get_tensor(mtmd_format(TN_LN_2, p, il, "bias")); - layer.ff_up_w = get_tensor(mtmd_format(TN_FFN_UP, p, il, "weight")); - layer.ff_down_w = get_tensor(mtmd_format(TN_FFN_DOWN, p, il, "weight")); - layer.ls_2_w = get_tensor(mtmd_format(TN_LS_2, p, il, "weight")); - } + load_mimi_decoder(hparams.n_layer); for (int64_t i = 0; i < gguf_get_n_tensors(ctx_gguf.get()); ++i) { const char * name = gguf_get_tensor_name(ctx_gguf.get(), i); @@ -2799,6 +2819,43 @@ struct mtmd_model_loader { LOG_INF("%s: %zu predefined voices\n", __func__, model.gen_voices.size()); } } break; + case PROJECTOR_TYPE_MOSHI: + { + // streaming mimi encoder, its RVQ, then the backbone embeddings of the input codes + load_seanet(model.seanet, false); + model.downsample_w = get_tensor(mtmd_format(TN_A_DOWNSAMPLE_CONV, "weight")); + auto & c2w = model.c2w; + c2w.quant_first_in_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_FIRST_IN, "weight")); + c2w.quant_first_cb_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_FIRST_CB, "weight")); + c2w.quant_rest_in_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_REST_IN, "weight")); + c2w.quant_rest_cb_w = get_tensor(mtmd_format(TN_A_CODEC_VQ_REST_CB, "weight")); + model.mm_a_code_embd = get_tensor(mtmd_format(TN_MM_A_CODE_EMBD, "weight")); + if (model.mm_a_code_embd->ne[2] != c2w.quant_rest_cb_w->ne[2] + 1) { + throw std::runtime_error(mtmd_format("%s: the input code embeddings do not match the codebooks\n", __func__)); + } + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + // depformer, the generic loop above loaded the a.gen.code.blk.* tensors (per-step weights on dim 2) + model.gen_code_proj_in_w = get_tensor(mtmd_format(TN_A_GEN_CODE_PROJ_IN, "weight")); + model.gen_code_tok_embd_w = get_tensor(mtmd_format(TN_A_GEN_CODE_TOK_EMBD, "weight")); + model.gen_code_embd_w = get_tensor(mtmd_format(TN_A_GEN_CODE_EMBD, "weight")); + model.gen_code_head_w = get_tensor(mtmd_format(TN_A_GEN_CODE_HEAD, "weight")); + model.gen_code_out_embd_w = get_tensor(mtmd_format(TN_A_GEN_CODE_OUT_EMBD, "weight")); + const int64_t n_q = model.gen_code_head_w->ne[2]; + if (model.gen_code_embd_w->ne[2] != n_q - 1 || model.gen_code_out_embd_w->ne[2] != n_q || + model.gen_code_proj_in_w->ne[2] > n_q || (int64_t) n_q > mtmd_graph_moshi_gen::n_q_max) { + throw std::runtime_error(mtmd_format("%s: invalid depformer tensors\n", __func__)); + } + + // RVQ decode, then the mimi decoder + auto & c2w = model.c2w; + c2w.quant_first_out_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_FIRST_OUT, "weight")); + c2w.quant_first_cb_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_FIRST_CB, "weight")); + c2w.quant_rest_out_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_REST_OUT, "weight")); + c2w.quant_rest_cb_w = get_tensor(mtmd_format(TN_A_GEN_WAV_QUANT_REST_CB, "weight")); + load_mimi_decoder(mtmd_graph_moshi_gen::mimi_n_layer); + } break; case PROJECTOR_TYPE_LFM3A_GEN: { // must match the "tts" chat template, see conversion/lfm3.py @@ -5023,6 +5080,16 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { // one latent per call for GEN_CODE, GEN_WAV sizes its input from the caller n_patches = 1; } break; + case PROJECTOR_TYPE_MOSHI: + { + // one row per codebook and frame, then the rows of the initial codes, see mtmd_graph_moshi + const int n_q = (int) mm_a_code_embd->ne[2]; + n_patches = n_q * (img->nx() / mtmd_graph_moshi::n_samples_per_frame + 1); + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + n_patches = 1; + } break; case PROJECTOR_TYPE_GRANITE4_VISION: { // Per-tile output token count: each projector block outputs @@ -5214,6 +5281,10 @@ int mtmd_model::n_mmproj_embd() const { return spk_proj_w->ne[1]; case PROJECTOR_TYPE_POCKETTTS_GEN: return gen_input_lin_w->ne[1]; + case PROJECTOR_TYPE_MOSHI: + return mm_a_code_embd->ne[0]; + case PROJECTOR_TYPE_MOSHI_GEN: + return gen_code_out_embd_w->ne[0]; case PROJECTOR_TYPE_CHATTERBOX: // talker width, carried by the speech table return cbx_tensors.at("a.gen.code.out_embd.weight")->ne[0]; diff --git a/tools/mtmd/mtmd-subcontext.cpp b/tools/mtmd/mtmd-subcontext.cpp index aea0c1b92eda..078f154c7939 100644 --- a/tools/mtmd/mtmd-subcontext.cpp +++ b/tools/mtmd/mtmd-subcontext.cpp @@ -392,6 +392,7 @@ static std::vector list_gen_state_slots(const mtmd_hparams & hpa case PROJECTOR_TYPE_FISH_S2_GEN: return list_c2w_state_slots(hparams, model); case PROJECTOR_TYPE_DRAMA3_GEN: return list_drama3_state_slots(hparams, model); case PROJECTOR_TYPE_POCKETTTS_GEN: return list_pockettts_state_slots(hparams, model); + case PROJECTOR_TYPE_MOSHI_GEN: return list_pockettts_state_slots(hparams, model); case PROJECTOR_TYPE_LFM3A_GEN: return list_lfm3a_gen_state_slots(hparams, model); case PROJECTOR_TYPE_ZONOS3_GEN: return list_zonos3_gen_state_slots(hparams, model); case PROJECTOR_TYPE_VOXCPM2_GEN: return list_voxcpm2_state_slots(hparams, model); @@ -405,6 +406,7 @@ static std::vector list_enc_state_slots(const mtmd_hparams & hpa case PROJECTOR_TYPE_LFM3A: return list_lfm3a_state_slots(hparams, model); case PROJECTOR_TYPE_GEMMA4A: return list_gemma4a_state_slots(hparams, model); case PROJECTOR_TYPE_VIBEVOICE_ASR: return list_vibevoice_asr_state_slots(hparams, model); + case PROJECTOR_TYPE_MOSHI: return list_moshi_state_slots(hparams, model); default: return {}; } } @@ -454,7 +456,8 @@ mtmd_subctx_gen_state * mtmd_subcontext::gen_state_init(uint32_t seed) { mtmd_subctx_enc_state * mtmd_subcontext::enc_state_init(int32_t n_frames_max) { const auto & hparams = model.hparams; - if (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR) { + if (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR || + model.proj_type == PROJECTOR_TYPE_MOSHI) { // see list_enc_state_slots() const auto slots = list_enc_state_slots(hparams, model); auto st = std::make_unique(); @@ -2329,6 +2332,61 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } set_input_f32("pos_emb", pos_emb); } break; + case PROJECTOR_TYPE_MOSHI: + { + // positions and masks are derived in-graph from the "pos" slot + set_enc_state_in(); + } break; + case PROJECTOR_TYPE_MOSHI_GEN: + { + const int64_t n_q = model.gen_code_head_w->ne[2]; + if (params->gen_process == MTMD_SUBCTX_GEN_PROCESS_GEN_WAV) { + GGML_ASSERT(params->codes != nullptr); + // frame-major to codebook-major + const auto & in = *params->codes; + const int64_t n_frames = (int64_t) in.size() / n_q; + const int64_t n_codes = model.c2w.quant_first_cb_w->ne[1]; + std::vector codes(in.size()); + for (int64_t f = 0; f < n_frames; f++) { + for (int64_t k = 0; k < n_q; k++) { + const int32_t c = in[(size_t) (f * n_q + k)]; + if (c < 0 || c >= n_codes) { + LOG_ERR("%s: code out of range (%d, codebook size %lld)\n", __func__, c, (long long) n_codes); + return false; + } + codes[(size_t) (k * n_frames + f)] = c; + } + } + set_input_i32("inp_codes", codes); + set_gen_state_in(); + } else if (params->codes != nullptr) { + std::vector codes = *params->codes; + const int64_t n_rows = model.gen_code_out_embd_w->ne[1]; + for (int32_t c : codes) { + if (c < 0 || c >= n_rows) { + LOG_ERR("%s: code out of range (%d)\n", __func__, c); + return false; + } + } + set_input_i32("inp_codes", codes); + } else { + std::vector code0 = { params->code0 }; + if (code0[0] < 0 || code0[0] >= model.gen_code_tok_embd_w->ne[1]) { + LOG_ERR("%s: text token out of range (%d)\n", __func__, code0[0]); + return false; + } + set_input_i32("inp_code0", code0); + // greedy has no random input + if (ggml_graph_get_tensor(gf, "inp_rand") != nullptr) { + std::uniform_real_distribution dist(0.0f, 1.0f); + std::vector r(n_q); + for (auto & v : r) { + v = dist(params->gen_state->rng); + } + set_input_f32("inp_rand", r); + } + } + } break; case PROJECTOR_TYPE_LFM3A: { GGML_ASSERT(imgs.entries.size() == 1); @@ -2902,7 +2960,8 @@ bool mtmd_subcontext::encode(mtmd_subctx_encode_params * params) { } } } - if (params->enc_state != nullptr && (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR)) { + if (params->enc_state != nullptr && (model.proj_type == PROJECTOR_TYPE_LFM3A || model.proj_type == PROJECTOR_TYPE_GEMMA4A || model.proj_type == PROJECTOR_TYPE_VIBEVOICE_ASR || + model.proj_type == PROJECTOR_TYPE_MOSHI)) { const auto & slots = params->enc_state->slots; size_t i = 0; for (const auto & slot : list_enc_state_slots(hparams, model)) { diff --git a/tools/mtmd/mtmd.cpp b/tools/mtmd/mtmd.cpp index 666f48eeb5bc..fdac762ac98c 100644 --- a/tools/mtmd/mtmd.cpp +++ b/tools/mtmd/mtmd.cpp @@ -1470,6 +1470,7 @@ struct mtmd_context { audio_preproc = std::make_unique(models.a.get()); } break; case PROJECTOR_TYPE_VOXTRAL_RT: + case PROJECTOR_TYPE_MOSHI: { // audio and text share positions, only usable via mtmd_audio_stream } break; @@ -2827,6 +2828,10 @@ mtmd_gen_audio_info mtmd_gen_audio_get_info(const mtmd_context * ctx) { info.type = MTMD_GEN_AUDIO_TYPE_POCKETTTS; info.sample_rate = 24000; break; + case PROJECTOR_TYPE_MOSHI_GEN: + info.type = MTMD_GEN_AUDIO_TYPE_MOSHI; + info.sample_rate = 24000; + break; case PROJECTOR_TYPE_SOPRANO: info.type = MTMD_GEN_AUDIO_TYPE_SOPRANO; info.sample_rate = 32000; @@ -3344,6 +3349,12 @@ mtmd_gen_inp mtmd_gen_inp_default(const mtmd_context * ctx) { case PROJECTOR_TYPE_TINY_VOCA: inp.type = MTMD_GEN_PROCESS_TYPE_GEN_WAV; break; + case PROJECTOR_TYPE_MOSHI_GEN: + // lm_gen_config of the checkpoint (audio codes), the text token is sampled by the caller + inp.top_k = 250; + inp.top_p = 1.0f; + inp.temp = 0.8f; + break; case PROJECTOR_TYPE_VOXCPM2_GEN: // UnifiedCFM.forward(): unit gaussian noise, see VoxCPM2Model._inference() for the steps and the guidance inp.temp = 1.0f; @@ -5485,6 +5496,36 @@ struct mtmd_audio_stream_lfm3a : mtmd_audio_stream { int32_t step_live(llama_token last_token); }; +// Moshi family (e.g. Hibiki): full duplex, one row per 80 ms frame of input audio +// row = embeddings of the input codes (the acoustic ones lag by acoustic_delay frames) + the text token sampled from the previous row +// the codes the model generates are added by the caller, see the moshi pipeline of mtmd_helper_gen_audio +struct mtmd_audio_stream_moshi : mtmd_audio_stream { + static constexpr int acoustic_delay = 2; + static constexpr int n_frames_max = 4; // frames per encoder call + + mtmd_subctx_enc_state * enc_state = nullptr; + + int n_q = 0; + llama_token tok_text_start = LLAMA_TOKEN_NULL; + + std::vector codes_embd; // n_q rows per encoded frame, from frame codes_off + int64_t codes_off = 0; + int64_t n_frames_enc = 0; + std::vector init_embd; // n_q rows of the initial codes + std::vector tok_embd; + + ~mtmd_audio_stream_moshi() override { + delete enc_state; + } + + bool init(const mtmd_audio_stream_params & params) override; + int32_t flush(bool end) override; + int32_t step(llama_token last_token) override; + + bool encode(); + const float * code_row(int64_t frame, int k) const; +}; + // Gemma 4: the encoder is causal struct mtmd_audio_stream_gemma4a : mtmd_audio_stream { mtmd_subctx_enc_state * enc_state = nullptr; @@ -5564,7 +5605,7 @@ bool mtmd_support_audio_stream(const mtmd_context * ctx) { } const projector_type proj = ctx->ctx_a->model.proj_type; return proj == PROJECTOR_TYPE_VOXTRAL_RT || proj == PROJECTOR_TYPE_LFM3A || proj == PROJECTOR_TYPE_GEMMA4A || - proj == PROJECTOR_TYPE_HIGGS_AUDIO || proj == PROJECTOR_TYPE_VIBEVOICE_ASR; + proj == PROJECTOR_TYPE_HIGGS_AUDIO || proj == PROJECTOR_TYPE_VIBEVOICE_ASR || proj == PROJECTOR_TYPE_MOSHI; } mtmd_audio_stream_params mtmd_audio_stream_params_default(void) { @@ -5589,6 +5630,7 @@ mtmd_audio_stream * mtmd_audio_stream_init(mtmd_context * ctx, mtmd_audio_stream case PROJECTOR_TYPE_GEMMA4A: s = std::make_unique(); break; case PROJECTOR_TYPE_HIGGS_AUDIO: s = std::make_unique(); break; case PROJECTOR_TYPE_VIBEVOICE_ASR: s = std::make_unique(); break; + case PROJECTOR_TYPE_MOSHI: s = std::make_unique(); break; default: GGML_ABORT("unsupported projector"); } s->ctx = ctx; @@ -6538,3 +6580,120 @@ int64_t mtmd_audio_stream_get_n_rows(const mtmd_audio_stream * s) { int64_t mtmd_audio_stream_get_n_rows_flushed(const mtmd_audio_stream * s) { return s->n_rows_flushed; } + +// +// Moshi +// + +bool mtmd_audio_stream_moshi::init(const mtmd_audio_stream_params & params) { + if (params.n_prompt > 0) { + LOG_ERR("%s: moshi takes no prompt\n", __func__); + return false; + } + n_q = (int) sctx->model.mm_a_code_embd->ne[2]; + samples_per_tok = mtmd_graph_moshi::n_samples_per_frame; + + const std::string name = "<|text_start|>"; + std::vector toks(4); + if (llama_tokenize(ctx->vocab, name.c_str(), (int32_t) name.size(), toks.data(), (int32_t) toks.size(), false, true) != 1) { + LOG_ERR("%s: cannot find the %s token\n", __func__, name.c_str()); + return false; + } + tok_text_start = toks[0]; + + enc_state = sctx->enc_state_init(0); + return enc_state != nullptr; +} + +int32_t mtmd_audio_stream_moshi::flush(bool end) { + // pad to a whole frame + const int64_t n_align = (samples_per_tok - n_samples % samples_per_tok) % samples_per_tok; + add_silence(n_align); + n_rows_flushed = n_samples / samples_per_tok; + ended = end; + return 0; +} + +// encodes the whole frames of buf, n_frames_max per call +bool mtmd_audio_stream_moshi::encode() { + while (true) { + const int64_t n = std::min((int64_t) buf.size() / samples_per_tok, n_frames_max); + if (n <= 0) { + return true; + } + const size_t n_in = (size_t) (n * samples_per_tok); + + mtmd_image_f32 img; + img.set_size({(int) n_in, 1}, false, /* is_audio */ true); + img.cpy_buf(std::vector(buf.begin(), buf.begin() + n_in)); + mtmd_image_f32_batch batch; + batch.is_audio = true; + batch.entries.push_back(std::move(img)); + + std::vector res((size_t) n_embd * n_q * (n + 1)); + mtmd_subctx_encode_params params; + params.n_threads = ctx->n_threads; + params.imgs = &batch; + params.out_embd = &res; + params.enc_state = enc_state; + if (!sctx->encode(¶ms)) { + LOG_ERR("%s: failed to encode audio\n", __func__); + return false; + } + const size_t n_codes = (size_t) n_embd * n_q * n; + codes_embd.insert(codes_embd.end(), res.begin(), res.begin() + n_codes); + init_embd.assign(res.begin() + n_codes, res.end()); + n_frames_enc += n; + + buf.erase(buf.begin(), buf.begin() + n_in); + buf_pos += (int64_t) n_in; + } +} + +const float * mtmd_audio_stream_moshi::code_row(int64_t frame, int k) const { + return codes_embd.data() + ((size_t) (frame - codes_off) * n_q + k) * n_embd; +} + +int32_t mtmd_audio_stream_moshi::step(llama_token last_token) { + n_rows_done = n_rows; + out.clear(); + + if (!encode()) { + return -2; + } + // row p goes with frame p + if (n_rows >= n_frames_enc) { + return ended ? -1 : 0; + } + const int64_t p = n_rows; + + // the text of the previous row, see _get_initial_token() of the reference + const llama_token tok = p == 0 ? tok_text_start : last_token; + if (tok == LLAMA_TOKEN_NULL) { + LOG_ERR("%s: the token sampled from the previous row is required\n", __func__); + return -2; + } + tok_embd.resize(n_embd); + if (llama_model_get_tok_embd_rows(ctx->text_model, &tok, 1, tok_embd.data()) == 0) { + return -2; + } + + // the semantic code has no delay; a stream starts with initial codes, the first frame is never seen, like the reference + out = tok_embd; + for (int k = 0; k < n_q; k++) { + const int64_t delay = k == 0 ? 0 : acoustic_delay; + const float * row = p <= delay ? init_embd.data() + (size_t) k * n_embd : code_row(p - delay, k); + for (int i = 0; i < n_embd; i++) { + out[i] += row[i]; + } + } + n_rows++; + + // drop the frames no row will need again + const int64_t keep_from = std::max(0, n_rows - acoustic_delay); + if (keep_from - codes_off >= 64) { + codes_embd.erase(codes_embd.begin(), codes_embd.begin() + (size_t) (keep_from - codes_off) * n_q * n_embd); + codes_off = keep_from; + } + return 1; +} diff --git a/tools/mtmd/mtmd.h b/tools/mtmd/mtmd.h index cf2d14ce2564..09cae0ad836b 100644 --- a/tools/mtmd/mtmd.h +++ b/tools/mtmd/mtmd.h @@ -478,6 +478,7 @@ enum mtmd_gen_audio_type { MTMD_GEN_AUDIO_TYPE_YUE2, MTMD_GEN_AUDIO_TYPE_MINIMAX_MUSIC3, MTMD_GEN_AUDIO_TYPE_FISH_S2, + MTMD_GEN_AUDIO_TYPE_MOSHI, MTMD_GEN_AUDIO_TYPE_KOKORO, MTMD_GEN_AUDIO_TYPE_TINY_VOCA, MTMD_GEN_AUDIO_TYPE_VOXCPM2, @@ -534,6 +535,7 @@ struct mtmd_gen_inp { // for MTMD_GEN_PROCESS_TYPE_GEN_WAV // pass either codes (discrete) or feats (continuous), depending on the pipeline // lfm3a GEN_CODE also takes codes: the codes revealed so far, -1 for a masked codebook + // moshi GEN_CODE: code0 is the sampled text token; with codes (all of the frame), only their backbone embedding is built // zonos3 GEN_WAV: -1 for a residual code not known yet, the frame is decoded without it // kokoro GEN_WAV takes both: codes are the phoneme tokens, feats is the voice row (256 values) then the backbone state of each token int32_t * codes; diff --git a/tools/server/README.md b/tools/server/README.md index 1f6553389d61..b0168b6d14dc 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -1667,6 +1667,12 @@ LFM3-Omni is not trained to reason, run it with `--reasoning off` so that its tu Tools go into the system prompt with the chat template, and the tool calls are parsed as in `/v1/chat/completions`. The client runs the calls of a response, sends their results as `function_call_output` items, then asks for the next response. +#### Full duplex + +Full duplex models, like Hibiki (French to English speech translation), speak while they listen on the same endpoint. There are no turns: the first `input_audio_buffer.append` opens a response, then every 80 ms of input audio gives 80 ms of output audio (`response.output_audio.delta`) and the text of the translation (`response.output_text.delta`). `response.cancel` ends the response with `response.done`, the next audio opens another one. Audio input and output are PCM16 mono, as for a realtime conversation. + +The model attends to the last 120 s of the stream, so the context of each slot only needs to hold that window (1500 frames for Hibiki, `-c` divided by `-np`). The model is trained on streams no longer than its window, so once the window is full the first frames of the stream stay in context and the oldest frames after them are dropped, 20 s at a time. This keeps Hibiki-1B going on long streams; Hibiki-2B still degrades after about 2 minutes, as the reference implementation does, cancel the response between long segments of speech. `input_audio_buffer.commit`, `conversation.item.create` and `response.create` are rejected. The text and the audio are sampled with the settings of the model, the text settings can be overridden with the server sampling options. + ### POST `/v1/audio/speech`: OpenAI-compatible Speech API Generates speech from text, for models that can generate audio. The request is converted to a [`/tts`](#post-tts-generate-speech-audio-from-text) request, so the `/tts` options such as `lang`, `seed` or `speaker_ref_b64` can also be used. diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index bfade25d7c92..e37661a9a87a 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -6132,7 +6132,7 @@ void server_routes::init_routes() { // models that answer after the audio hold a conversation, see server-realtime.h // live transcription: Voxtral Realtime (no chat), or an "asr" model in a session opened with ?intent=transcription const bool live_asr = !ctx_server.asr_prompt.empty() && req.get_param("intent") == "transcription"; - if (ctx_server.mtmd_cap.audio_stream && ctx_server.mtmd_cap.chat && !live_asr) { + if (ctx_server.mtmd_cap.audio_duplex || (ctx_server.mtmd_cap.audio_stream && ctx_server.mtmd_cap.chat && !live_asr)) { server_realtime_conversation({queue_tasks, queue_results, *meta, params, ctx_server.mctx, ctx_server.mtmd_cap, ctx_server.vocab}, conn); return; } diff --git a/tools/server/server-realtime.cpp b/tools/server/server-realtime.cpp index 6f08120dd140..b379fa203d84 100644 --- a/tools/server/server-realtime.cpp +++ b/tools/server/server-realtime.cpp @@ -13,7 +13,9 @@ #include #include +#include #include +#include #include #include #include @@ -180,8 +182,14 @@ struct realtime_conversation { std::atomic closed{false}; + // full duplex: no turns, the first audio opens a response that runs until response.cancel + const bool duplex; + bool duplex_open = false; // guarded by mutex + std::condition_variable duplex_done; // the cancelled response is done + realtime_conversation(const server_realtime_deps & deps, server_http_context::ws_conn & conn) - : deps(deps), conn(conn), out_language(deps.params.tts_lang), out_voice(deps.params.tts_voice) {} + : deps(deps), conn(conn), out_language(deps.params.tts_lang), out_voice(deps.params.tts_voice), + duplex(deps.cap.audio_duplex) {} // // events @@ -395,6 +403,23 @@ struct realtime_conversation { if (samples.empty()) { return; } + if (duplex) { + if (!resample(samples) || samples.empty()) { + return; + } + bool open = false; + { + std::lock_guard lock(mutex); + open = !duplex_open; + duplex_open = true; + } + if (open) { + started = true; + open_response(MTMD_HELPER_GEN_AUDIO_OUT_MIXED); + } + control(SERVER_CONTROL_ACTION_AUDIO_APPEND, {}, std::move(samples)); + return; + } if (!resample(samples) || samples.empty() || !ensure_turn()) { return; } @@ -449,6 +474,10 @@ struct realtime_conversation { } void on_commit() { + if (duplex) { + send_error("input_audio_buffer.commit: the model answers while it listens, there is no turn to commit"); + return; + } const int64_t n_audio = n_turn_samples; if (!commit() || type != "transcription") { return; @@ -480,6 +509,10 @@ struct realtime_conversation { } void on_item_create(const json & ev) { + if (duplex) { + send_error("conversation.item.create: the model only takes audio"); + return; + } if (type == "transcription") { send_error("conversation.item.create: not supported in a transcription session"); return; @@ -537,6 +570,10 @@ struct realtime_conversation { } void on_response_create(const json & ev) { + if (duplex) { + send_error("response.create: the model answers while it listens, its response opens with the first audio"); + return; + } if (type == "transcription") { send_error("response.create: not supported in a transcription session"); return; @@ -606,24 +643,7 @@ struct realtime_conversation { } response.sampling = response_sampling(chat ? &*chat : nullptr); - { - std::lock_guard lock(mutex); - response_id = "resp_" + random_string(); - response_item_id = "item_" + random_string(); - response_text.clear(); - parts = json::array(); - idx_text = -1; - idx_audio = -1; - output = json::array(); - idx_message = -1; - call_items.clear(); - parse.reset(); - if (chat) { - parse.emplace(std::move(*chat)); - } - send_event({{"type", "response.created"}, {"response", {{"id", response_id}, {"object", "realtime.response"}, - {"status", "in_progress"}, {"output_modalities", output_modalities_json(mode)}, {"output", json::array()}}}}); - } + open_response(mode, chat ? &*chat : nullptr); if (!control(SERVER_CONTROL_ACTION_RESPONSE_CREATE, prompt, {}, response)) { return; } @@ -634,6 +654,26 @@ struct realtime_conversation { n_turns++; } + // the results that follow belong to a new response + void open_response(mtmd_helper_gen_audio_out_mode mode, common_chat_session * chat = nullptr) { + std::lock_guard lock(mutex); + response_id = "resp_" + random_string(); + response_item_id = "item_" + random_string(); + response_text.clear(); + parts = json::array(); + idx_text = -1; + idx_audio = -1; + output = json::array(); + idx_message = -1; + call_items.clear(); + parse.reset(); + if (chat) { + parse.emplace(std::move(*chat)); + } + send_event({{"type", "response.created"}, {"response", {{"id", response_id}, {"object", "realtime.response"}, + {"status", "in_progress"}, {"output_modalities", output_modalities_json(mode)}, {"output", json::array()}}}}); + } + void on_session_update(const json & ev) { const json session = ev.value("session", json::object()); if (!session.is_object()) { @@ -646,6 +686,10 @@ struct realtime_conversation { send_error("session.update: unknown session type " + t); return; } + if (duplex) { + send_error("session.update: the model only holds \"realtime\" sessions"); + return; + } if (started) { send_error("session.update: the session type cannot change after the first audio or message"); return; @@ -726,7 +770,7 @@ struct realtime_conversation { out_voice = voice; out_language = lang; } - if (!started && !configure()) { + if (!duplex && !started && !configure()) { send_error("the chat template does not fit the realtime turn format", "server_error"); return; } @@ -774,6 +818,11 @@ struct realtime_conversation { on_response_create(ev); } else if (t == "response.cancel") { control(SERVER_CONTROL_ACTION_RESPONSE_CANCEL); + if (duplex) { + // the next audio opens another response, once the results of this one are out + std::unique_lock lock(mutex); + duplex_done.wait_for(lock, std::chrono::seconds(10), [this]() { return !duplex_open || closed.load(); }); + } } else { send_error("unknown event type: " + t); } @@ -918,6 +967,8 @@ struct realtime_conversation { send_event({{"type", "response.done"}, {"response", {{"id", response_id}, {"object", "realtime.response"}, {"status", status}, {"output", output}, {"usage", {{"output_tokens", res.n_decoded}}}}}}); parse.reset(); + duplex_open = false; + duplex_done.notify_all(); } // @@ -929,7 +980,7 @@ struct realtime_conversation { if (deps.cap.audio_gen) { output_rate = mtmd_gen_audio_get_info(deps.mctx).sample_rate; } - if (!configure()) { + if (!duplex && !configure()) { send_error("the chat template does not fit the realtime turn format", "server_error"); conn.close(); return; @@ -1015,6 +1066,7 @@ server_realtime_slot::server_realtime_slot(llama_context * ctx, mtmd_context * m if (mtmd_gen_audio_get_info(mctx).type != MTMD_GEN_AUDIO_TYPE_NONE) { gen.init(ctx, mctx); } + duplex = mtmd_helper_get_capabilities(model, mctx).audio_duplex; } void server_realtime_slot::push(server_realtime_op && op) { @@ -1022,10 +1074,19 @@ void server_realtime_slot::push(server_realtime_op && op) { } void server_realtime_slot::cancel() { + if (duplex) { + // in order with the audio: the response of a full duplex model may still be opening + ops.push_back({SERVER_CONTROL_ACTION_RESPONSE_CANCEL, {}, {}, {}}); + return; + } cancelled = responding; } bool server_realtime_slot::is_idle() const { + if (duplex) { + // a full duplex response waits for the next audio + return ops.empty() && !(responding && duplex_pending); + } return ops.empty() && !responding; } @@ -1051,7 +1112,8 @@ void server_realtime_slot::send_result(common_chat_input content, std::vector= n_ctx) { + // a full duplex model attends to a sliding window, its stream has no end + if (!duplex && n_past + n >= n_ctx) { return fail("the conversation does not fit in the context", ERROR_TYPE_EXCEED_CONTEXT_SIZE); } common_batch batch(ctx); @@ -1220,16 +1282,149 @@ bool server_realtime_slot::response_step() { // the pipeline decoded the response, the sequence ends where it stopped n_past = llama_memory_seq_pos_max(llama_get_memory(ctx), seq_id) + 1; } - send_result({}, {}, true); - responding = false; - cancelled = false; + response_end(); + } + return true; +} + +void server_realtime_slot::response_end() { + send_result({}, {}, true); + responding = false; + cancelled = false; +} + +// +// full duplex (e.g. Hibiki): one row per frame of input audio, the model speaks while it listens +// row = the stream row (input audio + previous text token) + the embedding of the audio generated at the previous frame +// + +bool server_realtime_slot::duplex_start() { + // the cells past the window are reused, the window itself must fit + const int32_t n_swa = llama_model_n_swa(model); + if (n_ctx < n_swa) { + return fail("the context of a slot (" + std::to_string(n_ctx) + ") must hold the attention window of the model (" + + std::to_string(n_swa) + "), see -c and -np"); + } + stream.reset(mtmd_audio_stream_init(mctx, mtmd_audio_stream_params_default())); + if (!stream) { + return fail("failed to initialize the audio stream"); + } + mtmd_helper::gen_audio::inp inp; + inp.data.seq_id = seq_id; + inp.data.seed = sampling.seed; + inp.data.stream = true; + inp.data.out_type = MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM; + if (gen.set_input(inp.get()) != 0 || gen.step_prompt(llama_n_batch(ctx)) != 0) { + return fail("failed to start the response"); + } + llama_memory_seq_rm(llama_get_memory(ctx), seq_id, -1, -1); + n_past = 0; + n_decoded = 0; + sampled = LLAMA_TOKEN_NULL; + h_state.assign(llama_model_n_embd_inp(model), 0.0f); + smpl.reset(common_sampler_init(model, sampling)); + responding = true; + cancelled = false; + return true; +} + +bool server_realtime_slot::duplex_frame() { + const int32_t n = mtmd_audio_stream_step(stream.get(), sampled); + if (n == -2) { + return fail("audio stream error"); + } + if (n <= 0) { + duplex_pending = false; + return true; + } + GGML_ASSERT(n == 1); + + // the model was trained on streams no longer than its window, so it always saw their start (it acts as an attention sink) + // once the window is full: the first rows stay, the oldest rows after them go and the rest shifts back, like StreamingLLM + llama_memory_t mem = llama_get_memory(ctx); + const int32_t n_swa = llama_model_n_swa(model); + if (n_swa > 0 && n_past >= n_swa && llama_memory_can_shift(mem)) { + const int32_t n_discard = n_swa / duplex_discard_div; + llama_memory_seq_rm (mem, seq_id, duplex_n_keep, duplex_n_keep + n_discard); + llama_memory_seq_add(mem, seq_id, duplex_n_keep + n_discard, -1, -n_discard); + n_past -= n_discard; + } + + const float * row = mtmd_audio_stream_get_output_embd(stream.get()); + std::vector inp(row, row + h_state.size()); + for (size_t i = 0; i < inp.size(); i++) { + inp[i] += h_state[i]; + } + if (!decode(nullptr, inp.data(), 1, true)) { + return false; + } + sampled = common_sampler_sample(smpl.get(), ctx, -1); + common_sampler_accept(smpl.get(), sampled, true); + + // copy the hidden state before any other slot decodes + const float * h = llama_get_embeddings_ith(ctx, -1); + std::vector h_cur(h, h + llama_model_n_embd(model)); + const float * fb = nullptr; + if (gen.step_gen(sampled, h_cur.data(), &fb) != 0 || fb == nullptr) { + return fail("response generation failed"); + } + h_state.assign(fb, fb + h_state.size()); + n_decoded++; + + common_chat_input content; + content.append(piece(sampled), sampled); + std::vector audio; + int32_t sample_rate = 0; + const char * data = nullptr; + size_t data_len = 0; + if (gen.get_output(&sample_rate, &data, &data_len) == 0 && data_len > 0) { + audio.assign((const float *) data, (const float *) data + data_len / sizeof(float)); + } + if (!content.empty() || !audio.empty()) { + send_result(std::move(content), std::move(audio)); } return true; } +bool server_realtime_slot::duplex_update() { + while (!ops.empty()) { + server_realtime_op op = std::move(ops.front()); + ops.pop_front(); + switch (op.action) { + case SERVER_CONTROL_ACTION_AUDIO_APPEND: + { + // the first audio opens the response + if (!responding && !duplex_start()) { + return false; + } + mtmd_audio_stream_push(stream.get(), op.audio.data(), op.audio.size()); + duplex_pending = true; + } break; + case SERVER_CONTROL_ACTION_RESPONSE_CANCEL: + { + // the audio after it opens another response + if (responding) { + stream.reset(); + gen.reset(); + duplex_pending = false; + cancelled = true; + response_end(); + } + } break; + default: + break; + } + } + return !responding || !duplex_pending || duplex_frame(); +} + bool server_realtime_slot::update() { llama_set_embeddings(ctx, gen.valid()); + if (duplex) { + return duplex_update(); + } + if (responding) { return response_step(); } diff --git a/tools/server/server-realtime.h b/tools/server/server-realtime.h index 93c864df22d8..cb0efa93975b 100644 --- a/tools/server/server-realtime.h +++ b/tools/server/server-realtime.h @@ -32,6 +32,7 @@ struct server_realtime_deps { // a realtime conversation over websocket, for models that answer after the audio (e.g. LFM3-Audio): // the audio is prefilled as it arrives, responses follow output_modalities or the model's own switching +// full duplex models (e.g. Hibiki) answer while they listen: the first audio opens a response that runs until it is cancelled void server_realtime_conversation(const server_realtime_deps & deps, server_http_context::ws_conn & conn); // one control of a realtime conversation @@ -80,12 +81,19 @@ struct server_realtime_slot { int32_t n_decoded = 0; llama_token sampled = LLAMA_TOKEN_NULL; // next text token of the response, sampled right after the slot's own decode - mtmd::audio_stream_ptr stream; // the audio of the open turn + mtmd::audio_stream_ptr stream; // the audio of the open turn, or of the whole response of a full duplex model mtmd_helper::gen_audio gen; // set if the model generates audio std::vector h_state; // hidden state that the gen-audio pipeline steps from common_sampler_ptr smpl; std::set preserved; // special tokens of the response that go out as text (tool calls) + // full duplex: one frame per update(), h_state holds the embedding of the generated audio for the next row + bool duplex = false; + bool duplex_pending = false; // the stream may have a row ready + // past the attention window: the first rows of the stream stay, 1/duplex_discard_div of the window goes at once + static constexpr int32_t duplex_n_keep = 3; + static constexpr int32_t duplex_discard_div = 6; + bool fail(const std::string & msg, enum error_type type = ERROR_TYPE_SERVER); void send_result(common_chat_input content, std::vector audio, bool response_done = false); bool decode(const llama_token * tokens, const float * rows, int32_t n, bool logits_last); @@ -94,4 +102,9 @@ struct server_realtime_slot { std::string piece(llama_token tok) const; bool response_start(const server_realtime_op & op); bool response_step(); + void response_end(); + + bool duplex_update(); + bool duplex_start(); + bool duplex_frame(); }; From 660be5506b15eae512f0df3ae0cc168712555319 Mon Sep 17 00:00:00 2001 From: "Kazutoshi, Akao" <73567414+kazutoshi-ak@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:16:40 +0900 Subject: [PATCH 025/401] ggml : improvements to the memory access pattern in `ggml_compute_forward_mul_mat_one_chunk` (#30846) --- ggml/src/ggml-cpu/ggml-cpu.c | 38 ++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 4d9760bad5b1..33193a5affa1 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -1169,6 +1169,28 @@ void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, //////////////////////////////////////////////////////////////////////////////// +static inline void ggml_deinterleave_f32( + float * GGML_RESTRICT dst0, + float * GGML_RESTRICT dst1, + const float * GGML_RESTRICT src, + int64_t n, + size_t bs, + int nrc) { + GGML_ASSERT(nrc >= 1 && nrc <= 2); + + if (nrc == 1) { + memcpy(dst0, src, n * sizeof(float)); + return; + } + + for (int64_t i = 0; i < n; ++i) { + dst0[i ] = src[2*i + 0 ]; + dst1[i ] = src[2*i + 1 ]; + dst0[bs + i] = src[2*i + 0 + 16]; + dst1[bs + i] = src[2*i + 1 + 16]; + } +} + // ggml_compute_forward_mul_mat static void ggml_compute_forward_mul_mat_one_chunk( @@ -1218,8 +1240,12 @@ static void ggml_compute_forward_mul_mat_one_chunk( // 16 * 2, accounting for mmla kernels float tmp[32]; + const int64_t nr0_split = (ir0_end - ir0_start) / num_rows_per_vec_dot; // rows per stream + const int64_t ir0_end_split = ir0_start + nr0_split; + const int64_t blck_0_split = blck_0 / num_rows_per_vec_dot; + for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) { - for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) { + for (int64_t iir0 = ir0_start; iir0 < ir0_end_split; iir0 += blck_0_split) { for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ir1 += num_rows_per_vec_dot) { const int64_t i13 = (ir1 / (ne12 * ne1)); const int64_t i12 = (ir1 - i13 * ne12 * ne1) / ne1; @@ -1249,13 +1275,13 @@ static void ggml_compute_forward_mul_mat_one_chunk( // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col); //} - for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ir0 += num_rows_per_vec_dot) { - vec_dot(ne00, &tmp[ir0 - iir0], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot); + for (int64_t ir0 = iir0; ir0 < iir0 + blck_0_split && ir0 < ir0_end_split; ++ir0) { + vec_dot(ne00, &tmp[(ir0 - iir0) * num_rows_per_vec_dot], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 * nr0_split : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot); } - for (int cn = 0; cn < num_rows_per_vec_dot; ++cn) { - memcpy(&dst_col[iir0 + cn * nb1 / nb0], tmp + (cn * 16), (MIN(iir0 + blck_0, ir0_end) - iir0) * sizeof(float)); - } + const int64_t n = MIN(iir0 + blck_0_split, ir0_end_split) - iir0; + float * dst0 = dst_col + iir0; + ggml_deinterleave_f32(dst0, dst0 + nr0_split, tmp, n, nb1 / nb0, num_rows_per_vec_dot); } } } From e50c254a22c590c9d2a60db86690d48d42497e2b Mon Sep 17 00:00:00 2001 From: Frosty40 Date: Sat, 21 Nov 2026 08:20:29 -0600 Subject: [PATCH 026/401] sycl: bound CONV_TRANSPOSE_1D input iteration (#31109) Used angelX to optimize SYCL/drama 3 coordination, results are as follows Each output reads only inputs with i*s0 <= idx < i*s0 + K, in the same ascending order as before. Arc Pro B70, oneAPI 2026.1, test-backend-ops perf, base 9b56ccf00 vs patch, median of 3 same-boot A/B/A rounds, A/A 1.000-1.001: | input [ne0, ne1] | kernel [K, OC, IC] | s0 | base us | patch us | speedup | |---|---|---|---|---|---| | [16, 1536] | [16, 768, 1536] | 8 | 3910.57 | 1348.59 | 2.90x | | [128, 768] | [16, 384, 768] | 8 | 37735.00 | 1665.26 | 22.66x | | [1024, 384] | [8, 192, 384] | 4 | 270371.75 | 1471.74 | 183.71x | | [4096, 192] | [4, 96, 192] | 2 | 534614.63 | 752.74 | 710.23x | Shapes are the drama 3 codec decoder upsampling stack, added as perf cases. Chained 4-layer stack at 1/4/24 input frames: base 66.3/847.4/28638.5 ms, patch 2.3/6.7/30.7 ms. Kernel numbers, not end-to-end TTS latency. Correctness: test-backend-ops -o CONV_TRANSPOSE_1D 116/116 on base and patch, and 116/116 rebased on 3f03b1772. Seeded output dump (7.46 MB) byte-identical to base. Full test-backend-ops aborts on base and patch alike at the non-F32 SWIGLU_OAI assert (element_wise.cpp:1187, see #30857). With only those cases excluded: 20145/20173 on base and patch, and every patch-run failure also fails on base. Co-authored-by: Titaniumtown --- ggml/src/ggml-sycl/conv.cpp | 13 +++++++------ tests/test-backend-ops.cpp | 6 ++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-sycl/conv.cpp b/ggml/src/ggml-sycl/conv.cpp index 475bd34a25d5..5f15c25a2e01 100644 --- a/ggml/src/ggml-sycl/conv.cpp +++ b/ggml/src/ggml-sycl/conv.cpp @@ -28,16 +28,17 @@ static void conv_transpose_1d_kernel( float accumulator = 0; - for (int c = 0; c < src0_ne2; c++) { - int idx = global_index % dst_ne0; + const int idx = global_index % dst_ne0; + + // only inputs with i*s0 <= idx < i*s0 + src0_ne0 contribute + const int i_begin = idx >= src0_ne0 ? (idx - src0_ne0) / s0 + 1 : 0; + const int i_end = sycl::min(src1_ne0, idx / s0 + 1); + for (int c = 0; c < src0_ne2; c++) { int kernel_offset = (src0_ne0 * src0_ne1 * c) + (out_index * src0_ne0); int input_offset = src1_ne0 * c; - for (int i = 0; i < src1_ne0; i++) { - if (!(idx >= i*s0 && idx < i*s0 + src0_ne0)) { - continue; - } + for (int i = i_begin; i < i_end; i++) { int weight_idx = idx - i*s0; float kernel_weight = src0[kernel_offset + weight_idx]; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index a0d3349e65de..e377277a485b 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -14349,6 +14349,12 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {200000, 1, 1, 1})); test_cases.emplace_back(new test_argsort(GGML_TYPE_F32, {200000, 16, 1, 1})); + // Independent perf cases using upsampling layer shapes from the Drama 3 audio codec decoder. + test_cases.emplace_back(new test_conv_transpose_1d({16, 1536, 1, 1}, {16, 768, 1536, 1}, 8, 0, 1)); + test_cases.emplace_back(new test_conv_transpose_1d({128, 768, 1, 1}, {16, 384, 768, 1}, 8, 0, 1)); + test_cases.emplace_back(new test_conv_transpose_1d({1024, 384, 1, 1}, {8, 192, 384, 1}, 4, 0, 1)); + test_cases.emplace_back(new test_conv_transpose_1d({4096, 192, 1, 1}, {4, 96, 192, 1}, 2, 0, 1)); + test_cases.emplace_back(new test_top_k(GGML_TYPE_F32, {2, 1, 1, 1}, 1)); // widths around the tiling threshold for (auto cols : {4096, 8192, 12288, 16384, 24576, 32768, 65536, 131072}) { From 19bc41dbb41e858eebc269b49ccdec1f0d28880c Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Sat, 21 Nov 2026 16:30:01 +0100 Subject: [PATCH 027/401] model: apply .scale tensors automatically + fix correctness (#32669) * model: apply .scale tensors automatically * rm build_moe_ffn "_s" overload * use llama_prec_policy * fix ci * build_lora_mm_id: rm w_s --- ggml/src/ggml-backend-meta.cpp | 42 ++++++----- src/llama-graph.cpp | 134 ++++++--------------------------- src/llama-graph.h | 8 +- src/llama-model.cpp | 56 +++++++++++++- src/llama-model.h | 14 +++- src/models/clover-moe.cpp | 5 +- src/models/cohere2moe.cpp | 10 +-- src/models/deepseek32.cpp | 10 +-- src/models/deepseek4.cpp | 3 - src/models/deepseek41.cpp | 4 +- src/models/dots3note.cpp | 5 +- src/models/flint.cpp | 5 +- src/models/gemma4.cpp | 5 +- src/models/glm-dsa.cpp | 10 +-- src/models/glm4-moe.cpp | 5 ++ src/models/glm4.cpp | 4 + src/models/granite-hybrid.cpp | 6 +- src/models/granite-swa.cpp | 5 +- src/models/granite.cpp | 6 +- src/models/hy-v3.cpp | 10 +-- src/models/inkling2.cpp | 7 +- src/models/jais2.cpp | 4 + src/models/kolibri1.cpp | 2 +- src/models/lfm-base.cpp | 7 +- src/models/llama.cpp | 6 +- src/models/mellum.cpp | 12 +-- src/models/metis16.cpp | 2 +- src/models/minimax-m3.cpp | 5 +- src/models/mistral-large4.cpp | 5 +- src/models/mistral3.cpp | 6 +- src/models/muse-spark.cpp | 2 +- src/models/nemotron-h-moe.cpp | 5 +- src/models/nemotron-h.cpp | 5 +- src/models/qwen35moe.cpp | 10 +-- src/models/qwen3moe.cpp | 6 +- src/models/qwen3next.cpp | 10 +-- src/models/qwen4exp.cpp | 5 +- src/models/zaya1.cpp | 3 - tests/fusion/MTL.csv | 5 +- 39 files changed, 164 insertions(+), 290 deletions(-) diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 595a5824aafe..c4e37ed4692a 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -2154,8 +2154,28 @@ static enum ggml_status ggml_backend_meta_graph_compute(ggml_backend_t backend, } }; - skip_unrelated(); - if (id + 1 >= cgraph->n_nodes) { + // Chain of MULs with MIRRORED src[1], returns false at the end of the graph + auto absorb_muls = [&]() -> bool { + while (true) { + skip_unrelated(); + if (id + 1 >= cgraph->n_nodes) { + return false; + } + ggml_tensor * next = cgraph->nodes[id+1]; + if (next->op == GGML_OP_MUL && next->src[0] == node && + ggml_backend_meta_get_split_state(next->src[1], false).axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) { + node = next; + id++; + idr = id; + n_used = ggml_node_get_use_count(cgraph, id); + } else { + return true; + } + } + }; + + // MULs before the PARTIAL bias (e.g. a per-expert weight scale): sum_j(s*p_j + b/n) == s*sum_j(p_j) + b + if (!absorb_muls()) { return idr; } { @@ -2169,22 +2189,8 @@ static enum ggml_status ggml_backend_meta_graph_compute(ggml_backend_t backend, n_used = ggml_node_get_use_count(cgraph, id); } } - // Chain of MULs with MIRRORED src[1] - while (true) { - skip_unrelated(); - if (id + 1 >= cgraph->n_nodes) { - return idr; - } - ggml_tensor * next = cgraph->nodes[id+1]; - if (next->op == GGML_OP_MUL && next->src[0] == node && - ggml_backend_meta_get_split_state(next->src[1], false).axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) { - node = next; - id++; - idr = id; - n_used = ggml_node_get_use_count(cgraph, id); - } else { - break; - } + if (!absorb_muls()) { + return idr; } if (n_used != node->ne[1] || id + 2*n_used-1 >= cgraph->n_nodes) { diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index c5c9ddf014b9..1bd3f8d0f85e 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1810,16 +1810,21 @@ ggml_tensor * llm_graph_context::build_lora_mm( ggml_tensor * w, ggml_tensor * cur, ggml_tensor * w_s) const { + if (!w_s) { + w_s = model.get_w_scale(w); + } + // a Hadamard-folded weight reads the transformed input; a LoRA delta lives in the primal basis and reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); ggml_tensor * res = ggml_mul_mat(ctx0, w, cur_mm); - prec_policy.apply(res); - if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); } + + prec_policy.apply(res); + if (w_s) { res = ggml_mul(ctx0, res, w_s); } @@ -1886,9 +1891,10 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_tensor * w, // ggml_tensor * as ggml_tensor * cur, // ggml_tensor * b ggml_tensor * ids, - ggml_tensor * w_s, ggml_tensor * slots, bool cached) const { + ggml_tensor * w_s = model.get_w_scale(w); + // as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); // the experts in the MoE cache are selected by their slots @@ -1896,12 +1902,13 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_mul_mat_id(ctx0, w, cur_mm, ids) : ggml_mul_mat_id(ctx0, cached ? moe_cache->get_experts(w) : w, cur_mm, slots); - prec_policy.apply(res); - if (w->type == GGML_TYPE_NVFP4) { ggml_prec_set_acc(res, GGML_PREC_BF16); } + // after the NVFP4 default, so that the policy can request a higher precision + prec_policy.apply(res); + if (w_s) { const int64_t n_expert = w_s->ne[0]; const int64_t n_tokens = cur->ne[2]; @@ -2115,34 +2122,7 @@ ggml_tensor * llm_graph_context::build_ffn( int il) const { const llm_arch arch = model.arch; - // NVFP4 support is currently restricted to - // 1) LORA absence (*_s would be applied after LORA residual, which is incorrect) - // 2) bias absense (*_s would be applied after bias addition, which is incorrect) - // TODO: disambiguate LLM-architectural scales (which use *_s) from NVFP4 scale_2 (which also uses *_s currently) - auto has_lora = [this](ggml_tensor * w) { - if (!w) { - return false; - } - for (const auto & lora : *loras) { - if (lora.first->get_weight(w) != nullptr) { - return true; - } - } - return false; - }; - - auto is_scaled_low_precision = [](ggml_tensor * w) { - return w && (w->type == GGML_TYPE_NVFP4 || w->type == GGML_TYPE_F8_E4M3); - }; - - GGML_ASSERT(!up_s || !up_b || !is_scaled_low_precision(up)); - GGML_ASSERT(!gate_s || !gate_b || !is_scaled_low_precision(gate)); - GGML_ASSERT(!down_s || !down_b || !is_scaled_low_precision(down)); - GGML_ASSERT(!up_s || !is_scaled_low_precision(up) || !has_lora(up)); - GGML_ASSERT(!gate_s || !is_scaled_low_precision(gate) || !has_lora(gate)); - GGML_ASSERT(!down_s || !is_scaled_low_precision(down) || !has_lora(down)); - - ggml_tensor * tmp = up ? build_lora_mm(up, cur) : cur; + ggml_tensor * tmp = up ? build_lora_mm(up, cur, up_s) : cur; cb(tmp, "ffn_up", il); if (up_b) { @@ -2150,21 +2130,16 @@ ggml_tensor * llm_graph_context::build_ffn( cb(tmp, "ffn_up_b", il); } - if (up_s) { - tmp = ggml_mul(ctx0, tmp, up_s); - cb(tmp, "ffn_up_s", il); - } - if (gate) { switch (type_gate) { case LLM_FFN_SEQ: { - cur = build_lora_mm(gate, tmp); + cur = build_lora_mm(gate, tmp, gate_s); cb(cur, "ffn_gate", il); } break; case LLM_FFN_PAR: { - cur = build_lora_mm(gate, cur); + cur = build_lora_mm(gate, cur, gate_s); cb(cur, "ffn_gate", il); } break; } @@ -2174,11 +2149,6 @@ ggml_tensor * llm_graph_context::build_ffn( cb(cur, "ffn_gate_b", il); } - if (gate_s) { - cur = ggml_mul(ctx0, cur, gate_s); - cb(cur, "ffn_gate_s", il); - } - } else { cur = tmp; } @@ -2300,11 +2270,7 @@ ggml_tensor * llm_graph_context::build_ffn( } if (down) { - cur = build_lora_mm(down, cur); - if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) { - // GLM4, GLM4_MOE, and JAIS2 have numerical issues with F16 accumulators - ggml_prec_set_acc(cur, GGML_PREC_BF16); - } + cur = build_lora_mm(down, cur, down_s); } if (down_b) { @@ -2315,11 +2281,6 @@ ggml_tensor * llm_graph_context::build_ffn( cur = ggml_add(ctx0, cur, down_b); } - if (down_s) { - cur = ggml_mul(ctx0, cur, down_s); - cb(cur, "ffn_down_s", il); - } - return cur; } @@ -2339,9 +2300,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( int il, ggml_tensor * probs_in, ggml_tensor * gate_up_exps, - ggml_tensor * up_exps_s, - ggml_tensor * gate_exps_s, - ggml_tensor * down_exps_s, ggml_tensor * selected_experts_in, ggml_tensor * post_exp_norm, float post_exp_norm_eps) const { @@ -2362,9 +2320,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( probs_in, gate_up_exps, /* gate_up_exps_b */ nullptr, - up_exps_s, - gate_exps_s, - down_exps_s, selected_experts_in, post_exp_norm, post_exp_norm_eps @@ -2392,9 +2347,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( ggml_tensor * probs_in, ggml_tensor * gate_up_exps, ggml_tensor * gate_up_exps_b, - ggml_tensor * up_exps_s, - ggml_tensor * gate_exps_s, - ggml_tensor * down_exps_s, ggml_tensor * selected_experts_in, ggml_tensor * post_exp_norm, float post_exp_norm_eps) const { @@ -2407,10 +2359,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( if (probs_in == nullptr) { logits = build_lora_mm(gate_inp, cur); // [n_expert, n_tokens] - if (gating_op == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { - // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 - ggml_prec_set_acc(logits, GGML_PREC_F32); - } cb(logits, "ffn_moe_logits", il); } else { logits = probs_in; @@ -2583,13 +2531,9 @@ ggml_tensor * llm_graph_context::build_moe_ffn( if (gate_up_exps) { // merged gate_up path: one mul_mat_id, then split into gate and up views - ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, ids, up_exps_s, mm_ids, cached); // [n_ff*2, n_expert_used, n_tokens] + ggml_tensor * gate_up = build_lora_mm_id(gate_up_exps, cur, ids, mm_ids, cached); // [n_ff*2, n_expert_used, n_tokens] cb(gate_up, "ffn_moe_gate_up", il); - if (up_exps_s) { - cb(gate_up, "ffn_moe_gate_up_scaled", il); - } - if (gate_up_exps_b) { gate_up = ggml_add_id(ctx0, gate_up, gate_up_exps_b, ids); cb(gate_up, "ffn_moe_gate_up_biased", il); @@ -2602,29 +2546,21 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cb(up, "ffn_moe_up", il); } else { // separate gate and up path - up = build_lora_mm_id(up_exps, cur, ids, up_exps_s, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] + up = build_lora_mm_id(up_exps, cur, ids, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] cb(up, "ffn_moe_up", il); - if (up_exps_s) { - cb(up, "ffn_moe_up_scaled", il); - } - if (up_exps_b) { up = ggml_add_id(ctx0, up, up_exps_b, ids); cb(up, "ffn_moe_up_biased", il); } if (gate_exps) { - cur = build_lora_mm_id(gate_exps, cur, ids, gate_exps_s, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] + cur = build_lora_mm_id(gate_exps, cur, ids, mm_ids, cached); // [n_ff, n_expert_used, n_tokens] cb(cur, "ffn_moe_gate", il); } else { cur = up; } - if (gate_exps_s) { - cb(cur, "ffn_moe_gate_scaled", il); - } - if (gate_exps_b) { cur = ggml_add_id(ctx0, cur, gate_exps_b, ids); cb(cur, "ffn_moe_gate_biased", il); @@ -2727,7 +2663,7 @@ ggml_tensor * llm_graph_context::build_moe_ffn( cur = amax_src1.res; } - ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, down_exps_s, mm_ids, cached); // [n_embd, n_expert_used, n_tokens] + ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, mm_ids, cached); // [n_embd, n_expert_used, n_tokens] //ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above) cb(experts, "ffn_moe_down", il); @@ -2745,10 +2681,6 @@ ggml_tensor * llm_graph_context::build_moe_ffn( return (*static_cast(user_data))(cur, ids, mm_ids, cached); }, &build_experts); - if (down_exps_s) { - cb(experts, "ffn_moe_down_scaled", il); - } - if (down_exps_b) { experts = ggml_add_id(ctx0, experts, down_exps_b, selected_experts); cb(experts, "ffn_moe_down_biased", il); @@ -3485,8 +3417,6 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * v_mla, // TODO: remove float kq_scale, int il) const { - const llm_arch arch = model.arch; - GGML_ASSERT(v_mla == nullptr); if (inp->self_k_rot[il]) { @@ -3543,16 +3473,7 @@ ggml_tensor * llm_graph_context::build_attn( } if (wo) { - if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE || arch == LLM_ARCH_JAIS2) { - // GLM4, GLM4_MOE, and JAIS2 have numerical issues with F16 accumulators - cur = build_lora_mm(wo, cur); - ggml_prec_set_acc(cur, GGML_PREC_BF16); - if (wo_s) { - cur = ggml_mul(ctx0, cur, wo_s); - } - } else { - cur = build_lora_mm(wo, cur, wo_s); - } + cur = build_lora_mm(wo, cur, wo_s); } if (wo_b) { @@ -3603,8 +3524,6 @@ ggml_tensor * llm_graph_context::build_attn( ggml_tensor * v_mla, float kq_scale, int il) const { - const llm_arch arch = model.arch; - // these nodes are added to the graph together so that they are not reordered // by doing so, the number of splits in the graph is reduced // expand k later to enable rope fusion which directly writes into k-v cache @@ -3632,16 +3551,7 @@ ggml_tensor * llm_graph_context::build_attn( cb(cur, "kqv_out", il); if (wo) { - if (arch == LLM_ARCH_GLM4 || arch == LLM_ARCH_GLM4_MOE) { - // GLM4 and GLM4_MOE have numerical issues with F16 accumulators - cur = build_lora_mm(wo, cur); - ggml_prec_set_acc(cur, GGML_PREC_BF16); - if (wo_s) { - cur = ggml_mul(ctx0, cur, wo_s); - } - } else { - cur = build_lora_mm(wo, cur, wo_s); - } + cur = build_lora_mm(wo, cur, wo_s); } if (wo_b) { diff --git a/src/llama-graph.h b/src/llama-graph.h index a9f8e5ce0068..116b7132a53e 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -1179,6 +1179,7 @@ struct llm_graph_context { ggml_tensor * cur) const; // do mat_mul, while optionally apply lora and per-tensor scale + // w_s defaults to the weight scale of w ggml_tensor * build_lora_mm( ggml_tensor * w, ggml_tensor * cur, @@ -1190,7 +1191,6 @@ struct llm_graph_context { ggml_tensor * w, // ggml_tensor * as ggml_tensor * cur, // ggml_tensor * b ggml_tensor * ids, - ggml_tensor * w_s = nullptr, ggml_tensor * slots = nullptr, bool cached = true) const; @@ -1263,9 +1263,6 @@ struct llm_graph_context { int il, ggml_tensor * probs_in = nullptr, ggml_tensor * gate_up_exps = nullptr, - ggml_tensor * up_exps_s = nullptr, - ggml_tensor * gate_exps_s = nullptr, - ggml_tensor * down_exps_s = nullptr, ggml_tensor * selected_experts_in = nullptr, ggml_tensor * post_exp_norm = nullptr, float post_exp_norm_eps = 1e-5f) const; @@ -1291,9 +1288,6 @@ struct llm_graph_context { ggml_tensor * probs_in = nullptr, ggml_tensor * gate_up_exps = nullptr, ggml_tensor * gate_up_exps_b = nullptr, - ggml_tensor * up_exps_s = nullptr, - ggml_tensor * gate_exps_s = nullptr, - ggml_tensor * down_exps_s = nullptr, ggml_tensor * selected_experts_in = nullptr, ggml_tensor * post_exp_norm = nullptr, float post_exp_norm_eps = 1e-5f) const; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 11c4569470a9..06eb7c929281 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -1410,12 +1410,19 @@ bool llama_prec_policy::apply(ggml_tensor * res) const { return false; } - const auto it = prec_src1.find(res->src[0]); - if (it == prec_src1.end()) { - return false; + bool applied = false; + + const auto it_acc = prec_acc.find(res->src[0]); + if (it_acc != prec_acc.end()) { + applied |= ggml_prec_set_acc(res, it_acc->second); } - return ggml_prec_set_src(res, it->second, 1); + const auto it_src1 = prec_src1.find(res->src[0]); + if (it_src1 != prec_src1.end()) { + applied |= ggml_prec_set_src(res, it_src1->second, 1); + } + + return applied; } void llama_prec_policy::load(llama_model_loader & ml, const llama_model & model) { @@ -2044,6 +2051,42 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } } + // map each weight to its ".scale" tensor: shape {1} for a 2D weight, {n_expert} for a 3D weight + { + auto ends_with = [](const std::string & str, const std::string & suffix) { + return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; + }; + std::unordered_map weights; + for (const auto & [name, cur] : tensors_by_name) { + if (ends_with(name, ".weight")) { + weights.emplace(name.substr(0, name.size() - 7), cur); + } + } + for (const auto & [name, s] : tensors_by_name) { + if (!ends_with(name, ".scale")) { + continue; + } + const auto it = weights.find(name.substr(0, name.size() - 6)); + if (it == weights.end()) { + continue; + } + ggml_tensor * w = it->second; + const bool ok = w->ne[3] == 1 && ggml_nelements(s) == w->ne[2] && s->ne[0] == w->ne[2]; + if (ok) { + w_scales.emplace(w, s); + } else { + LLAMA_LOG_DEBUG("%s: '%s' is not a weight scale for '%s', skipping\n", __func__, name.c_str(), w->name); + } + } + } + + // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 + if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { + for (const auto & layer : layers) { + prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); + } + } + // per-tensor activation precision policy prec_policy.load(ml, *this); @@ -2575,6 +2618,11 @@ size_t llama_model::size() const { return pimpl->n_bytes; } +ggml_tensor * llama_model::get_w_scale(const ggml_tensor * w) const { + const auto it = w_scales.find(w); + return it == w_scales.end() ? nullptr : it->second; +} + size_t llama_model::n_tensors() const { return tensors_by_name.size(); } diff --git a/src/llama-model.h b/src/llama-model.h index 6473980a8db3..eae5c68486ab 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -737,8 +737,7 @@ struct llama_meta_device_get_split_state_userdata { struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const struct ggml_tensor * tensor, void * userdata); struct llama_prec_policy { - // the key is the weight tensor `res->src[0]`, stores the recommended accumulation type of the op (unused for now) - // TODO: migrate ad-hoc ggml_prec_set_acc() calls to this container + update apply() to use it + // the key is the weight tensor `res->src[0]`, stores the recommended accumulation type of the op std::unordered_map prec_acc; // the key is the weight tensor `res->src[0]`, stores the recommended activation precision type @@ -746,6 +745,12 @@ struct llama_prec_policy { bool apply(ggml_tensor * res) const; + void set_acc(const ggml_tensor * w, ggml_prec prec) { + if (w) { + prec_acc[w] = prec; + } + } + void load(llama_model_loader & ml, const llama_model & model); }; @@ -818,6 +823,11 @@ struct llama_model { llama_hadamard hdmd; + // weight -> ".scale" tensor (e.g. NVFP4 scale2), applied by build_lora_mm and build_lora_mm_id + std::unordered_map w_scales; + + ggml_tensor * get_w_scale(const ggml_tensor * w) const; + // see llama_model_set_attn_rot bool attn_rot = true; diff --git a/src/models/clover-moe.cpp b/src/models/clover-moe.cpp index 8892521eee35..83799726145c 100644 --- a/src/models/clover-moe.cpp +++ b/src/models/clover-moe.cpp @@ -398,10 +398,7 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_ffn(ggml_tensor * cur, LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); if (model.layers[il].ffn_up_shexp != nullptr) { diff --git a/src/models/cohere2moe.cpp b/src/models/cohere2moe.cpp index 52b959672dfa..c4d778e5050d 100644 --- a/src/models/cohere2moe.cpp +++ b/src/models/cohere2moe.cpp @@ -226,10 +226,7 @@ llama_model_cohere2moe::graph::graph(const llm_graph_params & params) : llm_grap hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(cur, "ffn_moe_out", il); if (layer.ffn_up_shexp) { @@ -371,10 +368,7 @@ llama_model_cohere2moe::graph_mtp::graph_mtp(const llm_graph_params & params) : hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(cur, "mtp_ffn_moe_out", il); if (layer.ffn_up_shexp) { diff --git a/src/models/deepseek32.cpp b/src/models/deepseek32.cpp index 853389b88306..8f6f34790df3 100644 --- a/src/models/deepseek32.cpp +++ b/src/models/deepseek32.cpp @@ -383,10 +383,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // FFN shared expert @@ -624,10 +621,7 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); // FFN shared expert diff --git a/src/models/deepseek4.cpp b/src/models/deepseek4.cpp index dfc9858e7bea..f4269e0430e4 100644 --- a/src/models/deepseek4.cpp +++ b/src/models/deepseek4.cpp @@ -1284,9 +1284,6 @@ llama_model_deepseek4::graph::graph(const llm_graph_params & params) : il, nullptr, nullptr, - nullptr, - nullptr, - nullptr, selected_experts); cb(moe_out, "ffn_moe_out", il); diff --git a/src/models/deepseek41.cpp b/src/models/deepseek41.cpp index ed93be5348e2..e481cbd1de10 100644 --- a/src/models/deepseek41.cpp +++ b/src/models/deepseek41.cpp @@ -203,6 +203,8 @@ void llama_model_deepseek41::load_arch_tensors(llama_model_loader & ml) { } layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, 0); + // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/1bae0e1088993b9b82de08f59de5be5a34e42170/inference/model.py#L813 + prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); layer.ffn_exp_probs_b = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B, "bias", i), {n_expert}, 0); layer.ffn_exp_probs_b_vl = create_tensor(tn(LLM_TENSOR_FFN_EXP_PROBS_B_VL, "bias", i), {n_expert}, TENSOR_NOT_REQUIRED); layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0); @@ -874,9 +876,7 @@ llama_model_deepseek41::graph::graph(const llm_graph_params & params) : cur = build_norm(cur, layer.ffn_norm, nullptr, LLM_NORM_RMS, il); cb(cur, "ffn_norm", il); - // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash-1017/blob/1bae0e1088993b9b82de08f59de5be5a34e42170/inference/model.py#L813 ggml_tensor * logits = build_lora_mm(layer.ffn_gate_inp, cur); - ggml_prec_set_acc(logits, GGML_PREC_F32); cb(logits, "ffn_moe_logits", il); // image (embedding) tokens use the vision router bias, as DeepSeek-V4 diff --git a/src/models/dots3note.cpp b/src/models/dots3note.cpp index da16f24801fc..2a2d5500b992 100644 --- a/src/models/dots3note.cpp +++ b/src/models/dots3note.cpp @@ -401,10 +401,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); ggml_tensor * ffn_shexp = diff --git a/src/models/flint.cpp b/src/models/flint.cpp index 520334ce656f..173278b6f34c 100644 --- a/src/models/flint.cpp +++ b/src/models/flint.cpp @@ -158,10 +158,7 @@ llama_model_flint::graph::graph(const llm_graph_params & params) : LLM_FFN_SILU, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); { diff --git a/src/models/gemma4.cpp b/src/models/gemma4.cpp index 1a377fa3cb7b..491ef128319a 100644 --- a/src/models/gemma4.cpp +++ b/src/models/gemma4.cpp @@ -406,10 +406,7 @@ llama_model_gemma4::graph::graph(const llm_graph_params & params) : 1.0f, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, logits, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cur_moe = build_norm(cur_moe, model.layers[il].ffn_post_norm_2, nullptr, LLM_NORM_RMS, il); diff --git a/src/models/glm-dsa.cpp b/src/models/glm-dsa.cpp index 6daafd007caf..c0ff62e4a3ac 100644 --- a/src/models/glm-dsa.cpp +++ b/src/models/glm-dsa.cpp @@ -431,10 +431,7 @@ llama_model_glm_dsa::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // FFN shared expert @@ -672,10 +669,7 @@ llama_model_glm_dsa::graph_mtp::graph_mtp(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); // FFN shared expert diff --git a/src/models/glm4-moe.cpp b/src/models/glm4-moe.cpp index 9560fd3d0429..a3e2fa46e4ef 100644 --- a/src/models/glm4-moe.cpp +++ b/src/models/glm4-moe.cpp @@ -113,6 +113,11 @@ void llama_model_glm4_moe::load_arch_tensors(llama_model_loader & ml) { layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED | flags); layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, TENSOR_NOT_REQUIRED | flags); } + + // numerical issues with F16 accumulators + prec_policy.set_acc(layer.wo, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down_shexp, GGML_PREC_BF16); } } diff --git a/src/models/glm4.cpp b/src/models/glm4.cpp index e57c51cbe78e..5c50b2f055d2 100644 --- a/src/models/glm4.cpp +++ b/src/models/glm4.cpp @@ -58,6 +58,10 @@ void llama_model_glm4::load_arch_tensors(llama_model_loader &) { layer.nextn.shared_head_head = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "weight", i), { n_embd, n_vocab }, flags | TENSOR_NOT_REQUIRED); layer.nextn.shared_head_norm = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_NORM, "weight", i), { n_embd }, flags | TENSOR_NOT_REQUIRED); } + + // numerical issues with F16 accumulators + prec_policy.set_acc(layer.wo, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down, GGML_PREC_BF16); } } diff --git a/src/models/granite-hybrid.cpp b/src/models/granite-hybrid.cpp index be352dfd770d..d638663afd44 100644 --- a/src/models/granite-hybrid.cpp +++ b/src/models/granite-hybrid.cpp @@ -260,11 +260,7 @@ ggml_tensor * llama_model_granite_hybrid::graph::build_layer_ffn(ggml_tensor * LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); // For Granite MoE Shared diff --git a/src/models/granite-swa.cpp b/src/models/granite-swa.cpp index be9e5577856d..2e2609f52c83 100644 --- a/src/models/granite-swa.cpp +++ b/src/models/granite-swa.cpp @@ -277,10 +277,7 @@ ggml_tensor * llama_model_granite_swa::graph::build_layer_ffn( hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // For Granite MoE Shared - gate+up kept fused in ffn_up_shexp diff --git a/src/models/granite.cpp b/src/models/granite.cpp index 0ab9084dae8a..0a5dd78eafb6 100644 --- a/src/models/granite.cpp +++ b/src/models/granite.cpp @@ -269,11 +269,7 @@ ggml_tensor * llama_model_granite::graph::build_layer_ffn( LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); // For Granite MoE Shared diff --git a/src/models/hy-v3.cpp b/src/models/hy-v3.cpp index c47c373f89ea..f53d94827ee7 100644 --- a/src/models/hy-v3.cpp +++ b/src/models/hy-v3.cpp @@ -168,10 +168,7 @@ llama_model_hy_v3::graph::graph(const llm_graph_params & params) : llm_graph_con hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // shared expert (always active, no gate) @@ -323,10 +320,7 @@ llama_model_hy_v3::graph_mtp::graph_mtp(const llm_graph_params & params) hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); ggml_tensor * sh_out = build_ffn(cur, diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 3e43ef4184ea..45477a69e35e 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -97,6 +97,7 @@ void llama_model_inkling2::load_arch_tensors(llama_model_loader &) { // output output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab_padded}, 0); + prec_policy.set_acc(output, GGML_PREC_F32); output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); output_res_query = create_tensor(tn(LLM_TENSOR_OUTPUT_RES_QUERY, "weight"), {n_embd}, 0); @@ -406,10 +407,7 @@ ggml_tensor * llama_model_inkling2::graph::build_layer(int il, int ip, ggml_tens LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + layer.ffn_gate_up_exps); cur = convolve(cur, layer.ffn_post_conv, nullptr, state, history, recr, 2*n_embd_k_gqa + n_embd); cb(cur, "ffn_out", il); @@ -433,7 +431,6 @@ void llama_model_inkling2::graph::build_output(ggml_tensor * cur, const std::vec // lm_head cur = build_lora_mm(model.output, cur); - ggml_prec_set_acc(cur, GGML_PREC_F32); if (hparams.f_final_logit_softcapping != 0.0f) { const float cap = hparams.f_final_logit_softcapping; diff --git a/src/models/jais2.cpp b/src/models/jais2.cpp index 8376423ea5fd..1f077fd8699b 100644 --- a/src/models/jais2.cpp +++ b/src/models/jais2.cpp @@ -42,6 +42,10 @@ void llama_model_jais2::load_arch_tensors(llama_model_loader &) { layer.ffn_up_b = create_tensor(tn(LLM_TENSOR_FFN_UP, "bias", i), {n_ff}, 0); layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0); layer.ffn_down_b = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "bias", i), {n_embd}, 0); + + // numerical issues with F16 accumulators + prec_policy.set_acc(layer.wo, GGML_PREC_BF16); + prec_policy.set_acc(layer.ffn_down, GGML_PREC_BF16); } } diff --git a/src/models/kolibri1.cpp b/src/models/kolibri1.cpp index c4d8eca1bed4..64182d186061 100644 --- a/src/models/kolibri1.cpp +++ b/src/models/kolibri1.cpp @@ -142,7 +142,7 @@ llama_model_kolibri1::graph::graph(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, logits, - nullptr, nullptr, nullptr, nullptr, selected); + nullptr, selected); cb(moe_out, "ffn_moe_out", il); ggml_tensor * shared = build_ffn(cur, diff --git a/src/models/lfm-base.cpp b/src/models/lfm-base.cpp index 3627c527dd7a..03e59bd0979b 100644 --- a/src/models/lfm-base.cpp +++ b/src/models/lfm-base.cpp @@ -116,10 +116,5 @@ ggml_tensor * llm_build_lfm_base::build_lfm_moe_ffn(ggml_tensor * cur, LLM_FFN_SILU, true, hparams.expert_weights_scale, static_cast(hparams.expert_gating_func), - il, - nullptr, - nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); } diff --git a/src/models/llama.cpp b/src/models/llama.cpp index 26d54968cabd..3925699f4188 100644 --- a/src/models/llama.cpp +++ b/src/models/llama.cpp @@ -198,11 +198,7 @@ llama_model_llama::graph::graph(const llm_graph_params & params) : llm_gr LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(cur, "ffn_moe_out", il); } cur = ggml_add(ctx0, cur, ffn_inp); diff --git a/src/models/mellum.cpp b/src/models/mellum.cpp index 57dd5b79a28e..d0b3609b1e08 100644 --- a/src/models/mellum.cpp +++ b/src/models/mellum.cpp @@ -199,11 +199,7 @@ llama_model_mellum::graph::graph(const llm_graph_params & params) : llm_gr LLM_FFN_SILU, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); cur = moe_out; @@ -351,11 +347,7 @@ llama_model_mellum::graph_mtp::graph_mtp(const llm_graph_params & params) LLM_FFN_SILU, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, - nullptr, nullptr, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + il); cb(cur, "mtp_ffn_moe_out", il); cur = ggml_add(ctx0, cur, ffn_inp); diff --git a/src/models/metis16.cpp b/src/models/metis16.cpp index 8a433f3cc0bb..0a57a6ab0b0e 100644 --- a/src/models/metis16.cpp +++ b/src/models/metis16.cpp @@ -329,7 +329,7 @@ llama_model_metis16::graph::graph(const llm_graph_params & params) : ggml_tensor * moe_out = build_moe_ffn(latent, nullptr, nullptr, nullptr, layer.ffn_down_exps, nullptr, n_exp, n_used, LLM_FFN_SILU, false, 0.0f, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX_WEIGHT, il_p, - logits, layer.ffn_gate_up_exps, nullptr, nullptr, nullptr, selected); + logits, layer.ffn_gate_up_exps, selected); ggml_tensor * shexp = build_ffn(latent, layer.ffn_up_shexp, NULL, NULL, layer.ffn_gate_shexp, NULL, NULL, diff --git a/src/models/minimax-m3.cpp b/src/models/minimax-m3.cpp index 4f1184590f82..8560c710aff3 100644 --- a/src/models/minimax-m3.cpp +++ b/src/models/minimax-m3.cpp @@ -572,10 +572,7 @@ llama_model_minimax_m3::graph::graph(const llm_graph_params & params) : llm_grap LLM_FFN_SWIGLU_OAI_MOE, hparams.expert_weights_norm, hparams.expert_weights_scale, (llama_expert_gating_func_type) hparams.expert_gating_func, - il, nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); // shared expert (swigluoai) diff --git a/src/models/mistral-large4.cpp b/src/models/mistral-large4.cpp index 6407d7663637..aab49df9d8a4 100644 --- a/src/models/mistral-large4.cpp +++ b/src/models/mistral-large4.cpp @@ -420,10 +420,7 @@ llama_model_mistral_large4::graph::graph(const llm_graph_params & params) : (llama_expert_gating_func_type) hparams.expert_gating_func, il, nullptr, - layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + layer.ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); ggml_tensor * ffn_shexp = build_ffn(cur, diff --git a/src/models/mistral3.cpp b/src/models/mistral3.cpp index ab81218635da..e1e6981bb0db 100644 --- a/src/models/mistral3.cpp +++ b/src/models/mistral3.cpp @@ -248,11 +248,7 @@ llama_model_mistral3::graph::graph(const llm_graph_params & params) : llm_graph_ LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(cur, "ffn_moe_out", il); } cur = ggml_add(ctx0, cur, ffn_inp); diff --git a/src/models/muse-spark.cpp b/src/models/muse-spark.cpp index ea6ab84abd94..10de4676e12f 100644 --- a/src/models/muse-spark.cpp +++ b/src/models/muse-spark.cpp @@ -180,7 +180,7 @@ llama_model_muse_spark::graph::graph(const llm_graph_params & params) (llama_expert_gating_func_type) hparams.expert_gating_func, il, router_logits, - nullptr, nullptr, nullptr, nullptr, nullptr, + nullptr, nullptr, model.layers[il].ffn_post_exp_norm, hparams.f_post_norm_eps); cb(moe_out, "ffn_moe_out", il); diff --git a/src/models/nemotron-h-moe.cpp b/src/models/nemotron-h-moe.cpp index 4753558327d1..3aa385379d6d 100644 --- a/src/models/nemotron-h-moe.cpp +++ b/src/models/nemotron-h-moe.cpp @@ -118,10 +118,7 @@ llama_model_nemotron_h_moe::graph_mtp::graph_mtp(const llm_graph_params & params hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, - router_logits, nullptr, - layer.ffn_up_exps_s, - nullptr, // no gate - layer.ffn_down_exps_s); + router_logits); cb(moe_out, "mtp_ffn_moe_out", il); if (layer.ffn_latent_up) { diff --git a/src/models/nemotron-h.cpp b/src/models/nemotron-h.cpp index 313f42f1c7a0..18e45320a317 100644 --- a/src/models/nemotron-h.cpp +++ b/src/models/nemotron-h.cpp @@ -322,10 +322,7 @@ ggml_tensor * llama_model_nemotron_h::graph::build_ffn_layer(ggml_tensor * cur, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SIGMOID, il, - router_logits, nullptr, - model.layers[il].ffn_up_exps_s, - nullptr, // no gate - model.layers[il].ffn_down_exps_s); + router_logits); cb(moe_out, "ffn_moe_out", il); if (model.layers[il].ffn_latent_up) { diff --git a/src/models/qwen35moe.cpp b/src/models/qwen35moe.cpp index c0ee6fa03fc8..c92b84d9d99e 100644 --- a/src/models/qwen35moe.cpp +++ b/src/models/qwen35moe.cpp @@ -479,10 +479,7 @@ ggml_tensor * llama_model_qwen35moe::graph::build_layer_ffn(ggml_tensor * cur, c LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // Add shared experts if present - following Qwen3Next reference implementation @@ -651,10 +648,7 @@ llama_model_qwen35moe::graph_mtp::graph_mtp(const llm_graph_params & params) LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); if (layer.ffn_up_shexp != nullptr) { diff --git a/src/models/qwen3moe.cpp b/src/models/qwen3moe.cpp index ce7144a229b3..fc57928f598b 100644 --- a/src/models/qwen3moe.cpp +++ b/src/models/qwen3moe.cpp @@ -136,11 +136,7 @@ llama_model_qwen3moe::graph::graph(const llm_graph_params & params) : llm_graph_ LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, - il, - nullptr, nullptr, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + il); cb(moe_out, "ffn_moe_out", il); cur = moe_out; diff --git a/src/models/qwen3next.cpp b/src/models/qwen3next.cpp index 9546fba581a4..208aa49d257e 100644 --- a/src/models/qwen3next.cpp +++ b/src/models/qwen3next.cpp @@ -561,10 +561,7 @@ ggml_tensor * llama_model_qwen3next::graph::build_layer_ffn(ggml_tensor * cur, c LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // Add shared experts if present - following Qwen3Next reference implementation @@ -748,10 +745,7 @@ llama_model_qwen3next::graph_mtp::graph_mtp(const llm_graph_params & params) LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, layer.ffn_gate_up_exps, - layer.ffn_up_exps_s, - layer.ffn_gate_exps_s, - layer.ffn_down_exps_s); + nullptr, layer.ffn_gate_up_exps); cb(moe_out, "mtp_ffn_moe_out", il); if (layer.ffn_up_shexp != nullptr) { diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index 63c918602547..106530490fd7 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -1230,10 +1230,7 @@ ggml_tensor * llama_model_qwen4exp::graph::build_layer_ffn(ggml_tensor * cur, co LLM_FFN_SILU, true, hparams.expert_weights_scale, LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, il, - nullptr, model.layers[il].ffn_gate_up_exps, - model.layers[il].ffn_up_exps_s, - model.layers[il].ffn_gate_exps_s, - model.layers[il].ffn_down_exps_s); + nullptr, model.layers[il].ffn_gate_up_exps); cb(moe_out, "ffn_moe_out", il); // shared experts, as in the Qwen3Next reference diff --git a/src/models/zaya1.cpp b/src/models/zaya1.cpp index 2763500f4001..013658c73448 100644 --- a/src/models/zaya1.cpp +++ b/src/models/zaya1.cpp @@ -277,9 +277,6 @@ ggml_tensor * llama_model_zaya1::graph::build_router_moe(const llama_model & mod il, logits, layer.ffn_gate_up_exps, - nullptr, - nullptr, - nullptr, expert); return ggml_mul(ctx0, moe, keep); diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index 9bd4b82bfed5..2a4f4b36192c 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -41,6 +41,7 @@ cohere2 ,0 ,any ,NORM+MUL , 3 cohere2moe ,1 ,any ,ADD+ADD , 2 cohere2moe ,1 ,any ,MUL+ADD , 2 cohere2moe ,1 ,any ,RMS_NORM+MUL , 3 +command-r ,0 ,any ,ADD+ADD , 2 command-r ,0 ,any ,NORM+MUL , 3 dbrx ,0 ,any ,MUL+ADD , 4 dbrx ,0 ,any ,NORM+MUL , 5 @@ -207,6 +208,7 @@ llama ,0 ,any ,MUL+ADD , 4 llama ,0 ,any ,RMS_NORM+MUL , 5 llama ,0 ,any ,SOFT_MAX+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 llama4 ,0 ,any ,ADD+ADD , 2 +llama4 ,0 ,any ,MUL+ADD , 4 llama4 ,0 ,any ,RMS_NORM+MUL , 9 maincoder ,0 ,any ,RMS_NORM+MUL , 9 maion-coder ,0 ,any ,MUL+ADD , 4 @@ -257,8 +259,7 @@ moshi ,0 ,any ,RMS_NORM+MUL , 5 mpt ,0 ,any ,NORM+MUL+ADD , 5 muse-glimmer ,0 ,any ,RMS_NORM+MUL , 10 muse-glimmer ,0 ,any ,RMS_NORM+MUL+ADD , 3 -muse-spark ,0 ,prefill ,MUL+ADD , 2 -muse-spark ,0 ,decode ,MUL+ADD , 4 +muse-spark ,0 ,any ,MUL+ADD , 4 muse-spark ,0 ,any ,RMS_NORM+MUL , 11 muse-spark ,0 ,any ,RMS_NORM+MUL+ADD , 3 muse-spark ,0 ,any ,UNARY+ADD+ARGSORT+GET_ROWS+SUM_ROWS+CLAMP+DIV, 2 From e6d624b9a4b95c6b52f5ca384d70b75581f9821a Mon Sep 17 00:00:00 2001 From: saiph Date: Sun, 22 Nov 2026 02:05:02 +0800 Subject: [PATCH 028/401] mtmd : merge Parakeet rel-pos views to avoid OOB (#32722) Assisted-by: Grok Bot --- tools/mtmd/models/parakeet.cpp | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/tools/mtmd/models/parakeet.cpp b/tools/mtmd/models/parakeet.cpp index 4a2377b4cf87..a989e5839177 100644 --- a/tools/mtmd/models/parakeet.cpp +++ b/tools/mtmd/models/parakeet.cpp @@ -296,23 +296,16 @@ ggml_cgraph * mtmd_graph_parakeet::build() { int center = pos_window / 2; size_t offset = rel_pos_scores->nb[0] * (center+1); - rel_pos_scores = ggml_view_3d(ctx0, rel_pos_scores, - n_frame, pos_window, n_head, - (pos_window) * 4, - rel_pos_scores->nb[2], - offset); - rel_pos_scores = ggml_cont(ctx0, rel_pos_scores); - ggml_format_name(rel_pos_scores, "enc_%d_attn_rel_pos_shifted", il); - + // nb1 is the diagonal-extraction stride, not the source row stride rel_pos_scores = ggml_view_3d(ctx0, rel_pos_scores, content_scores->ne[0], content_scores->ne[1], - rel_pos_scores->ne[2], - rel_pos_scores->nb[1], + n_head, + (size_t) pos_window * rel_pos_scores->nb[0], rel_pos_scores->nb[2], - 0); + offset); rel_pos_scores = ggml_cont(ctx0, rel_pos_scores); - ggml_format_name(rel_pos_scores, "enc_%d_attn_rel_pos_shifted_view", il); + ggml_format_name(rel_pos_scores, "enc_%d_attn_rel_pos_shifted", il); } struct ggml_tensor * attn_scores = ggml_add(ctx0, content_scores, rel_pos_scores); From afe77e18fadc2e673c6a6299495a443e17378ce4 Mon Sep 17 00:00:00 2001 From: Aldehir Rojas Date: Sat, 21 Nov 2026 15:27:25 -0600 Subject: [PATCH 029/401] chat : pass reasoning_effort = none if supported (#32763) --- common/jinja/caps.cpp | 7 +++++-- tests/test-chat.cpp | 5 +++-- tools/server/server-common.cpp | 9 +++++++-- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/common/jinja/caps.cpp b/common/jinja/caps.cpp index cf14c71c56d9..1f967daf6214 100644 --- a/common/jinja/caps.cpp +++ b/common/jinja/caps.cpp @@ -593,7 +593,7 @@ caps caps_get(jinja::program & prog) { if (result.supports_reasoning_effort) { JJ_DEBUG("%s\n", ">>> Running capability check: reasoning effort levels"); - static const std::vector candidates = { "minimal", "low", "medium", "high", "xhigh", "max" }; + static const std::vector candidates = { "none", "minimal", "low", "medium", "high", "xhigh", "max" }; // renders a single user turn with the given effort, nothing when the template raises const auto render = [&](const std::string & effort) { @@ -631,7 +631,10 @@ caps caps_get(jinja::program & prog) { for (const auto & level : candidates) { const auto rendered = render(level); if (!rendered) { - rejected.push_back(level); + // "none" also turns thinking off, so the server does not answer it with an error + if (level != "none") { + rejected.push_back(level); + } continue; } if (rendered == unknown) { diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 302ef319fa48..c4332941b6f1 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -8720,7 +8720,7 @@ static void test_reasoning_effort_caps() { assert_equals(json(expected).dump(), common_chat_templates_get_caps(tmpls.get()).at("reasoning_effort_levels").dump()); }; - const std::vector all_levels = { "minimal", "low", "medium", "high", "xhigh", "max" }; + const std::vector all_levels = { "none", "minimal", "low", "medium", "high", "xhigh", "max" }; assert_effort_levels("models/templates/deepseek-ai-DeepSeek-V4.jinja", { "max" }); assert_effort_levels("models/templates/deepseek-ai-DeepSeek-V4-Flash-0731.jinja", { "high", "max" }); @@ -8730,7 +8730,8 @@ static void test_reasoning_effort_caps() { assert_effort_levels("models/templates/upstage-Solar-Open-100B.jinja", { "low" }); assert_effort_levels("models/templates/muse-glimmer.jinja", all_levels); assert_effort_levels("models/templates/openai-gpt-oss-120b.jinja", all_levels); - assert_effort_levels("models/templates/Cohere2MoE.jinja", {}); + assert_effort_levels("models/templates/Cohere2MoE.jinja", { "none" }); + assert_effort_levels("models/templates/thinkingmachines-Inkling-2-Small.jinja", { "none", "minimal", "low", "medium", "high", "max" }); assert_effort_levels("models/templates/Qwen-Qwen3-0.6B.jinja", {}); auto assert_effort_rejected = [](const std::string & path, const std::vector & expected) { diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index eb5781e740d7..8d4c022e975d 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -1641,13 +1641,18 @@ json oaicompat_chat_params_parse( // Parse the OAI "reasoning_effort" field; "none" disables reasoning. if (body.contains("reasoning_effort")) { auto reasoning_effort = json_value(body, "reasoning_effort", std::string("")); + const auto levels = caps.at("reasoning_effort_levels").get>(); if (reasoning_effort == "none") { inputs.enable_thinking = false; - inputs.chat_template_kwargs.erase("reasoning_effort"); + // Some models use reasoning_effort = none and some throw an exception, so check the model's list of effort levels first + if (std::find(levels.begin(), levels.end(), reasoning_effort) != levels.end()) { + inputs.chat_template_kwargs["reasoning_effort"] = json(reasoning_effort).dump(); + } else { + inputs.chat_template_kwargs.erase("reasoning_effort"); + } } else if (!reasoning_effort.empty()) { const auto rejected = caps.at("reasoning_effort_rejected").get>(); if (std::find(rejected.begin(), rejected.end(), reasoning_effort) != rejected.end()) { - const auto levels = caps.at("reasoning_effort_levels").get>(); throw std::invalid_argument("reasoning_effort \"" + reasoning_effort + "\" is not supported by the chat template, supported levels: " + string_join(levels, ", ")); } inputs.chat_template_kwargs["reasoning_effort"] = json(reasoning_effort).dump(); From cbb1c1c50bba81929387dea473873d1df87a6212 Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Sun, 22 Nov 2026 00:35:43 +0100 Subject: [PATCH 030/401] model: fix no_realloc for clef and vllm-decision2 (#32754) --- src/models/clef.cpp | 48 +++++++++++++++++++++++------------ src/models/models.h | 2 +- src/models/vllm-decision2.cpp | 16 ++++++++---- 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/src/models/clef.cpp b/src/models/clef.cpp index 86fed4e874a8..c41c93cb138c 100644 --- a/src/models/clef.cpp +++ b/src/models/clef.cpp @@ -173,22 +173,35 @@ static clef_spans clef_get_spans(const llama_ubatch & ubatch) { return res; } +// the head always has the max number of spans, so its graph depends only on n_tokens +// each span has 1 token or more and each question has an option, so there is always a spare question for the padding options +static size_t clef_n_questions(int64_t n_tokens) { return n_tokens / 2 + 1; } +static size_t clef_n_options (int64_t n_tokens) { return std::max(n_tokens - 1, 1); } + // pooling matrices and indices computed from the spans class llama_model_clef::input_decision : public llm_graph_input_i { public: - input_decision(const llama_ubatch & ubatch) : n_tokens(ubatch.n_tokens) { - const auto spans = clef_get_spans(ubatch); - n_questions = spans.questions.size(); - n_options = spans.options.size(); - } + input_decision(const llama_ubatch & ubatch) : + n_tokens(ubatch.n_tokens), n_questions(clef_n_questions(n_tokens)), n_options(clef_n_options(n_tokens)) {} void set_input(const llama_ubatch * ubatch) override { // a batch of embeddings has no token ids, and no usable spans const std::vector no_tokens(ubatch->token ? 0 : n_tokens, 0); ggml_backend_tensor_set(tokens, ubatch->token ? ubatch->token : no_tokens.data(), 0, n_tokens * sizeof(llama_token)); - const auto spans = clef_get_spans(*ubatch); - GGML_ASSERT(spans.questions.size() == n_questions && spans.options.size() == n_options); + auto spans = clef_get_spans(*ubatch); + const int32_t n_q_used = spans.questions.size(); + GGML_ASSERT((size_t) n_q_used < n_questions && spans.options.size() <= n_options); + + // the padding options belong to the first padding question, the questions do not read the padding questions + spans.questions.resize(n_questions, { 0, 0, 0 }); + spans.options.resize(n_options, { n_q_used, 0, 0 }); + + std::vector q_mask(n_questions * n_questions, 0.0f); + for (size_t i = 0; i < n_questions; i++) { + std::fill(q_mask.begin() + i * n_questions + n_q_used, q_mask.begin() + (i + 1) * n_questions, -INFINITY); + } + ggml_backend_tensor_set(question_mask, q_mask.data(), 0, ggml_nbytes(question_mask)); // the scores are NaN if the batch has a decision order that cannot be used const float status_data = spans.valid || ubatch->decision_order == nullptr ? 0.0f : NAN; @@ -215,6 +228,8 @@ class llama_model_clef::input_decision : public llm_graph_input_i { owner[i] = o.question; mask[o.question * n_options + i] = 0.0f; } + // a padding question reads all options, a row of -inf gives NaN + std::fill(mask.begin() + n_q_used * n_options, mask.end(), 0.0f); ggml_backend_tensor_set(pool_q, pool_q_data.data(), 0, ggml_nbytes(pool_q)); ggml_backend_tensor_set(pool_o, pool_o_data.data(), 0, ggml_nbytes(pool_o)); @@ -225,8 +240,7 @@ class llama_model_clef::input_decision : public llm_graph_input_i { bool can_reuse(const llm_graph_params & params) override { // the values are computed again in set_input(), only the shapes must match - const auto spans = clef_get_spans(params.ubatch); - return spans.questions.size() == n_questions && spans.options.size() == n_options; + return params.ubatch.n_tokens == (uint32_t) n_tokens; } ggml_tensor * tokens = nullptr; // I32 [n_tokens] @@ -235,11 +249,12 @@ class llama_model_clef::input_decision : public llm_graph_input_i { ggml_tensor * question_type = nullptr; // I32 [n_questions] ggml_tensor * option_question = nullptr; // I32 [n_options] ggml_tensor * option_mask = nullptr; // F32 [n_options, n_questions], 0 if the option belongs to the question, else -inf + ggml_tensor * question_mask = nullptr; // F32 [n_questions, n_questions], -inf for the padding questions ggml_tensor * status = nullptr; // F32 [1], added to the scores: 0, or NaN on invalid input const int64_t n_tokens; - size_t n_questions; - size_t n_options; + const size_t n_questions; + const size_t n_options; }; // the backbone is copied from llama_model_qwen35::graph, without the memory module @@ -479,8 +494,8 @@ ggml_tensor * llama_model_clef::graph::build_head_norm(ggml_tensor * cur, const return build_norm(cur, n.w, n.b, LLM_NORM, -1); } -// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], no mask -ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a) { +// q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null +ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) { const int64_t n_embd_h = q->ne[0]; const int64_t n_head_h = model.n_head_decision; const int64_t d_head = n_embd_h / n_head_h; @@ -497,7 +512,7 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten Vcur = ggml_cont(ctx0, Vcur); ggml_tensor * kq = ggml_mul_mat(ctx0, Kcur, Qcur); // [n_kv, n_q, n_head] - kq = ggml_soft_max_ext(ctx0, kq, nullptr, 1.0f / sqrtf(float(d_head)), 0.0f); + kq = ggml_soft_max_ext(ctx0, kq, kq_mask, 1.0f / sqrtf(float(d_head)), 0.0f); ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head] cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q); @@ -523,8 +538,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de inp->question_type = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_questions); inp->option_question = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_options); inp->option_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_options, n_questions); + inp->question_mask = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_questions, n_questions); inp->status = ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1); - for (ggml_tensor * t : { inp->tokens, inp->pool_q, inp->pool_o, inp->question_type, inp->option_question, inp->option_mask, inp->status }) { + for (ggml_tensor * t : { inp->tokens, inp->pool_q, inp->pool_o, inp->question_type, inp->option_question, inp->option_mask, inp->question_mask, inp->status }) { ggml_set_input(t); } @@ -584,7 +600,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de const auto & layer = model.head_layers[il]; ggml_tensor * cur = build_head_norm(fields, layer.self_norm); - fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn)); + fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn, inp->question_mask)); cur = build_head_norm(fields, layer.cross_norm); fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn)); diff --git a/src/models/models.h b/src/models/models.h index 0f49b8ae05b1..b12642fb9a70 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -2927,7 +2927,7 @@ struct llama_model_clef : public llama_model_qwen35 { input_decision * inp); ggml_tensor * build_head_norm(ggml_tensor * cur, const norm & n); - ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a); + ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr); ggml_tensor * build_head_ffn (ggml_tensor * cur, const head_layer & layer); const llama_model_clef & model; diff --git a/src/models/vllm-decision2.cpp b/src/models/vllm-decision2.cpp index 2a3b9595c72d..6925344257a5 100644 --- a/src/models/vllm-decision2.cpp +++ b/src/models/vllm-decision2.cpp @@ -99,13 +99,19 @@ static decision2_rows decision2_get_rows(const llama_ubatch & ubatch) { return res; } +// no decision order (e.g. reserve): use the max number of options +static size_t decision2_n_options(const llama_ubatch & ubatch, uint32_t n_outputs) { + return ubatch.decision_order ? decision2_get_rows(ubatch).options.size() : std::max(n_outputs, 1); +} + class llama_model_vllm_decision2::input_decision : public llm_graph_input_i { public: - input_decision(const llama_ubatch & ubatch) : n_options(decision2_get_rows(ubatch).options.size()) {} + input_decision(const llama_ubatch & ubatch, uint32_t n_outputs) : n_options(decision2_n_options(ubatch, n_outputs)) {} void set_input(const llama_ubatch * ubatch) override { - const auto rows = decision2_get_rows(*ubatch); - GGML_ASSERT(rows.options.size() == n_options); + auto rows = decision2_get_rows(*ubatch); + GGML_ASSERT(rows.options.size() <= n_options); + rows.options.resize(n_options, 0); // the scores are NaN if the batch has a decision order that cannot be used const float status_data = rows.valid || ubatch->decision_order == nullptr ? 0.0f : NAN; @@ -117,7 +123,7 @@ class llama_model_vllm_decision2::input_decision : public llm_graph_input_i { bool can_reuse(const llm_graph_params & params) override { // the values are computed again in set_input(), only the shapes must match - return decision2_get_rows(params.ubatch).options.size() == n_options; + return decision2_n_options(params.ubatch, params.n_outputs) == n_options; } ggml_tensor * options = nullptr; // I32 [n_options] @@ -129,7 +135,7 @@ class llama_model_vllm_decision2::input_decision : public llm_graph_input_i { llama_model_vllm_decision2::graph::graph(const llm_graph_params & params) : llama_model_qwen3::graph(params, no_build()), model(static_cast(*params.model)) { - auto inp_decision_ptr = std::make_unique(ubatch); + auto inp_decision_ptr = std::make_unique(ubatch, n_outputs); auto * inp_decision = inp_decision_ptr.get(); res->add_input(std::move(inp_decision_ptr)); From b052049276778d47eb216739c9e1537d764c5585 Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Sun, 22 Nov 2026 10:11:39 +0900 Subject: [PATCH 031/401] vulkan : fix memset for unaligned ranges for non-UMA devices (#32725) See https://github.com/ggml-org/llama.cpp/pull/32574 --- ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp | 18 +++++++++++++++++- tests/test-backend-tensor.cpp | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp index ed814b59feed..778d012bcb7e 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp @@ -809,9 +809,25 @@ void ggml_vk_buffer_memset(vk_buffer& dst, size_t offset, uint32_t c, size_t siz return; } + // vkCmdFillBuffer requires a 4-byte aligned offset and size, so write the unaligned ends from the matching bytes of c + const size_t end = offset + size; + const size_t begin_aligned = std::min(GGML_PAD(offset, 4), end); + const size_t end_aligned = std::max(end - end % 4, begin_aligned); + + const uint8_t * c_bytes = (const uint8_t *) &c; + if (begin_aligned > offset) { + ggml_vk_buffer_write(dst, offset, c_bytes + offset % 4, begin_aligned - offset); + } + if (end > end_aligned) { + ggml_vk_buffer_write(dst, end_aligned, c_bytes, end - end_aligned); + } + if (end_aligned == begin_aligned) { + return; + } + std::lock_guard guard(dst->device->mutex); vk_context subctx = ggml_vk_begin_sync_ctx(dst->device, dst->device->transfer_queue->cmd_pool); - subctx->s->buffer->buf.fillBuffer(dst->buffer, offset, size, c); + subctx->s->buffer->buf.fillBuffer(dst->buffer, begin_aligned, end_aligned - begin_aligned, c); ggml_vk_submit_sync(dst->device, subctx); } diff --git a/tests/test-backend-tensor.cpp b/tests/test-backend-tensor.cpp index ed617939d2ea..213275f62ff5 100644 --- a/tests/test-backend-tensor.cpp +++ b/tests/test-backend-tensor.cpp @@ -170,6 +170,25 @@ static bool test_tensor_n(ggml_backend_buffer_type_t buft) { } } + { + uint8_t expected[24], out[24] = {}; + memset(expected, 0x11, sizeof(expected)); + ggml_backend_tensor_set(t_big, expected, 0, sizeof(expected)); + + // Verify memset of unaligned ranges, such as single F16 elements. + const size_t ranges[][2] = { { 2, 2 }, { 1, 1 }, { 5, 2 }, { 9, 13 }, { 22, 2 } }; + for (const auto & range : ranges) { + const uint8_t value = (uint8_t) (0xA0 + range[0]); + memset(expected + range[0], value, range[1]); + ggml_backend_tensor_memset(t_big, value, range[0], range[1]); + } + + ggml_backend_tensor_get(t_big, out, 0, sizeof(out)); + if (memcmp(out, expected, sizeof(out)) != 0) { + return false; + } + } + { std::vector batch; ggml_backend_buffer_ptr scatter_buf = alloc_tensors(ctx.get(), buft, { 64 }, batch); From 225a5345bbb0e0c70859af5441ba922beb666fcf Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Sun, 22 Nov 2026 11:25:13 +0800 Subject: [PATCH 032/401] server : fit non-causal batches in one ubatch (#32713) --- tools/server/server-context.cpp | 4 +++- tools/server/tests/unit/test_systemone.py | 24 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index e37661a9a87a..b458a17c42fa 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -4285,7 +4285,9 @@ struct server_context_impl { if (!slot.can_split()) { // cannot fit the prompt in the current batch - will try next iter - if (batch.size() + slot.task->n_tokens() > n_batch) { + // with non-causal attention the whole batch must fit in one ubatch, see llama_decode + const int32_t n_batch_max = llama_get_causal_attn(ctx_tgt) ? n_batch : std::min(n_batch, n_ubatch); + if (batch.size() + slot.task->n_tokens() > n_batch_max) { return; } } diff --git a/tools/server/tests/unit/test_systemone.py b/tools/server/tests/unit/test_systemone.py index b0b5715e9afd..96f70632b1fc 100644 --- a/tools/server/tests/unit/test_systemone.py +++ b/tools/server/tests/unit/test_systemone.py @@ -375,6 +375,30 @@ def decide(state): assert_answers_close(a[qid], b[qid], 1e-6) +def test_systemone_noncausal_parallel(): + global server + server = ServerPreset.tinydecision("vllm-d3") + # n_batch > n_ubatch: each prompt fits in one ubatch, but several of them do not + server.n_batch = 2048 + server.n_ubatch = 512 + server.n_slots = 4 + server.start() + state = " ".join(f"The order {i} arrived damaged and the customer wants a replacement." for i in range(14)) + questions = {"angry": TEST_QUESTIONS["angry"]} + + def decide(): + res = server.make_request("POST", "/v1/systemone", data={"state": state, "questions": questions}) + assert res.status_code == 200 + assert res.body["usage"]["input_tokens"] > 512 // 2 + return res.body["answers"] + + # a non-causal batch is evaluated in one ubatch, the concurrent prompts are spread over several batches + single = decide() + parallel = parallel_function_calls([(decide, ()) for _ in range(4)]) + for answers in parallel: + assert_answers_close(single["angry"], answers["angry"], 1e-6) + + def test_systemone_d1_special_tokens(): global server server = ServerPreset.tinydecision("lfm3-d1-omni") From 8a97fa98ab1a454709bbf5ac979661feaeadec40 Mon Sep 17 00:00:00 2001 From: Revertron <105154+Revertron@users.noreply.github.com> Date: Sun, 22 Nov 2026 07:28:46 +0100 Subject: [PATCH 033/401] vulkan : support non-contiguous src in SCALE (#32735) Assisted-By: Opus 5.5 --- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 2 +- ggml/src/ggml-vulkan/vulkan-shaders/scale.comp | 2 +- tests/test-backend-ops.cpp | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index ae5a05c72e38..efb644793eb1 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -17046,7 +17046,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm case GGML_OP_SLEEP: return device->shader_clock; case GGML_OP_SCALE: - return ggml_is_contiguous(op->src[0]) && ggml_vk_is_float_elementwise(op); + return ggml_vk_is_float_elementwise(op); case GGML_OP_PAD: case GGML_OP_PAD_REFLECT_1D: case GGML_OP_ROLL: diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp b/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp index 83ee31a72960..0313f2fed90a 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/scale.comp @@ -18,7 +18,7 @@ void main() { continue; } - data_d[get_doffset() + idx] = FLOAT_TO_D(A_TO_FLOAT(data_a[get_aoffset() + idx]) * FLOAT_TYPE(p.param1) + FLOAT_TYPE(p.param2)); + data_d[get_doffset() + dst_idx(idx)] = FLOAT_TO_D(A_TO_FLOAT(data_a[get_aoffset() + src0_idx(idx)]) * FLOAT_TYPE(p.param1) + FLOAT_TYPE(p.param2)); idx += num_threads; } } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index e377277a485b..9b8d7015c8a5 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -11758,6 +11758,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_scale(GGML_TYPE_F32, {10, 10, 10, 10}, 2.0f, 1.0f, false, 1)); // view test test_cases.emplace_back(new test_scale(GGML_TYPE_F32, {10, 10, 10, 10}, 2.0f, 1.0f, true, 1)); // view test, inplace test_cases.emplace_back(new test_scale(GGML_TYPE_BF16, {10, 10, 10, 10}, 2.0f, 1.0f, true, 1)); // view test, inplace + test_cases.emplace_back(new test_scale(GGML_TYPE_F16, {10, 10, 10, 10}, 2.0f, 1.0f, false, 1)); // view test test_cases.emplace_back(new test_softcap(GGML_TYPE_F32, {10, 10, 10, 10}, 50.0f)); test_cases.emplace_back(new test_silu_back()); From 1fb8a269603b497fc1ce7dab2f2fc5c1be7a51cb Mon Sep 17 00:00:00 2001 From: shaofeiqi Date: Sun, 22 Nov 2026 00:01:14 -0800 Subject: [PATCH 034/401] opencl: add coopmat GEMM for Adreno 850 (Q4_0, Q5_0, Q8_0, Q4_K, Q5_K, Q6_K) (#32686) * opencl: add Q4_0 coopmat GEMM for Adreno 850 Assisted-by: Claude Opus 5.5 * opencl: add Q5_0 coopmat GEMM for Adreno 850 * opencl: add Q8_0 coopmat GEMM for Adreno 850 * opencl: add Q4_K coopmat GEMM for Adreno 850 * opencl: add Q5_K coopmat GEMM for Adreno 850 * opencl: add Q6_K coopmat GEMM for Adreno 850 --- ggml/src/ggml-opencl/CMakeLists.txt | 7 + ggml/src/ggml-opencl/ggml-opencl.cpp | 223 +++++++++++++++++- .../gemm_noshuffle_q4_0_f32_coopmat.cl | 145 ++++++++++++ .../gemm_noshuffle_q4_k_f32_coopmat.cl | 148 ++++++++++++ .../gemm_noshuffle_q5_0_f32_coopmat.cl | 157 ++++++++++++ .../gemm_noshuffle_q5_k_f32_coopmat.cl | 164 +++++++++++++ .../gemm_noshuffle_q6_k_f32_coopmat.cl | 145 ++++++++++++ .../gemm_noshuffle_q8_0_f32_coopmat.cl | 157 ++++++++++++ .../ggml-opencl/kernels/pack_b_f16_coopmat.cl | 48 ++++ 9 files changed, 1190 insertions(+), 4 deletions(-) create mode 100644 ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_0_f32_coopmat.cl create mode 100644 ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32_coopmat.cl create mode 100644 ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32_coopmat.cl create mode 100644 ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32_coopmat.cl create mode 100644 ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32_coopmat.cl create mode 100644 ggml/src/ggml-opencl/kernels/gemm_noshuffle_q8_0_f32_coopmat.cl create mode 100644 ggml/src/ggml-opencl/kernels/pack_b_f16_coopmat.cl diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index 325f5c4bfc75..aadf5ddb3321 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -227,6 +227,13 @@ set(GGML_OPENCL_KERNELS gemm_coopk_q4_0_q8_1_dp4a gemm_coopk_q4_k_q8_1_dp4a gemm_coopk_q6_k_q8_1_dp4a + pack_b_f16_coopmat + gemm_noshuffle_q4_0_f32_coopmat + gemm_noshuffle_q5_0_f32_coopmat + gemm_noshuffle_q8_0_f32_coopmat + gemm_noshuffle_q4_k_f32_coopmat + gemm_noshuffle_q5_k_f32_coopmat + gemm_noshuffle_q6_k_f32_coopmat quant_a_q8_1 gemv_moe_q4_k_f32_ns gemm_moe_q5_k_f32_ns diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 894f8235e9a0..d35c6d047167 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1495,6 +1495,13 @@ struct ggml_backend_opencl_context { cl_kernel kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a = nullptr; // dp4a (int8) dense IQ4_NL prefill GEMM cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a = nullptr; // dp4a (int8) dense q4_0 prefill GEMM cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 = nullptr; + cl_kernel kernel_pack_b_f16_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q4_0_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q5_0_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q8_0_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q5_k_f32_coopmat = nullptr; + cl_kernel kernel_gemm_noshuffle_q6_k_f32_coopmat = nullptr; cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c4 = nullptr; cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 = nullptr; int nsg_coopk_dp4a_q4_0 = 8; @@ -1979,6 +1986,137 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx } } +static void load_cl_kernels_coopmat(ggml_backend_opencl_context * backend_ctx) { + if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO || !strstr(backend_ctx->device_name.c_str(), "850")) { + return; + } + + cl_int err; + const std::string opts = "-cl-std=CL" + std::to_string(backend_ctx->opencl_c_version.major) + "." + + std::to_string(backend_ctx->opencl_c_version.minor) + + (backend_ctx->adreno_use_large_buffer ? " -qcom-enable-large-buffer" : ""); + + // pack_b_f16_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "pack_b_f16_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("pack_b_f16_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (!prog) { + return; + } + CL_CHECK((backend_ctx->kernel_pack_b_f16_coopmat = clCreateKernel(prog, "kernel_pack_b_f16_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q4_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q5_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q8_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q8_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q8_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q4_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q5_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q6_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q6_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } +} + #endif static std::string ggml_opencl_make_compile_opts(const ggml_backend_opencl_context * backend_ctx) { @@ -7813,6 +7951,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { } } load_cl_kernels_gemm_coopk(backend_ctx); + load_cl_kernels_coopmat(backend_ctx); #endif // GGML_OPENCL_USE_ADRENO_KERNELS GGML_LOG_CONT("\n"); backend_ctx->kernels_loaded = true; @@ -11739,7 +11878,8 @@ inline bool use_q4_0_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat)) { return false; } @@ -11893,7 +12033,8 @@ inline bool use_q6_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q6_k_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat)) { return false; } // bin kernels require ne2 == 1 and ne3 == 1 for weights @@ -11911,7 +12052,8 @@ inline bool use_q4_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q4_k_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat)) { return false; } // bin kernels require ne2 == 1 and ne3 == 1 for weights @@ -11929,7 +12071,8 @@ inline bool use_q5_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, #ifdef GGML_OPENCL_USE_ADRENO_KERNELS if (!backend_ctx->kernel_gemv_noshuffle_q5_k_f32_32b_trans || !(backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin)) { + backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin || + backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat)) { return false; } return (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0); @@ -25619,6 +25762,48 @@ static void ggml_cl_mul_mat_q2_0_f32_adreno(ggml_backend_t backend, const ggml_t CL_CHECK(clReleaseMemObject(b_sub_buf)); } +static bool ggml_cl_mul_mat_coopmat(ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, + std::initializer_list weights, + const ggml_tensor * src1, ggml_tensor * dst, int K, int M, int N) { + if (kernel == nullptr || M % 64 != 0 || N < 2) { + return false; + } + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int n_tiles = CEIL_DIV(N, 64); + + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, (size_t)n_tiles * 64 * K * sizeof(cl_half)); + + cl_kernel pk = backend_ctx->kernel_pack_b_f16_coopmat; + CL_CHECK(clSetKernelArg(pk, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(pk, 1, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(pk, 2, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); + CL_CHECK(clSetKernelArg(pk, 3, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(pk, 4, sizeof(int), &N)); + size_t p_local[2] = { 64, 4 }; + size_t p_global[2] = { (size_t)n_tiles * 64, (size_t)CEIL_DIV(K, 64) * 4 }; + backend_ctx->enqueue_ndrange_kernel(pk, 2, p_global, p_local, dst); + + cl_uint ka = 0; + for (cl_mem w : weights) { + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &w)); + } + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &N)); + + size_t c_local[3] = { 64, 1, 4 }; + size_t c_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(n_tiles, 4) * 4 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, c_global, c_local, dst); + return true; +} + static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); @@ -25934,6 +26119,11 @@ static void ggml_cl_mul_mat_q4_0_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q4_0_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat, + { extra0_q4_0->q, extra0_q4_0->d }, src1, dst, K, M, N)) { + return; + } + if (use_bin) { if (use_q40_mc3) { static bool warned = false; @@ -26498,6 +26688,11 @@ static void ggml_cl_mul_mat_q5_0_f32_adreno(ggml_backend_t backend, const ggml_t int N = ne1; int K = ne00; + if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat, + { extra0_q5_0->qs, extra0_q5_0->qh, extra0_q5_0->d }, src1, dst, K, M, N)) { + return; + } + if (ne1 == 1) { cl_mem qs_img = nullptr; cl_mem b_sub_buf = nullptr; @@ -27340,6 +27535,11 @@ static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_t int N = ne1; int K = ne00; + if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat, + { extra0_q8_0->q, extra0_q8_0->d }, src1, dst, K, M, N)) { + return; + } + // Multi-column verify GEMV for ne1 2..4, reuses the ne1 == 1 image setup. // Default on for X2E, GGML_OPENCL_Q8_0_MC=0/1 forces it. static const char * q8_mc_env = getenv("GGML_OPENCL_Q8_0_MC"); @@ -28321,6 +28521,11 @@ static void ggml_cl_mul_mat_q4_k_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q4_k_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat, + { extra0_q4_k->q, extra0_q4_k->s, extra0_q4_k->d, extra0_q4_k->dm }, src1, dst, K, M, N)) { + return; + } + if (use_bin) { if (use_mc3) { static bool warned = false; @@ -29231,6 +29436,11 @@ static void ggml_cl_mul_mat_q6_K_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q6_k_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat, + { extra0_q6_K->ql, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, src1, dst, ne00, ne01, ne1)) { + return; + } + if (use_bin) { if (use_q6k_mc3 || use_q6k_tiled_mc) { static bool warned = false; @@ -29971,6 +30181,11 @@ static void ggml_cl_mul_mat_q5_K_f32_adreno(ggml_backend_t backend, const ggml_t const bool use_bin = use_q5_k_bin_kernels(backend_ctx, src0); + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat, + { extra0_q5_k->q, extra0_q5_k->qh, extra0_q5_k->s, extra0_q5_k->d, extra0_q5_k->dm }, src1, dst, K, M, N)) { + return; + } + if (use_bin) { if (use_q5k_mc3) { static bool warned = false; diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_0_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_0_f32_coopmat.cl new file mode 100644 index 000000000000..56210a1ad814 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_0_f32_coopmat.cl @@ -0,0 +1,145 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q4_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, half d) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1032.0h)) * d; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define LOAD_Q(qv, dd, o) { \ + qv.s0 = qp[(4 * (o) + 0) * M]; \ + qv.s1 = qp[(4 * (o) + 1) * M]; \ + qv.s2 = qp[(4 * (o) + 2) * M]; \ + qv.s3 = qp[(4 * (o) + 3) * M]; \ + dd = dp[(o) * M]; } + +#define MMA_K32(qv, dd, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(qv.s0, dd), dequant8(qv.s1, dd)); \ + ua1.h = (half16)(dequant8(qv.s2, dd), dequant8(qv.s3, dd)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q4_0_f32_coopmat( + global const uint * src0_q, // A: q4_0 quants, [K/8][M] u32 + global const half * src0_d, // A: q4_0 scales, [K/32][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + global const uint * qp = src0_q + row + lane; + global const half * dp = src0_d + row + lane; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + + { + const int odd = (K / 32) & 1; + const int ob = odd ? 0 : 1; + uint4 qa; + uint4 qb; + half da; + half db; + LOAD_Q(qa, da, 0) + LOAD_Q(qb, db, ob) + da = odd ? 0.0h : da; + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + ob * 2048) + qp += (ob + 1) * 4 * M; + dp += (ob + 1) * M; + bp += (ob + 1) * 2048; + } + +#pragma unroll 1 + for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) { + uint4 qa; + uint4 qb; + half da; + half db; + LOAD_Q(qa, da, 0) + LOAD_Q(qb, db, 1) + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + 2048) + qp += 8 * M; + dp += 2 * M; + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32_coopmat.cl new file mode 100644 index 000000000000..65f29309f8ab --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q4_k_f32_coopmat.cl @@ -0,0 +1,148 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q4_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +#define K_SCALE_SIZE 12 + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, half scale, half nminv) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1024.0h)) * scale + nminv; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define MMA_K32(q0, q1, q2, q3, sc, nm, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(q0, sc, nm), dequant8(q1, sc, nm)); \ + ua1.h = (half16)(dequant8(q2, sc, nm), dequant8(q3, sc, nm)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +#define STEP64(sa, na, sb_, nb_) { \ + uint8 qv; \ + qv.s0 = qp[0]; \ + qv.s1 = qp[M]; \ + qv.s2 = qp[2 * M]; \ + qv.s3 = qp[3 * M]; \ + qv.s4 = qp[4 * M]; \ + qv.s5 = qp[5 * M]; \ + qv.s6 = qp[6 * M]; \ + qv.s7 = qp[7 * M]; \ + qp += 8 * M; \ + MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, sa, na, bp) \ + MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, sb_, nb_, bp + 2048) \ + bp += 4096; } + +kernel void kernel_gemm_noshuffle_q4_k_f32_coopmat( + global const uint * src0_q, // A: q4_K quants, [K/8][M] u32 + global const uchar * src0_s, // A: 6-bit scale/min codes, [K/256*12][M] u8 + global const half * src0_d, // A: per-superblock scale, [K/256][M] f16 + global const half * src0_dm, // A: per-superblock min, [K/256][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + const int lrow = row + lane; + + global const uint * qp = src0_q + lrow; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + +#pragma unroll 1 + for (int k0 = 0; k0 < K; k0 += 128) { + const int sb = k0 >> 8; + const half dd = src0_d [(ulong)sb * M + lrow]; + const half dmm = src0_dm[(ulong)sb * M + lrow]; + + global const uchar * sp = src0_s + (ulong)(sb * K_SCALE_SIZE) * M + lrow; + const uchar4 c0 = (uchar4)(sp[0], sp[M], sp[2 * M], sp[3 * M]); + const uchar4 c1 = (uchar4)(sp[4 * M], sp[5 * M], sp[6 * M], sp[7 * M]); + const uchar4 c2 = (uchar4)(sp[8 * M], sp[9 * M], sp[10 * M], sp[11 * M]); + const uchar4 sl = c0 & (uchar)0x3F; + const uchar4 ml = c1 & (uchar)0x3F; + const uchar4 sh = (c2 & (uchar)0x0F) | ((c0 >> (uchar)2) & (uchar)0x30); + const uchar4 mh = (c2 >> (uchar)4) | ((c1 >> (uchar)2) & (uchar)0x30); + const int hi = (k0 >> 7) & 1; + const half4 S = dd * convert_half4(hi ? sh : sl); + const half4 Nm = -(dmm * convert_half4(hi ? mh : ml)); + + STEP64(S.s0, Nm.s0, S.s1, Nm.s1) + STEP64(S.s2, Nm.s2, S.s3, Nm.s3) + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32_coopmat.cl new file mode 100644 index 000000000000..1880a86f0e2c --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_0_f32_coopmat.cl @@ -0,0 +1,157 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q5_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, uint h, half d) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000) | ((h << 4) & 0x0010) | ((h << 19) & 0x00100000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000) | ((h << 2) & 0x0010) | ((h << 17) & 0x00100000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000) | ( h & 0x0010) | ((h << 15) & 0x00100000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000) | ((h >> 2) & 0x0010) | ((h << 13) & 0x00100000); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1040.0h)) * d; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define LOAD_Q(qv, hv, dd, o) { \ + qv.s0 = (uint)qp[(8 * (o) + 0) * M] | ((uint)qp[(8 * (o) + 1) * M] << 16); \ + qv.s1 = (uint)qp[(8 * (o) + 2) * M] | ((uint)qp[(8 * (o) + 3) * M] << 16); \ + qv.s2 = (uint)qp[(8 * (o) + 4) * M] | ((uint)qp[(8 * (o) + 5) * M] << 16); \ + qv.s3 = (uint)qp[(8 * (o) + 6) * M] | ((uint)qp[(8 * (o) + 7) * M] << 16); \ + hv.s0 = hp[(4 * (o) + 0) * M]; \ + hv.s1 = hp[(4 * (o) + 1) * M]; \ + hv.s2 = hp[(4 * (o) + 2) * M]; \ + hv.s3 = hp[(4 * (o) + 3) * M]; \ + dd = dp[(o) * M]; } + +#define MMA_K32(qv, hv, dd, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(qv.s0, hv.s0, dd), dequant8(qv.s1, hv.s1, dd)); \ + ua1.h = (half16)(dequant8(qv.s2, hv.s2, dd), dequant8(qv.s3, hv.s3, dd)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q5_0_f32_coopmat( + global const ushort * src0_q, // A: q5_0 quants, [K/4][M] u16 + global const uchar * src0_qh, // A: q5_0 high bits, [K/8][M] u8 + global const half * src0_d, // A: q5_0 scales, [K/32][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + global const ushort * qp = src0_q + row + lane; + global const uchar * hp = src0_qh + row + lane; + global const half * dp = src0_d + row + lane; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + + { + const int odd = (K / 32) & 1; + const int ob = odd ? 0 : 1; + uint4 qa; + uint4 qb; + uint4 ha; + uint4 hb; + half da; + half db; + LOAD_Q(qa, ha, da, 0) + LOAD_Q(qb, hb, db, ob) + da = odd ? 0.0h : da; + MMA_K32(qa, ha, da, bp) + MMA_K32(qb, hb, db, bp + ob * 2048) + qp += (ob + 1) * 8 * M; + hp += (ob + 1) * 4 * M; + dp += (ob + 1) * M; + bp += (ob + 1) * 2048; + } + +#pragma unroll 1 + for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) { + uint4 qa; + uint4 qb; + uint4 ha; + uint4 hb; + half da; + half db; + LOAD_Q(qa, ha, da, 0) + LOAD_Q(qb, hb, db, 1) + MMA_K32(qa, ha, da, bp) + MMA_K32(qb, hb, db, bp + 2048) + qp += 16 * M; + hp += 8 * M; + dp += 2 * M; + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32_coopmat.cl new file mode 100644 index 000000000000..2b4f11780a57 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q5_k_f32_coopmat.cl @@ -0,0 +1,164 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q5_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +#define K_SCALE_SIZE 12 + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, uint h, half scale, half nminv) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t.s0 |= ((h & 0x01u) << 4) | ((h & 0x02u) << 19); + t.s1 |= ((h & 0x04u) << 2) | ((h & 0x08u) << 17); + t.s2 |= ( h & 0x10u ) | ((h & 0x20u) << 15); + t.s3 |= ((h & 0x40u) >> 2) | ((h & 0x80u) << 13); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1024.0h)) * scale + nminv; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define MMA_K32(q0, q1, q2, q3, h0_, h1_, h2_, h3_, sc, nm, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(q0, h0_, sc, nm), dequant8(q1, h1_, sc, nm)); \ + ua1.h = (half16)(dequant8(q2, h2_, sc, nm), dequant8(q3, h3_, sc, nm)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +#define STEP64(sa, na, sb_, nb_) { \ + uint8 qv; \ + qv.s0 = qp[0]; \ + qv.s1 = qp[M]; \ + qv.s2 = qp[2 * M]; \ + qv.s3 = qp[3 * M]; \ + qv.s4 = qp[4 * M]; \ + qv.s5 = qp[5 * M]; \ + qv.s6 = qp[6 * M]; \ + qv.s7 = qp[7 * M]; \ + qp += 8 * M; \ + uint8 hv; \ + hv.s0 = qhp[0]; \ + hv.s1 = qhp[M]; \ + hv.s2 = qhp[2 * M]; \ + hv.s3 = qhp[3 * M]; \ + hv.s4 = qhp[4 * M]; \ + hv.s5 = qhp[5 * M]; \ + hv.s6 = qhp[6 * M]; \ + hv.s7 = qhp[7 * M]; \ + qhp += 8 * M; \ + MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, hv.s0, hv.s1, hv.s2, hv.s3, sa, na, bp) \ + MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, hv.s4, hv.s5, hv.s6, hv.s7, sb_, nb_, bp + 2048) \ + bp += 4096; } + +kernel void kernel_gemm_noshuffle_q5_k_f32_coopmat( + global const uint * src0_q, // A: q5_K low nibbles, [K/8][M] u32 + global const uchar * src0_qh, // A: q5_K high bits, [K/8][M] u8 + global const uchar * src0_s, // A: 6-bit scale/min codes, [K/256*12][M] u8 + global const half * src0_d, // A: per-superblock scale, [K/256][M] f16 + global const half * src0_dm, // A: per-superblock min, [K/256][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + const int lrow = row + lane; + + global const uint * qp = src0_q + lrow; + global const uchar * qhp = src0_qh + lrow; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + +#pragma unroll 1 + for (int k0 = 0; k0 < K; k0 += 128) { + const int sb = k0 >> 8; + const half dd = src0_d [(ulong)sb * M + lrow]; + const half dmm = src0_dm[(ulong)sb * M + lrow]; + + global const uchar * sp = src0_s + (ulong)(sb * K_SCALE_SIZE) * M + lrow; + const uchar4 c0 = (uchar4)(sp[0], sp[M], sp[2 * M], sp[3 * M]); + const uchar4 c1 = (uchar4)(sp[4 * M], sp[5 * M], sp[6 * M], sp[7 * M]); + const uchar4 c2 = (uchar4)(sp[8 * M], sp[9 * M], sp[10 * M], sp[11 * M]); + const uchar4 sl = c0 & (uchar)0x3F; + const uchar4 ml = c1 & (uchar)0x3F; + const uchar4 sh = (c2 & (uchar)0x0F) | ((c0 >> (uchar)2) & (uchar)0x30); + const uchar4 mh = (c2 >> (uchar)4) | ((c1 >> (uchar)2) & (uchar)0x30); + const int hi = (k0 >> 7) & 1; + const half4 S = dd * convert_half4(hi ? sh : sl); + const half4 Nm = -(dmm * convert_half4(hi ? mh : ml)); + + STEP64(S.s0, Nm.s0, S.s1, Nm.s1) + STEP64(S.s2, Nm.s2, S.s3, Nm.s3) + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32_coopmat.cl new file mode 100644 index 000000000000..5c517f94db07 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q6_k_f32_coopmat.cl @@ -0,0 +1,145 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q6_K x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half8 dequant8(uint v, uint hh, half scale) { + uint4 t; + t.s0 = ( v & 0x000F) | ((v << 12) & 0x000F0000); + t.s1 = ((v >> 8) & 0x000F) | ((v << 4) & 0x000F0000); + t.s2 = ((v >> 16) & 0x000F) | ((v >> 4) & 0x000F0000); + t.s3 = ((v >> 24) & 0x000F) | ((v >> 12) & 0x000F0000); + t.s0 |= ((hh & 0x0003u) << 4) | ((hh & 0x000Cu) << 18); + t.s1 |= ( hh & 0x0030u ) | ((hh & 0x00C0u) << 14); + t.s2 |= ((hh & 0x0300u) >> 4) | ((hh & 0x0C00u) << 10); + t.s3 |= ((hh & 0x3000u) >> 8) | ((hh & 0xC000u) << 6); + t |= (uint4)(0x64006400); + + return (as_half8(t) - (half8)(1056.0h)) * scale; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define MMA_K32(q0, q1, q2, q3, hA, hB, sc0, sc1, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant8(q0, (hA), sc0), dequant8(q1, (hA) >> 16, sc0)); \ + ua1.h = (half16)(dequant8(q2, (hB), sc1), dequant8(q3, (hB) >> 16, sc1)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q6_k_f32_coopmat( + global const uint * src0_ql, // A: q6_K low nibbles, [K/8][M] u32 + global const uint * src0_qh, // A: q6_K high 2-bit, [K/16][M] u32 + global const uint * src0_s, // A: int8 sub-scales, [M][K/16] (4 per u32) + global const half * src0_d, // A: per-superblock scale, [K/256][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + const int lrow = row + lane; + + global const uint * qp = src0_ql + lrow; + global const uint * qhp = src0_qh + lrow; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + global const uint * sp = src0_s + (ulong)lrow * (K / 64); + + mat_c_t acc = qcom_coop_mat_init(0.0); + +#pragma unroll 1 + for (int k0 = 0; k0 < K; k0 += 64) { + const half dd = src0_d[(ulong)(k0 >> 8) * M + lrow]; + + const half4 g = convert_half4(as_char4(sp[0])) * dd; + sp += 1; + + uint8 qv; + qv.s0 = qp[0]; + qv.s1 = qp[M]; + qv.s2 = qp[2 * M]; + qv.s3 = qp[3 * M]; + qv.s4 = qp[4 * M]; + qv.s5 = qp[5 * M]; + qv.s6 = qp[6 * M]; + qv.s7 = qp[7 * M]; + qp += 8 * M; + + uint4 hv; + hv.s0 = qhp[0]; + hv.s1 = qhp[M]; + hv.s2 = qhp[2 * M]; + hv.s3 = qhp[3 * M]; + qhp += 4 * M; + + MMA_K32(qv.s0, qv.s1, qv.s2, qv.s3, hv.s0, hv.s1, g.s0, g.s1, bp) + MMA_K32(qv.s4, qv.s5, qv.s6, qv.s7, hv.s2, hv.s3, g.s2, g.s3, bp + 2048) + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q8_0_f32_coopmat.cl b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q8_0_f32_coopmat.cl new file mode 100644 index 000000000000..e0a86a15fcb3 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_noshuffle_q8_0_f32_coopmat.cl @@ -0,0 +1,157 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#pragma OPENCL EXTENSION cl_qcom_kernel_cooperative_matrix : enable + +// Q8_0 x F32 GEMM with cl_qcom_kernel_cooperative_matrix: one 64x64 f16 C tile per wave, +// A dequantized in registers, B packed by kernel_pack_b_f16_coopmat. + +typedef half mat_a_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 16, CLK_COOPERATIVE_MATRIX_A_QCOM))); +typedef half mat_b_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 16, 64, CLK_COOPERATIVE_MATRIX_B_QCOM))); +typedef half mat_c_t __attribute__((qcom_coop_mat(CLK_COOPERATIVE_MATRIX_SCOPE_SUBGROUP_QCOM, 64, 64, CLK_COOPERATIVE_MATRIX_ACCUMULATOR_QCOM))); + +typedef half half1024 __attribute__((ext_vector_type(1024))); +typedef half half4096 __attribute__((ext_vector_type(4096))); + +typedef union { + half1024 v; + half16 h; +} a_row_t; + +typedef union { + half4096 v; + struct { + half16 h0; + half16 h1; + half16 h2; + half16 h3; + } s; +} c_row_t; + +inline half4 dequant4(uint v, half d) { + return convert_half4(as_char4(v)) * d; +} + +inline void store_c16(global float * p, half16 h, int j0, int nv, int M) { + float16 f = convert_float16(h); + if (j0 + 0 < nv) p[(ulong)(j0 + 0) * M] = f.s0; + if (j0 + 1 < nv) p[(ulong)(j0 + 1) * M] = f.s1; + if (j0 + 2 < nv) p[(ulong)(j0 + 2) * M] = f.s2; + if (j0 + 3 < nv) p[(ulong)(j0 + 3) * M] = f.s3; + if (j0 + 4 < nv) p[(ulong)(j0 + 4) * M] = f.s4; + if (j0 + 5 < nv) p[(ulong)(j0 + 5) * M] = f.s5; + if (j0 + 6 < nv) p[(ulong)(j0 + 6) * M] = f.s6; + if (j0 + 7 < nv) p[(ulong)(j0 + 7) * M] = f.s7; + if (j0 + 8 < nv) p[(ulong)(j0 + 8) * M] = f.s8; + if (j0 + 9 < nv) p[(ulong)(j0 + 9) * M] = f.s9; + if (j0 + 10 < nv) p[(ulong)(j0 + 10) * M] = f.sa; + if (j0 + 11 < nv) p[(ulong)(j0 + 11) * M] = f.sb; + if (j0 + 12 < nv) p[(ulong)(j0 + 12) * M] = f.sc; + if (j0 + 13 < nv) p[(ulong)(j0 + 13) * M] = f.sd; + if (j0 + 14 < nv) p[(ulong)(j0 + 14) * M] = f.se; + if (j0 + 15 < nv) p[(ulong)(j0 + 15) * M] = f.sf; +} + +#define LOAD_Q(qv, dd) { \ + qv.s0 = qp[0]; \ + qv.s1 = qp[M]; \ + qv.s2 = qp[2 * M]; \ + qv.s3 = qp[3 * M]; \ + qv.s4 = qp[4 * M]; \ + qv.s5 = qp[5 * M]; \ + qv.s6 = qp[6 * M]; \ + qv.s7 = qp[7 * M]; \ + dd = dp[0]; \ + qp += 8 * M; \ + dp += M; } + +#define MMA_K32(qv, dd, b) { \ + a_row_t ua0; \ + a_row_t ua1; \ + ua0.h = (half16)(dequant4(qv.s0, dd), dequant4(qv.s1, dd), dequant4(qv.s2, dd), dequant4(qv.s3, dd)); \ + ua1.h = (half16)(dequant4(qv.s4, dd), dequant4(qv.s5, dd), dequant4(qv.s6, dd), dequant4(qv.s7, dd)); \ + mat_a_t a0 = __builtin_astype(ua0.v, mat_a_t); \ + mat_a_t a1 = __builtin_astype(ua1.v, mat_a_t); \ + mat_b_t b0 = qcom_coop_mat_load((b), CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + mat_b_t b1 = qcom_coop_mat_load((b) + 1024, CLK_COOPERATIVE_MATRIX_LAYOUT_COLUMN_MAJOR_QCOM, 16); \ + acc = qcom_coop_mat_mulAdd(a0, b0, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); \ + acc = qcom_coop_mat_mulAdd(a1, b1, acc, CLK_COOPERATIVE_MATRIX_OPERAND_NONE_QCOM); } + +kernel void kernel_gemm_noshuffle_q8_0_f32_coopmat( + global const uint * src0_q, // A: q8_0 quants, [K/4][M] u32 + global const half * src0_d, // A: q8_0 scales, [K/32][M] f16 + global const half * src1, // B: packed f16 tiles + global char * dst, // C: [N][M] f32 + ulong offsetd, + int K, + int M, + int N +) { + const int lane = get_local_id(0); + const int row = get_global_id(1) * 64; + const int tn = get_global_id(2); + const int n_tiles = (N + 63) / 64; + + if (tn >= n_tiles) { + return; + } + + global const uint * qp = src0_q + row + lane; + global const half * dp = src0_d + row + lane; + global const half * bp = src1 + (ulong)tn * (K / 16) * 1024; + + mat_c_t acc = qcom_coop_mat_init(0.0); + + { + const int odd = (K / 32) & 1; + const int kb = odd ? 0 : 32; + uint8 qa; + uint8 qb; + half da; + half db; + qa.s0 = qp[0]; + qa.s1 = qp[M]; + qa.s2 = qp[2 * M]; + qa.s3 = qp[3 * M]; + qa.s4 = qp[4 * M]; + qa.s5 = qp[5 * M]; + qa.s6 = qp[6 * M]; + qa.s7 = qp[7 * M]; + da = odd ? 0.0h : dp[0]; + qb.s0 = qp[(kb / 4 + 0) * M]; + qb.s1 = qp[(kb / 4 + 1) * M]; + qb.s2 = qp[(kb / 4 + 2) * M]; + qb.s3 = qp[(kb / 4 + 3) * M]; + qb.s4 = qp[(kb / 4 + 4) * M]; + qb.s5 = qp[(kb / 4 + 5) * M]; + qb.s6 = qp[(kb / 4 + 6) * M]; + qb.s7 = qp[(kb / 4 + 7) * M]; + db = dp[(kb / 32) * M]; + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + (kb / 16) * 1024) + qp += (kb / 4 + 8) * M; + dp += (kb / 32 + 1) * M; + bp += (kb / 16 + 2) * 1024; + } + +#pragma unroll 1 + for (int k0 = (K / 32) & 1 ? 32 : 64; k0 < K; k0 += 64) { + uint8 qa; + uint8 qb; + half da; + half db; + LOAD_Q(qa, da) + LOAD_Q(qb, db) + MMA_K32(qa, da, bp) + MMA_K32(qb, db, bp + 2048) + bp += 4096; + } + + c_row_t uc; + uc.v = __builtin_astype(acc, half4096); + + global float * p = (global float *)(dst + offsetd) + (ulong)tn * 64 * M + row + lane; + const int nv = N - tn * 64; + store_c16(p, uc.s.h0, 0, nv, M); + store_c16(p, uc.s.h1, 16, nv, M); + store_c16(p, uc.s.h2, 32, nv, M); + store_c16(p, uc.s.h3, 48, nv, M); +} diff --git a/ggml/src/ggml-opencl/kernels/pack_b_f16_coopmat.cl b/ggml/src/ggml-opencl/kernels/pack_b_f16_coopmat.cl new file mode 100644 index 000000000000..3f60223b842c --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/pack_b_f16_coopmat.cl @@ -0,0 +1,48 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +// Pack B f32 [N][K] into f16 64x16 tiles (column-major, ld 16) at (tn * (K/16) + ks) * 1024. +// Columns >= N are zero. A workgroup (64, 4) packs 64 columns x 64 k. +#define PACK_LDS (64 + 8) + +kernel void kernel_pack_b_f16_coopmat( + global const char * src1, + ulong offset1, + global half * dst, + int K, + int N +) { + local half tile[64 * PACK_LDS]; + + const int l = get_local_id(1) * 64 + get_local_id(0); + const int tn = get_group_id(0); + const int kt = get_group_id(1); + const int k0 = kt * 64; + + global const float * src = (global const float *)(src1 + offset1); + + for (int j = 0; j < 4; j++) { + const int f = j * 256 + l; + const int r = f >> 4; + const int c = (f & 15) * 4; + const int n = tn * 64 + r; + float4 v = (float4)(0.0f); + if (n < N && k0 + c < K) { + v = vload4(0, src + (ulong)n * K + k0 + c); + } + vstore_half4(v, 0, tile + r * PACK_LDS + c); + } + + barrier(CLK_LOCAL_MEM_FENCE); + + global half * out = dst + ((ulong)tn * (K / 16) + kt * 4) * 1024; + for (int j = 0; j < 2; j++) { + const int q = j * 256 + l; + const int ks = q >> 7; + const int n = (q >> 1) & 63; + const int h = q & 1; + if (kt * 4 + ks < K / 16) { + half8 v = vload8(0, tile + n * PACK_LDS + ks * 16 + h * 8); + vstore8(v, 0, out + q * 8); + } + } +} From 5d28d64bf2969d7b9c863e5001de83b30ce81557 Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Sun, 22 Nov 2026 17:07:48 +0900 Subject: [PATCH 035/401] ggml-webgpu : Update to a recent version of Dawn (#32779) Dawn v20260908.214631 doesn't compile with emsdk latest, that is 7.0.1. --- .github/workflows/build-wasm.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-wasm.yml b/.github/workflows/build-wasm.yml index bfe57033e899..b2181271a357 100644 --- a/.github/workflows/build-wasm.yml +++ b/.github/workflows/build-wasm.yml @@ -72,7 +72,7 @@ jobs: - name: Fetch emdawnwebgpu run: | - DAWN_TAG="v20260908.214631" + DAWN_TAG="v20261120.121236" EMDAWN_PKG="emdawnwebgpu_pkg-${DAWN_TAG}.zip" echo "Downloading ${EMDAWN_PKG}" curl -L -o emdawn.zip \ From e300919cc704ddde3a8a8346a8714f57eeeee71b Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Sun, 22 Nov 2026 17:08:21 +0900 Subject: [PATCH 036/401] webgpu : update GDN supports_op check (#32782) --- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 75527b111f6a..3fd8a66727c1 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -5262,7 +5262,8 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32 && src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 && op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 && - s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup && + ggml_are_same_stride(src0, src1); } break; case GGML_OP_CLAMP: From 8cb0d98ccd0a310879ae8eaa1ce2c41e4b40a052 Mon Sep 17 00:00:00 2001 From: Eddie Zhou Date: Sun, 22 Nov 2026 04:06:12 -0700 Subject: [PATCH 037/401] HIP: fix double halving of NVFP4 scales on CDNA3 (#32790) Fixes #32789 --- ggml/src/ggml-cuda/common.cuh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml-cuda/common.cuh b/ggml/src/ggml-cuda/common.cuh index 8cd2366ed907..5b3c32858c4a 100644 --- a/ggml/src/ggml-cuda/common.cuh +++ b/ggml/src/ggml-cuda/common.cuh @@ -911,7 +911,7 @@ static __device__ __forceinline__ float ggml_cuda_ue4m3_to_fp32(uint8_t x) { // but CDNA3 supports only e4m3_fnuz (no inf). const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation. const __hip_fp8_e4m3_fnuz xf = *reinterpret_cast(&bits); - return static_cast(xf) / 2; + return static_cast(xf); #else #if defined(FP8_AVAILABLE) && !defined(GGML_USE_HIP) const uint32_t bits = x * (x != 0x7F && x != 0xFF); // Convert NaN to 0.0f to match CPU implementation. From 9c10c94e16ebc4f3ed7c06264a93bf7e019c3f26 Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Sun, 22 Nov 2026 20:10:42 +0900 Subject: [PATCH 038/401] ggml : fix nonzero clear on WebGPU and non-UMA devices (#32727) --- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 4 +++- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 7 +++++-- tests/test-backend-tensor.cpp | 13 +++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index efb644793eb1..60cebe49445e 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -14279,7 +14279,9 @@ bool ggml_backend_vk_buffer_cpy_tensor_n(ggml_backend_buffer_t buffer, const ggm void ggml_backend_vk_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { ggml_backend_vk_buffer_context * ctx = (ggml_backend_vk_buffer_context *)buffer->context; - ggml_vk_buffer_memset(ctx->dev_buffer, 0, value, buffer->size); + // set all bytes of a u32 to the same 1 byte value + uint32_t val32 = (uint32_t)value * 0x01010101; + ggml_vk_buffer_memset(ctx->dev_buffer, 0, val32, buffer->size); } const char * ggml_backend_vk_buffer_type_name(ggml_backend_buffer_type_t buft) { diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 3fd8a66727c1..886760849796 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -4066,7 +4066,7 @@ static void ggml_backend_webgpu_buffer_memset_tensor(ggml_backend_buffer_t buffe size_t total_offset = ggml_webgpu_tensor_offset(tensor) + offset; - // This is a trick to set all bytes of a u32 to the same 1 byte value. + // set all bytes of a u32 to the same 1 byte value uint32_t val32 = (uint32_t) value * 0x01010101; ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32, total_offset, size); WEBGPU_CPU_PROFILE_TOTAL_END(memset_tensor, buf_ctx->global_ctx); @@ -4406,7 +4406,10 @@ static void ggml_backend_webgpu_buffer_clear(ggml_backend_buffer_t buffer, uint8 WEBGPU_LOG_DEBUG("ggml_backend_webgpu_buffer_clear(" << buffer << ", " << (uint32_t) value << ")"); WEBGPU_CPU_PROFILE_TOTAL_START(clear); ggml_backend_webgpu_buffer_context * buf_ctx = (ggml_backend_webgpu_buffer_context *) buffer->context; - ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, value, 0, buffer->size); + + // set all bytes of a u32 to the same 1 byte value + uint32_t val32 = (uint32_t) value * 0x01010101; + ggml_backend_webgpu_buffer_memset(buf_ctx->global_ctx, buf_ctx->buffer, val32, 0, buffer->size); WEBGPU_CPU_PROFILE_TOTAL_END(clear, buf_ctx->global_ctx); } diff --git a/tests/test-backend-tensor.cpp b/tests/test-backend-tensor.cpp index 213275f62ff5..84c4dc2bd30f 100644 --- a/tests/test-backend-tensor.cpp +++ b/tests/test-backend-tensor.cpp @@ -223,6 +223,19 @@ static bool test_tensor_n(ggml_backend_buffer_type_t buft) { } } + { + uint8_t expected[24], out[24] = {}; + memset(expected, 0x5A, sizeof(expected)); + + // Verify that clear fills every byte with a nonzero value. + ggml_backend_buffer_clear(buf.get(), 0x5A); + + ggml_backend_tensor_get(t_big, out, 0, sizeof(out)); + if (memcmp(out, expected, sizeof(out)) != 0) { + return false; + } + } + return true; } From 42f6a58fd1bfd475d9f09ea3bf7ef671c059eaf2 Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 22 Nov 2026 12:19:04 +0100 Subject: [PATCH 039/401] chat : trigger lazy grammar on bare JSON tool calls (#32497) Models like Llama 3.x emit tool calls as plain {"name": ...} JSON without a start marker, so with tool_choice=auto no grammar was produced at all. Use a pattern trigger on the opening of the call object instead. Assisted-by: Claude Code --- common/chat-auto-parser-generator.cpp | 22 ++++++++++++++++++---- tests/test-chat.cpp | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp index 9b918b366c38..e59a556ad08c 100644 --- a/common/chat-auto-parser-generator.cpp +++ b/common/chat-auto-parser-generator.cpp @@ -69,9 +69,21 @@ common_chat_params peg_generator::generate_parser(const common_chat_template & std::string trigger_marker = !autoparser.tools.format.section_start.empty() ? autoparser.tools.format.section_start : autoparser.tools.format.per_call_start; + // bare JSON calls without a start marker (e.g. Llama 3.x): trigger the lazy grammar on the call's opening instead + std::string trigger_pattern; + { + const auto & fmt = autoparser.tools.format; + bool top_level_name = (fmt.function_field.empty() || fmt.function_field == "function") && + fmt.name_field.find('.') == std::string::npos; + if (trigger_marker.empty() && fmt.mode == tool_format::JSON_NATIVE && !fmt.fun_name_is_key && + !fmt.tools_array_wrapped && top_level_name) { + trigger_pattern = "\\{\\s*\"" + regex_escape(fmt.name_field) + "\"\\s*:"; + } + } + bool has_response_format = !inputs.json_schema.empty() && inputs.json_schema.is_object(); bool include_grammar = has_response_format || (has_tools && - ((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && !trigger_marker.empty()) || + ((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && (!trigger_marker.empty() || !trigger_pattern.empty())) || inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); if (include_grammar) { @@ -82,9 +94,11 @@ common_chat_params peg_generator::generate_parser(const common_chat_template & // Set grammar triggers based on tool section markers (fall back to per-call markers) if (data.grammar_lazy) { - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker } - }; + if (!trigger_marker.empty()) { + data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker } }; + } else { + data.grammar_triggers = { { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, trigger_pattern } }; + } if (autoparser.tools.format.openai_wrapper_trigger) { // model emits the OpenAI function wrapper, trigger on it data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "{\"type\": \"function\"," }); diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index c4332941b6f1..7b70e7bcc853 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -1118,6 +1118,7 @@ struct peg_test_case { common_chat_msg expect; bool is_partial = false; bool expect_reconstruction = false; + bool expect_grammar = false; std::vector expect_rules; }; @@ -1191,6 +1192,10 @@ static void test_peg_parser(common_chat_templates * tmpls, } } + if (tc.expect_grammar && session.grammar().empty()) { + throw std::runtime_error("expected a grammar constraining the tool calls, but none was produced"); + } + common_chat_msg msg_accum; common_chat_msg msg_prev; msg_accum.role = msg_prev.role = "assistant"; @@ -1614,6 +1619,11 @@ class peg_test_builder { return *this; } + peg_test_builder & expect_grammar() { + tc_.expect_grammar = true; + return *this; + } + peg_test_builder & tool_choice(common_chat_tool_choice choice) { tc_.params.tool_choice = choice; return *this; @@ -7108,6 +7118,19 @@ static void test_template_output_peg_parsers(bool detailed_debug) { auto tst = peg_tester("models/templates/meta-llama-Llama-3.2-3B-Instruct.jinja", detailed_debug); tst.test("Hello, world!\nWhat's up?").tools({ special_function_tool }).expect(message_assist).expect_reconstruction().expect_rules({ "tool-0" }).run(); + // bare JSON calls have no start marker, auto mode must still produce a lazy grammar + tst.test("{\"name\": \"special_function\", \"parameters\": {\"arg1\": 1}}") + .tools({ special_function_tool }) + .expect(message_assist_call) + .expect_grammar() + .run(); + // same without spaces + tst.test("{\"name\":\"special_function\",\"parameters\":{\"arg1\":1}}") + .tools({ special_function_tool }) + .expect(message_assist_call) + .expect_grammar() + .run(); + // Continuation tests tst.test("world!\nWhat's up?") .messages({ message_user, message_assist_prefill_content }) From ad50351f5092436f312d98d25689207df25f4802 Mon Sep 17 00:00:00 2001 From: gianni-cor Date: Sun, 22 Nov 2026 12:33:13 +0100 Subject: [PATCH 040/401] ggml : add SIGMOID backward pass (#32126) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ggml : add SIGMOID backward pass Sigmoid is used in Qwen3.5 hybrid models and had no backward pass. Bump RPC protocol patch version for the new op. Signed-off-by: gianni-cor * replace assert with ggml_assert Co-authored-by: Johannes Gäßler * ggml : keep sigmoid backward checks in release builds Assisted-by: Codex * ggml : preserve existing operation IDs when adding SIGMOID_BACK Assisted-by: Codex --------- Signed-off-by: gianni-cor Co-authored-by: Johannes Gäßler --- ggml/include/ggml-rpc.h | 4 +- ggml/include/ggml.h | 9 +++ ggml/src/ggml-alloc.c | 1 + ggml/src/ggml-backend-meta.cpp | 3 +- ggml/src/ggml-cpu/ggml-cpu.c | 5 ++ ggml/src/ggml-cpu/ops.cpp | 112 +++++++++++++++++++++++++++++++++ ggml/src/ggml-cpu/ops.h | 1 + ggml/src/ggml-cpu/vec.h | 23 +++++++ ggml/src/ggml.c | 28 ++++++++- tests/test-backend-ops.cpp | 52 ++++++++++++++- 10 files changed, 231 insertions(+), 7 deletions(-) diff --git a/ggml/include/ggml-rpc.h b/ggml/include/ggml-rpc.h index 168ee774e488..062d5004e8d4 100644 --- a/ggml/include/ggml-rpc.h +++ b/ggml/include/ggml-rpc.h @@ -8,10 +8,10 @@ extern "C" { #define RPC_PROTO_MAJOR_VERSION 10 #define RPC_PROTO_MINOR_VERSION 0 -#define RPC_PROTO_PATCH_VERSION 1 +#define RPC_PROTO_PATCH_VERSION 2 #ifdef __cplusplus -static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); +static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION"); #endif #define GGML_RPC_MAX_SERVERS 16 diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 7c5b1e5528c0..2f466e2e4e46 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -433,6 +433,8 @@ extern "C" { GGML_OP_SLEEP, + GGML_OP_SIGMOID_BACK, + GGML_OP_COUNT, }; @@ -1038,6 +1040,13 @@ extern "C" { struct ggml_tensor * a, struct ggml_tensor * b); + // a - dy + // b - x + GGML_API struct ggml_tensor * ggml_sigmoid_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b); + // hardswish(x) = x * relu6(x + 3) / 6 GGML_API struct ggml_tensor * ggml_hardswish( struct ggml_context * ctx, diff --git a/ggml/src/ggml-alloc.c b/ggml/src/ggml-alloc.c index 65d2bea27726..90082d8619d9 100644 --- a/ggml/src/ggml-alloc.c +++ b/ggml/src/ggml-alloc.c @@ -35,6 +35,7 @@ bool ggml_op_can_inplace(enum ggml_op op) { case GGML_OP_ROPE: case GGML_OP_ROPE_BACK: case GGML_OP_SILU_BACK: + case GGML_OP_SIGMOID_BACK: case GGML_OP_RMS_NORM: case GGML_OP_RMS_NORM_BACK: case GGML_OP_CLAMP: diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index c4e37ed4692a..54d85b597fda 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -971,7 +971,8 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( case GGML_OP_CONCAT: { split_state = handle_concat(src_ss); } break; - case GGML_OP_SILU_BACK: { + case GGML_OP_SILU_BACK: + case GGML_OP_SIGMOID_BACK: { split_state = handle_generic(src_ss, /*scalar_only =*/ false); } break; case GGML_OP_NORM: diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index 33193a5affa1..ba075ff8d316 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -1884,6 +1884,10 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm { ggml_compute_forward_silu_back(params, tensor); } break; + case GGML_OP_SIGMOID_BACK: + { + ggml_compute_forward_sigmoid_back(params, tensor); + } break; case GGML_OP_NORM: { ggml_compute_forward_norm(params, tensor); @@ -2392,6 +2396,7 @@ static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { } break; case GGML_OP_SILU_BACK: + case GGML_OP_SIGMOID_BACK: case GGML_OP_MUL: case GGML_OP_DIV: case GGML_OP_NORM: diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index cd8134740e19..f984f13a6c3c 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -2898,6 +2898,118 @@ void ggml_compute_forward_silu_back( } } + +// ggml_compute_forward_sigmoid_back + +static void ggml_compute_forward_sigmoid_back_f32( + const ggml_compute_params * params, + ggml_tensor * dst) { + + const ggml_tensor * grad = dst->src[0]; + const ggml_tensor * src1 = dst->src[1]; + + GGML_ASSERT(ggml_is_contiguous_1(grad)); + GGML_ASSERT(ggml_is_contiguous_1(src1)); + GGML_ASSERT(ggml_is_contiguous_1(dst)); + GGML_ASSERT(ggml_are_same_shape(src1, dst)); + GGML_ASSERT(ggml_are_same_shape(src1, grad)); + + const int ith = params->ith; + const int nth = params->nth; + + const int nc = src1->ne[0]; + const int nr = ggml_nrows(src1); + + // rows per thread + const int dr = (nr + nth - 1)/nth; + + // row range for this thread + const int ir0 = dr*ith; + const int ir1 = MIN(ir0 + dr, nr); + + for (int i1 = ir0; i1 < ir1; i1++) { + ggml_vec_sigmoid_backward_f32(nc, + (float *) ((char *) dst->data + i1*( dst->nb[1])), + (float *) ((char *) src1->data + i1*(src1->nb[1])), + (float *) ((char *) grad->data + i1*(grad->nb[1]))); + +#ifndef NDEBUG + for (int k = 0; k < nc; k++) { + const float x = ((float *) ((char *) dst->data + i1*( dst->nb[1])))[k]; + GGML_UNUSED(x); + assert(!isnan(x)); + assert(!isinf(x)); + } +#endif // NDEBUG + } +} + +static void ggml_compute_forward_sigmoid_back_f16( + const ggml_compute_params * params, + ggml_tensor * dst) { + + const ggml_tensor * grad = dst->src[0]; + const ggml_tensor * src1 = dst->src[1]; + + GGML_ASSERT(ggml_is_contiguous_1(grad)); + GGML_ASSERT(ggml_is_contiguous_1(src1)); + GGML_ASSERT(ggml_is_contiguous_1(dst)); + GGML_ASSERT(ggml_are_same_shape(src1, dst)); + GGML_ASSERT(ggml_are_same_shape(src1, grad)); + + const int ith = params->ith; + const int nth = params->nth; + + const int nc = src1->ne[0]; + const int nr = ggml_nrows(src1); + + // rows per thread + const int dr = (nr + nth - 1)/nth; + + // row range for this thread + const int ir0 = dr*ith; + const int ir1 = MIN(ir0 + dr, nr); + + for (int i1 = ir0; i1 < ir1; i1++) { + ggml_vec_sigmoid_backward_f16(nc, + (ggml_fp16_t *) ((char *) dst->data + i1*( dst->nb[1])), + (ggml_fp16_t *) ((char *) src1->data + i1*(src1->nb[1])), + (ggml_fp16_t *) ((char *) grad->data + i1*(grad->nb[1]))); + +#ifndef NDEBUG + for (int k = 0; k < nc; k++) { + const float x = ((ggml_fp16_t *) ((char *) dst->data + i1*( dst->nb[1])))[k]; + const float v = GGML_CPU_FP16_TO_FP32(x); + GGML_UNUSED(v); + assert(!isnan(v)); + assert(!isinf(v)); + } +#endif // NDEBUG + } +} + +void ggml_compute_forward_sigmoid_back( + const ggml_compute_params * params, + ggml_tensor * dst) { + + const ggml_tensor * src0 = dst->src[0]; + + switch (src0->type) { + case GGML_TYPE_F32: + { + ggml_compute_forward_sigmoid_back_f32(params, dst); + } break; + case GGML_TYPE_F16: + { + ggml_compute_forward_sigmoid_back_f16(params, dst); + } break; + default: + { + GGML_ABORT("fatal error"); + } + } +} + // ggml_compute_forward_reglu // row loop shared by the BF16 GLU ops diff --git a/ggml/src/ggml-cpu/ops.h b/ggml/src/ggml-cpu/ops.h index 3a4fa0707e49..22017df7063d 100644 --- a/ggml/src/ggml-cpu/ops.h +++ b/ggml/src/ggml-cpu/ops.h @@ -41,6 +41,7 @@ void ggml_compute_forward_repeat(const struct ggml_compute_params * params, stru void ggml_compute_forward_repeat_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_concat(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_silu_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); +void ggml_compute_forward_sigmoid_back(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_norm(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_rms_norm(const struct ggml_compute_params * params, struct ggml_tensor * dst); void ggml_compute_forward_rms_norm_mul_fused(const struct ggml_compute_params * params, struct ggml_tensor * dst_rms_norm, struct ggml_tensor * dst_mul); diff --git a/ggml/src/ggml-cpu/vec.h b/ggml/src/ggml-cpu/vec.h index 4aac5e9666a7..0b8ac5d51e72 100644 --- a/ggml/src/ggml-cpu/vec.h +++ b/ggml/src/ggml-cpu/vec.h @@ -1536,6 +1536,29 @@ inline static void ggml_vec_silu_backward_f16(const int n, ggml_fp16_t * dx, con } } +inline static float ggml_sigmoid_backward_f32(float x, float dy) { + const float s = 1.0f/(1.0f + expf(-x)); + return dy*s*(1.0f - s); +} + +inline static ggml_fp16_t ggml_sigmoid_backward_f16(ggml_fp16_t x, ggml_fp16_t dy) { + const float v = GGML_CPU_FP16_TO_FP32(x); + const float s = 1.0f/(1.0f + expf(-v)); + return GGML_CPU_FP32_TO_FP16(GGML_CPU_FP16_TO_FP32(dy)*s*(1.0f - s)); +} + +inline static void ggml_vec_sigmoid_backward_f32(const int n, float * dx, const float * x, const float * dy) { + for (int i = 0; i < n; ++i) { + dx[i] = ggml_sigmoid_backward_f32(x[i], dy[i]); + } +} + +inline static void ggml_vec_sigmoid_backward_f16(const int n, ggml_fp16_t * dx, const ggml_fp16_t * x, const ggml_fp16_t * dy) { + for (int i = 0; i < n; ++i) { + dx[i] = ggml_sigmoid_backward_f16(x[i], dy[i]); + } +} + inline static void ggml_vec_reglu_f32 (const int n, float * y, const float * x, const float * g) { for (int i = 0; i < n; ++i) { y[i] = (x[i] > 0.f) ? x[i] * g[i] : 0.f; diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index b47c5addf6c5..3389dcd63d7c 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -1116,9 +1116,11 @@ static const char * GGML_OP_NAME[GGML_OP_COUNT] = { "GLU", "SLEEP", + + "SIGMOID_BACK", }; -static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100"); +static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "none", @@ -1231,9 +1233,11 @@ static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = { "glu(x)", "sleep(x)", + + "sigmoid_back(x)", }; -static_assert(GGML_OP_COUNT == 100, "GGML_OP_COUNT != 100"); +static_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT != 101"); static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2"); @@ -2866,6 +2870,21 @@ struct ggml_tensor * ggml_silu_back( return result; } +// ggml_sigmoid_back + +struct ggml_tensor * ggml_sigmoid_back( + struct ggml_context * ctx, + struct ggml_tensor * a, + struct ggml_tensor * b) { + struct ggml_tensor * result = ggml_dup_tensor(ctx, a); + + result->op = GGML_OP_SIGMOID_BACK; + result->src[0] = a; + result->src[1] = b; + + return result; +} + // ggml hardswish struct ggml_tensor * ggml_hardswish( @@ -7148,6 +7167,11 @@ static void ggml_compute_backward( ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, grad, src0)); } } break; + case GGML_UNARY_OP_SIGMOID: { + if (src0_needs_grads) { + ggml_add_or_set(ctx, cgraph, isrc0, ggml_sigmoid_back(ctx, grad, src0)); + } + } break; case GGML_UNARY_OP_EXP: { if (src0_needs_grads) { ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, tensor, grad)); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 9b8d7015c8a5..91ff4c86a5f3 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -2176,7 +2176,7 @@ struct test_unary : public test_case { ggml_tensor * build_graph(ggml_context * ctx) override { const bool grad_supported = op == GGML_UNARY_OP_ABS || op == GGML_UNARY_OP_SGN || op == GGML_UNARY_OP_NEG || op == GGML_UNARY_OP_STEP || op == GGML_UNARY_OP_RELU || op == GGML_UNARY_OP_SILU || - op == GGML_UNARY_OP_EXPM1 || op == GGML_UNARY_OP_SOFTPLUS; + op == GGML_UNARY_OP_EXPM1 || op == GGML_UNARY_OP_SOFTPLUS || op == GGML_UNARY_OP_SIGMOID; ggml_tensor * a; if (v & 1) { @@ -2218,6 +2218,12 @@ struct test_unary : public test_case { max = 10.f; } + // saturated sigmoid inputs give zero analytic and numeric gradients, which the grad check cannot compare + if (mode == MODE_GRAD && op == GGML_UNARY_OP_SIGMOID) { + min = -2.f; + max = 2.f; + } + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { // test extended range of values to check for NaNs in GELU init_tensor_uniform(t, min, max); @@ -2225,7 +2231,16 @@ struct test_unary : public test_case { } float grad_eps() override { - return 15.0f; + return op == GGML_UNARY_OP_SIGMOID ? 0.25f : 15.0f; + } + + bool grad_precise() override { + return op == GGML_UNARY_OP_SIGMOID; + } + + // f32 rounding of a large summed loss exceeds the tolerance, so only the small sigmoid case is grad checked + int64_t grad_nmax() override { + return op == GGML_UNARY_OP_SIGMOID ? 64 : test_case::grad_nmax(); } std::vector grad_expect() override { @@ -3898,6 +3913,37 @@ struct test_silu_back : public test_case { } }; +// GGML_OP_SIGMOID_BACK +struct test_sigmoid_back : public test_case { + const ggml_type type; + const std::array ne; + + std::string vars() override { + return VARS_TO_STR2(type, ne); + } + + test_sigmoid_back(ggml_type type = GGML_TYPE_F32, + std::array ne = {64, 5, 4, 3}) + : type(type), ne(ne) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * a = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(a, "a"); + + ggml_tensor * grad = ggml_new_tensor(ctx, type, 4, ne.data()); + ggml_set_name(grad, "grad"); + + ggml_tensor * out = ggml_sigmoid_back(ctx, a, grad); + ggml_set_name(out, "out"); + + return out; + } + + bool grad_precise() override { + return true; + } +}; + // GGML_OP_NORM struct test_norm : public test_case { const ggml_type type; @@ -10781,6 +10827,7 @@ static std::vector> make_test_cases_eval() { } } } + test_cases.emplace_back(new test_unary(GGML_UNARY_OP_SIGMOID, GGML_TYPE_F32, { 16, 4, 1, 1 })); // fused relu + sqr (squared ReLU) for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32}) { @@ -11761,6 +11808,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_scale(GGML_TYPE_F16, {10, 10, 10, 10}, 2.0f, 1.0f, false, 1)); // view test test_cases.emplace_back(new test_softcap(GGML_TYPE_F32, {10, 10, 10, 10}, 50.0f)); test_cases.emplace_back(new test_silu_back()); + test_cases.emplace_back(new test_sigmoid_back()); for (float eps : { 0.0f, 1e-6f, 1e-4f, 1e-1f, 10.f }) { for (uint32_t n : { 64, 1025 }) { From 8d60873dfb8619f2b5ed31adfbab07cccb40db5c Mon Sep 17 00:00:00 2001 From: chessMan <71754779+mohitmishra786@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:10:10 +0530 Subject: [PATCH 041/401] ggml/gguf : avoid creating invalid enum values from untrusted file data (#32641) * ggml/gguf : avoid creating invalid enum values from untrusted file data * removing the tests --- ggml/src/gguf.cpp | 31 +++++++++---------------------- 1 file changed, 9 insertions(+), 22 deletions(-) diff --git a/ggml/src/gguf.cpp b/ggml/src/gguf.cpp index c80b682185ce..1a57b608e972 100644 --- a/ggml/src/gguf.cpp +++ b/ggml/src/gguf.cpp @@ -322,24 +322,6 @@ struct gguf_reader { return true; } - bool read(enum ggml_type & dst) const { - int32_t tmp = -1; - if (!read(tmp)) { - return false; - } - dst = ggml_type(tmp); - return true; - } - - bool read(enum gguf_type & dst) const { - int32_t tmp = -1; - if (!read(tmp)) { - return false; - } - dst = gguf_type(tmp); - return true; - } - bool read(std::string & dst) const { uint64_t size = 0; if (!read(size)) { @@ -555,7 +537,7 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr for (int64_t i = 0; ok && i < n_kv; ++i) { std::string key; - gguf_type type = gguf_type(-1); + int32_t type = -1; bool is_array = false; uint64_t n = 1; @@ -724,15 +706,20 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr // tensor type { - ok = ok && gr.read(info.t.type); + int32_t type = -1; + ok = ok && gr.read(type); + if (!ok) { + break; + } // check that tensor type is within defined range - if (info.t.type < 0 || info.t.type >= GGML_TYPE_COUNT) { + if (type < 0 || type >= GGML_TYPE_COUNT) { GGML_LOG_ERROR("%s: tensor '%s' has invalid ggml type %d. should be in [0, %d)\n", - __func__, info.t.name, info.t.type, GGML_TYPE_COUNT); + __func__, info.t.name, type, GGML_TYPE_COUNT); ok = false; break; } + info.t.type = ggml_type(type); const size_t type_size = ggml_type_size(info.t.type); const int64_t blck_size = ggml_blck_size(info.t.type); From 0b51bb2fed322bc884f96f98db340e2b0f6ea176 Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Sun, 22 Nov 2026 17:52:56 +0100 Subject: [PATCH 042/401] server: support /models/sse on single-model mode (#32398) * server: support /models/sse on single-model mode * nits * nits --- common/arg.cpp | 10 +- common/arg.h | 3 + common/download.cpp | 26 +++- tools/server/README.md | 2 + tools/server/server-common.cpp | 17 +++ tools/server/server-common.h | 3 + tools/server/server-context.cpp | 11 +- tools/server/server-http.cpp | 3 + tools/server/server-models.cpp | 88 ++++++++---- tools/server/server-models.h | 21 ++- tools/server/server.cpp | 186 +++++++++++++++++--------- tools/server/tests/unit/test_basic.py | 16 +++ 12 files changed, 273 insertions(+), 113 deletions(-) diff --git a/common/arg.cpp b/common/arg.cpp index a638237672bd..e99b48c5b4d8 100644 --- a/common/arg.cpp +++ b/common/arg.cpp @@ -326,7 +326,7 @@ static bool parse_bool_value(const std::string & value) { // common_models_handler // -static std::string get_default_local_path(const std::string & url) { +std::string common_get_default_local_path(const std::string & url) { auto f = string_split(url, '#').front(); f = string_split(f, '?').front(); return fs_get_cache_file(string_split(f, '/').back()).string(); @@ -436,7 +436,7 @@ static std::vector build_url_tasks(const common_params_mod if (parts.size() == 1) { common_download_task task; task.url = parts[0]; - task.local_path = model.path.empty() ? get_default_local_path(parts[0]) : model.path; + task.local_path = model.path.empty() ? common_get_default_local_path(parts[0]) : model.path; task.opts = opts; tasks.push_back(std::move(task)); return tasks; @@ -454,7 +454,7 @@ static std::vector build_url_tasks(const common_params_mod task.url = part; task.opts = opts; - std::string local = get_default_local_path(part); + std::string local = common_get_default_local_path(part); if (!base_dir.empty()) { auto pos = local.rfind('/'); std::string name = pos == std::string::npos ? local : local.substr(pos + 1); @@ -487,7 +487,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params auto handle_url = [&](common_params_model & model) { if (!model.url.empty()) { if (model.path.empty()) { - model.path = get_default_local_path(model.url); + model.path = common_get_default_local_path(model.url); } } }; @@ -498,7 +498,7 @@ void common_models_handler_apply(common_models_handler & handler, common_params // optionally, if docker repo is set, resolve it if (!params.model.docker_repo.empty()) { params.model.url = common_docker_resolve_model(params.model.docker_repo); - params.model.path = get_default_local_path(params.model.url); + params.model.path = common_get_default_local_path(params.model.url); } // handle plain "url" tasks (non-hf) diff --git a/common/arg.h b/common/arg.h index 203d1b4e11b8..a7cf30be4052 100644 --- a/common/arg.h +++ b/common/arg.h @@ -149,6 +149,9 @@ common_models_handler common_models_handler_init(const common_params & params, l // check if the model is a preset repo (i.e. has a preset file) bool common_models_handler_is_preset_repo(const common_models_handler & handler); +// the cache path a model downloaded from a plain url is stored at +std::string common_get_default_local_path(const std::string & url); + // download and update params with the downloaded model path void common_models_handler_apply(common_models_handler & handler, common_params & params, common_download_callback * callback = nullptr); diff --git a/common/download.cpp b/common/download.cpp index 682fd6e3ef7a..4dabaedb5466 100644 --- a/common/download.cpp +++ b/common/download.cpp @@ -98,6 +98,9 @@ class ProgressBar : public common_download_callback { std::string filename; size_t len = 0; + // the caller's callback, if any, still receives every event + common_download_callback * next; + static void cleanup(const ProgressBar * line) { lines.erase(line); if (lines.empty()) { @@ -110,9 +113,12 @@ class ProgressBar : public common_download_callback { } public: - ProgressBar() = default; + ProgressBar(common_download_callback * next) : next(next) {} void on_start(const common_download_progress & p) override { + if (next) { + next->on_start(p); + } filename = url_get_filename(p.url); for (size_t i = 0; i < filename.size(); ++i) { @@ -126,12 +132,22 @@ class ProgressBar : public common_download_callback { } } - void on_done(const common_download_progress &, bool) override { + void on_done(const common_download_progress & p, bool ok) override { + if (next) { + next->on_done(p, ok); + } std::lock_guard lock(mutex); cleanup(this); } + bool is_cancelled() const override { + return next && next->is_cancelled(); + } + void on_update(const common_download_progress & p) override { + if (next) { + next->on_update(p); + } if (!p.total || !is_output_a_tty()) { return; } @@ -519,11 +535,9 @@ int common_download_file_single(const std::string & url, const std::string & lock_path, const std::string & alt_path) { if (!opts.offline) { - ProgressBar tty_cb; + ProgressBar tty_cb(opts.callback); common_download_opts online_opts = opts; - if (!online_opts.callback) { - online_opts.callback = &tty_cb; - } + online_opts.callback = &tty_cb; return common_download_file_single_online(url, path, online_opts, skip_etag, lock_path, alt_path); } diff --git a/tools/server/README.md b/tools/server/README.md index b0168b6d14dc..b995e740304b 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -2435,6 +2435,8 @@ Response: ### GET `/models/sse`: Real-time events +This endpoint is also available in single-model mode (`-m`, `-hf`, ...), where it is served before the model is loaded, to follow the download and loading progress. As `GET /models` is unavailable until the model is loaded, each new client first receives the last event sent. If the download or the loading fails, a `status_change` event with status `unloaded` is sent before the server exits. + Example events: ```js diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 8d4c022e975d..95c57f877bee 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -1,3 +1,4 @@ +#include "arg.h" #include "common.h" #include "download.h" #include "log.h" @@ -2386,6 +2387,22 @@ server_role::~server_role() { } } +std::string server_get_model_name(const common_params & params) { + if (!params.model_alias.empty()) { + // backward compat: use first alias as model name + return *params.model_alias.begin(); + } + if (!params.model.get_name().empty()) { + return params.model.get_name(); + } + if (!params.model.url.empty()) { + // -mu before the download: the path the model will be stored at + return common_get_default_local_path(params.model.url); + } + // fallback: derive model name from file name + return std::filesystem::path(params.model.path).filename().string(); +} + bool server_role::is_managed_by_router() { return std::getenv(SERVER_ENV_ROUTER_PORT) != nullptr; } diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 911bb31d709f..c1a0f4dcabe9 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -837,6 +837,9 @@ static inline server_state server_state_from_str(const std::string & str) { GGML_ASSERT(false && "invalid server_state string"); } +// the model name reported by the server: the first alias, else the model's repo or path +std::string server_get_model_name(const common_params & params); + // the role of this process and, when it is a child of a router, its side of the protocol struct server_role { // serializes the notify_to_router writes diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index b458a17c42fa..89f884e6548c 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1642,16 +1642,7 @@ struct server_context_impl { SRV_TRC("%s", "context checkpoints disabled\n"); } - if (!params_base.model_alias.empty()) { - // backward compat: use first alias as model name - model_name = *params_base.model_alias.begin(); - } else if (!params_base.model.get_name().empty()) { - model_name = params_base.model.get_name(); - } else { - // fallback: derive model name from file name - auto model_path = std::filesystem::path(params_base.model.path); - model_name = model_path.filename().string(); - } + model_name = server_get_model_name(params_base); model_aliases = params_base.model_alias; model_tags = params_base.model_tags; diff --git a/tools/server/server-http.cpp b/tools/server/server-http.cpp index 0244d4a72f75..d1f31e3ae22c 100644 --- a/tools/server/server-http.cpp +++ b/tools/server/server-http.cpp @@ -396,6 +396,9 @@ bool server_http_context::init_listener(const common_params & params) { if (frontend_paths.count(req.path)) { return true; // frontend asset, allow it to load and show "loading" } + if (req.path == "/models/sse") { + return true; // reports the download and loading progress + } // no endpoints are allowed to be accessed when the server is not ready // this is to prevent any data races or inconsistent states res.status = 503; diff --git a/tools/server/server-models.cpp b/tools/server/server-models.cpp index 5d5992c08d3a..8e3bb4982627 100644 --- a/tools/server/server-models.cpp +++ b/tools/server/server-models.cpp @@ -734,16 +734,7 @@ bool server_models::remove_sidecar(const std::string & name, const std::string & } void server_models::notify_sse(const std::string & event, const std::string & model_id, const json & data) { - std::unique_ptr result = std::make_unique(); - result->data = { - {"model", model_id}, - {"event", event}, - }; - if (!data.is_null()) { - result->data["data"] = data; - } - SRV_DBG("notifying SSE clients about event '%s' for model '%s': %s\n", event.c_str(), model_id.c_str(), safe_json_to_str(result->data).c_str()); - sse.broadcast(std::move(result)); + sse.notify(event, model_id, data); } void server_models::load_models() { @@ -1931,7 +1922,7 @@ void server_models::handle_child_state(const std::string & name, const std::stri } // -// server_models_routes +// server_models_sse // // RAII wrapper similar to server_response_reader, but doesn't use server_queue @@ -1970,6 +1961,61 @@ struct server_models_sse_client { } }; +void server_models_sse::notify(const std::string & event, const std::string & model_id, const json & data) { + std::unique_ptr result = std::make_unique(); + result->data = { + {"model", model_id}, + {"event", event}, + }; + if (!data.is_null()) { + result->data["data"] = data; + } + SRV_DBG("notifying SSE clients about event '%s' for model '%s': %s\n", event.c_str(), model_id.c_str(), safe_json_to_str(result->data).c_str()); + // under the lock, so that a client connecting meanwhile gets this event either replayed or queued, not both + std::lock_guard lk(mutex); + if (replay_last) { + last_event = result->data; + } + queue.broadcast(std::move(result)); +} + +server_http_context::handler_t server_models_sse::make_handler(std::function should_stop) { + return [this, should_stop = std::move(should_stop)](const server_http_req & req) { + auto res = std::make_unique(); + res->status = 200; + res->content_type = "text/event-stream"; + std::shared_ptr sse_client; + std::string pending; // the replayed event, sent first + { + std::lock_guard lk(mutex); + sse_client = std::make_shared(queue); + if (replay_last && !last_event.is_null()) { + pending = "data: " + safe_json_to_str(last_event) + "\n\n"; + } + } + res->next = [should_stop, sse_client, pending = std::move(pending), &req](std::string & output) mutable -> bool { + if (!pending.empty()) { + output = std::move(pending); + pending.clear(); + return true; + } + auto result = sse_client->next([&]() { + return should_stop() || req.should_stop(); + }); + if (result == nullptr) { + return false; // client disconnected or should_stop + } + output = "data: " + safe_json_to_str(result->to_json()) + "\n\n"; + return true; // listen for the next event + }; + return res; + }; +} + +// +// server_models_routes +// + static void res_ok(std::unique_ptr & res, const json & response_data) { res->status = 200; res->data = safe_json_to_str(response_data); @@ -2312,23 +2358,9 @@ void server_models_routes::init_routes() { return res; }; - this->get_router_models_sse = [this](const server_http_req & req) { - auto res = std::make_unique(); - res->status = 200; - res->content_type = "text/event-stream"; - auto sse_client = std::make_shared(models.sse); - res->next = [this, sse_client, &req](std::string & output) -> bool { - auto result = sse_client->next([&]() { - return stopping.load(std::memory_order_relaxed) || req.should_stop(); - }); - if (result == nullptr) { - return false; // client disconnected or should_stop - } - output = "data: " + safe_json_to_str(result->to_json()) + "\n\n"; - return true; // listen for the next event - }; - return res; - }; + this->get_router_models_sse = models.sse.make_handler([this]() { + return stopping.load(std::memory_order_relaxed); + }); this->post_router_models = [this](const server_http_req & req) { auto res = std::make_unique(); diff --git a/tools/server/server-models.h b/tools/server/server-models.h index e18ae3a31f43..fa5322ad8c28 100644 --- a/tools/server/server-models.h +++ b/tools/server/server-models.h @@ -157,6 +157,25 @@ struct server_unfinished_downloads { void delete_partials(const std::vector & parts); }; +// broadcasts model events to the clients of GET /models/sse, used by both router and single-model mode +struct server_models_sse { + // send the last event to each new client, for single-model mode where GET /models is unavailable while loading + const bool replay_last; + + server_models_sse(bool replay_last = false) : replay_last(replay_last) {} + + // thread-safe + void notify(const std::string & event, const std::string & model_id, const json & data = nullptr); + + // handler for GET /models/sse, a client is disconnected once should_stop() returns true + server_http_context::handler_t make_handler(std::function should_stop); + +private: + std::mutex mutex; + json last_event; + server_response queue; +}; + struct server_models_routes; struct server_monitor; // defined in server-models.cpp @@ -289,7 +308,7 @@ struct server_models { server_models(const common_params & params, int argc, char ** argv); ~server_models(); - server_response sse; // for real-time updates via SSE endpoint + server_models_sse sse; // for real-time updates via SSE endpoint // (re-)load the list of models from various sources and prepare the metadata mapping // - if this is called the first time, simply populate the metadata diff --git a/tools/server/server.cpp b/tools/server/server.cpp index fabf0a0413c8..e022355dca80 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -109,6 +109,7 @@ static server_role_type server_role_detect(const common_params & params, server_ } // a server given no model is a router const bool has_model = !params.model.path.empty() + || !params.model.url.empty() || !params.model.hf_repo.empty() || !params.model.docker_repo.empty(); return has_model ? SERVER_ROLE_INSTANCE : SERVER_ROLE_ROUTER; @@ -363,66 +364,45 @@ static bool server_on_listening(server_http_context & ctx_http, const common_par return true; } -// -// download worker: a child of the router that pulls a model into the cache and reports the progress -// - -struct server_download_state : public common_download_callback { - server_role * role; +// throttled download progress, shared by the download worker and single-model mode +struct server_download_progress : public common_download_callback { + // called under the lock, the files are downloaded in parallel threads + std::function on_progress; std::function should_stop; - // files download in parallel threads: throttle each file on its own, a shared - // timer lets a small, fast file (e.g. a draft) starve the updates of the others - std::mutex progress_mutex; + // throttle each file on its own, a shared timer lets a small, fast file (e.g. a draft) starve the updates of the others + std::mutex mutex; std::unordered_map last_progress_time; - bool is_ok = false; - server_download_state(server_role * r) : role(r) {} - - bool run(common_params & params) { - try { - common_models_handler handler = common_models_handler_init(params, LLAMA_EXAMPLE_SERVER); - common_models_handler_apply(handler, params, this); - is_ok = true; - } catch (const std::exception & e) { - auto model_name = params.model.get_name(); - SRV_ERR("download failed for model name=%s: %s\n", model_name.c_str(), e.what()); - is_ok = false; - } - return is_ok; - } - void on_progress(const common_download_progress & p) { - json data = { - {"url", p.url}, - {"downloaded", p.downloaded}, - {"total", p.total}, - }; - role->notify_to_router(server_state_to_str(SERVER_STATE_DOWNLOADING), data); + void notify(const common_download_progress & p) { + std::lock_guard lk(mutex); + on_progress(p); } void on_start(const common_download_progress & p) override { - on_progress(p); + notify(p); } void on_update(const common_download_progress & p) override { int64_t now = ggml_time_ms(); - // throttle progress updates to avoid flooding logs; the first update of a file - // always passes, it carries the file's total size - { - std::lock_guard lk(progress_mutex); - auto it = last_progress_time.find(p.url); - if (it != last_progress_time.end() && now - it->second < 100) { - return; - } - last_progress_time[p.url] = now; + // the first update of a file always passes, it carries the file's total size + std::lock_guard lk(mutex); + auto it = last_progress_time.find(p.url); + if (it != last_progress_time.end() && now - it->second < 100) { + return; } + last_progress_time[p.url] = now; on_progress(p); } void on_done(const common_download_progress & p, bool) override { - on_progress(p); + notify(p); } bool is_cancelled() const override { return should_stop ? should_stop() : false; } }; +// +// download worker: a child of the router that pulls a model into the cache and reports the progress +// + static int server_run_download(common_params & params, server_role & role) { auto cancelled = std::make_shared>(false); @@ -431,12 +411,27 @@ static int server_run_download(common_params & params, server_role & role) { cancelled->store(true, std::memory_order_relaxed); }); - server_download_state dl(&role); + server_download_progress dl; + dl.on_progress = [&role](const common_download_progress & p) { + role.notify_to_router(server_state_to_str(SERVER_STATE_DOWNLOADING), { + {"url", p.url}, + {"downloaded", p.downloaded}, + {"total", p.total}, + }); + }; dl.should_stop = [cancelled]() { return cancelled->load(std::memory_order_relaxed); }; - bool ok = dl.run(params); + bool ok = true; + try { + common_models_handler handler = common_models_handler_init(params, LLAMA_EXAMPLE_SERVER); + common_models_handler_apply(handler, params, &dl); + } catch (const std::exception & e) { + auto model_name = params.model.get_name(); + SRV_ERR("download failed for model name=%s: %s\n", model_name.c_str(), e.what()); + ok = false; + } role.notify_to_router(server_state_to_str(SERVER_STATE_DOWNLOADING), { {"result", ok ? "download_finished" : "download_failed"}, @@ -638,15 +633,21 @@ static int server_run_router(common_params & params, int argc, char ** argv, con // static int server_run_instance(common_params & params, server_role & role, common_models_handler & models_handler, const server_run_opts & opts) { - // -hf / docker: download if needed and resolve the local path. a child resolves what the router downloaded - if (opts.resolve_model) { - try { - common_models_handler_apply(models_handler, params); - } catch (const std::exception & e) { - SRV_ERR("failed to download model: %s\n", e.what()); - return 1; + // a router child reports its state to the router, a single-model server to its own /models/sse clients + const bool managed = role.is_managed_by_router(); + const std::string model_name = server_get_model_name(params); + server_models_sse sse(/* replay_last */ true); + std::atomic sse_stopping = false; + + auto notify = [&](const std::string & event, const json & data = nullptr) { + if (!managed) { + sse.notify(event, model_name, data); } - } + }; + auto notify_status = [&](server_model_status status, json data = json::object()) { + data["status"] = server_model_status_to_string(status); + notify("status_change", data); + }; // note: this is guaranteed to out-live ctx_http and tools server_mcp mcp_mgr; @@ -667,37 +668,82 @@ static int server_run_instance(common_params & params, server_role & role, commo server_stream_make_get_handler(), server_stream_make_lookup_handler(), server_stream_make_delete_handler()); + if (!managed) { + ctx_http.get("/models/sse", ex_wrapper(sse.make_handler([&sse_stopping]() { + return sse_stopping.load(std::memory_order_relaxed); + }))); + } if (!server_setup_features(ctx_http, params, mcp_mgr, tools, SERVER_ROLE_INSTANCE)) { return 1; } // setup clean up function, to be called before exit - auto clean_up = [&ctx_http, &ctx_server, &mcp_mgr]() { + auto clean_up = [&ctx_http, &ctx_server, &mcp_mgr, &sse_stopping]() { SRV_INF("%s: cleaning up before exit...\n", __func__); // stop the session GC first, it finalizes live sessions and wakes pending readers server_stream_session_manager_stop(); + sse_stopping.store(true); // disconnect the SSE clients ctx_http.stop(); ctx_server.terminate(); mcp_mgr.shutdown(); llama_backend_free(); }; - // start the HTTP server before loading the model to be able to serve /health requests + // start the HTTP server before downloading and loading the model to be able to serve /health and /models/sse requests if (!ctx_http.start()) { clean_up(); SRV_ERR("%s", "exiting due to HTTP server error\n"); return 1; } - // setup communication child --> router if necessary - if (role.is_managed_by_router()) { - ctx_server.set_state_callback([&](server_state state, json payload) { - role.notify_to_router(server_state_to_str(state), payload); - }); + // -hf / docker: download if needed and resolve the local path. a child resolves what the router downloaded + if (opts.resolve_model) { + json progress = json::object(); // url -> {done, total}, the same shape as the router sends + server_download_progress dl; + dl.on_progress = [&](const common_download_progress & p) { + if (p.total == 0) { + return; // not started yet, or found in the cache + } + progress[p.url] = { + {"done", p.downloaded}, + {"total", p.total}, + }; + notify("download_progress", {{"progress", progress}}); + }; + try { + common_models_handler_apply(models_handler, params, managed ? nullptr : &dl); + if (!progress.empty()) { + notify("download_finished"); + } + } catch (const std::exception & e) { + SRV_ERR("failed to download model: %s\n", e.what()); + notify("download_failed"); + notify_status(SERVER_MODEL_STATUS_UNLOADED, {{"exit_code", 1}}); + clean_up(); + ctx_http.join(); + return 1; + } } + // setup communication child --> router, or to the SSE clients + ctx_server.set_state_callback([&](server_state state, json payload) { + if (managed) { + role.notify_to_router(server_state_to_str(state), payload); + return; + } + switch (state) { + case SERVER_STATE_LOADING: notify_status(SERVER_MODEL_STATUS_LOADING, {{"progress", payload}}); break; + case SERVER_STATE_READY: notify_status(SERVER_MODEL_STATUS_LOADED); break; // wakeup from sleeping + case SERVER_STATE_SLEEPING: notify_status(SERVER_MODEL_STATUS_SLEEPING); break; + default: break; + } + }); + + notify_status(SERVER_MODEL_STATUS_LOADING); + if (!ctx_server.load_model(params)) { + notify_status(SERVER_MODEL_STATUS_UNLOADED, {{"exit_code", 1}}); clean_up(); ctx_http.join(); SRV_ERR("%s", "exiting due to model loading error\n"); @@ -709,7 +755,22 @@ static int server_run_instance(common_params & params, server_role & role, commo SRV_INF("%s", "model loaded\n"); + json info = routes.get_model_info(); + json memory; + if (const auto * ll_ctx = ctx_server.get_llama_context()) { + memory = server_model_memory(llama_n_ctx(ll_ctx), common_memory_breakdown_rows(ll_ctx)).to_json(); + } + + { + json data = {{"info", info}}; + if (!memory.is_null()) { + data["memory"] = memory; + } + notify_status(SERVER_MODEL_STATUS_LOADED, data); + } + shutdown_handler = [&](int) { + sse_stopping.store(true); mcp_mgr.shutdown(); // this will unblock start_loop() ctx_server.terminate(); @@ -729,12 +790,11 @@ static int server_run_instance(common_params & params, server_role & role, commo // optionally, notify router server that this instance is ready std::thread monitor_thread; - if (role.is_managed_by_router()) { + if (managed) { monitor_thread = role.setup(shutdown_handler); - json info = routes.get_model_info(); // the router tracks device memory from these reports - if (const auto * ll_ctx = ctx_server.get_llama_context()) { - info["memory"] = server_model_memory(llama_n_ctx(ll_ctx), common_memory_breakdown_rows(ll_ctx)).to_json(); + if (!memory.is_null()) { + info["memory"] = memory; } role.notify_to_router(server_state_to_str(SERVER_STATE_READY), info); } diff --git a/tools/server/tests/unit/test_basic.py b/tools/server/tests/unit/test_basic.py index 423a7c326cfa..ad3cea679ee2 100644 --- a/tools/server/tests/unit/test_basic.py +++ b/tools/server/tests/unit/test_basic.py @@ -143,3 +143,19 @@ def test_server_model_aliases_and_tags(): assert set(model["tags"]) == {"chat", "fim", "small"} # id is derived from first alias (alphabetical order from std::set) assert model["id"] == "code" + + +def test_server_models_sse_single_model(): + global server + server.start() + # a client connecting after the load gets the last status replayed + with requests.get(server.make_url("/models/sse"), stream=True, timeout=10) as res: + assert res.status_code == 200 + assert res.headers["Content-Type"].startswith("text/event-stream") + line = next(x for x in res.iter_lines() if x) + event = json.loads(line.decode("utf-8").removeprefix("data: ")) + model_id = server.make_request("GET", "/models").body["data"][0]["id"] + assert event["model"] == model_id + assert event["event"] == "status_change" + assert event["data"]["status"] == "loaded" + assert event["data"]["info"]["id"] == model_id From 1014775c8a10e52d2cc3189a13d3b9437fa0213c Mon Sep 17 00:00:00 2001 From: Aldehir Rojas Date: Sun, 22 Nov 2026 11:36:03 -0600 Subject: [PATCH 043/401] chat : implement token aware parsing (#29307) --- common/chat-auto-parser-generator.cpp | 10 +- common/chat-auto-parser.h | 1 + common/chat-peg-parser.h | 11 + common/chat.cpp | 20 +- common/chat.h | 6 + common/json-schema-to-grammar.cpp | 4 +- common/parsers/gemma4.cpp | 55 +- common/parsers/gpt-oss.cpp | 61 +- common/parsers/harmony-xml.cpp | 7 +- common/parsers/k2-horizon.cpp | 4 +- common/parsers/minicpm5.cpp | 4 +- common/parsers/minimax-m3.cpp | 6 +- common/parsers/muse-glimmer.cpp | 54 +- common/parsers/muse-spark.cpp | 5 +- common/parsers/qwen3-coder.cpp | 79 +-- common/peg-parser.cpp | 660 ++++++++++++++++++---- common/peg-parser.h | 94 ++- common/reasoning-budget.cpp | 8 +- common/trie.cpp | 74 ++- common/trie.h | 61 +- docs/development/parsing.md | 131 +++++ grammars/README.md | 6 +- src/llama-grammar.cpp | 216 +++++-- src/llama-grammar.h | 20 +- tests/peg-parser/test-basic.cpp | 43 ++ tests/peg-parser/test-gbnf-generation.cpp | 362 +++++++++--- tests/test-chat.cpp | 273 +++++++-- tests/test-grammar-integration.cpp | 189 ++++++- tests/test-grammar-parser.cpp | 24 + tests/test-llama-grammar.cpp | 2 +- 30 files changed, 1988 insertions(+), 502 deletions(-) diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp index e59a556ad08c..220889367754 100644 --- a/common/chat-auto-parser-generator.cpp +++ b/common/chat-auto-parser-generator.cpp @@ -373,7 +373,9 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte auto & p = ctx.p; const auto & inputs = ctx.inputs; - auto until_suffix = p.rule("until-suffix", p.until(arguments.value_suffix)); + // A raw string value needs a suffix to end on, without one it is parsed as JSON + bool raw_strings = !arguments.value_suffix.empty(); + auto until_suffix = raw_strings ? p.rule("until-suffix", p.until(arguments.value_suffix)) : p.eps(); common_peg_parser tool_choice = p.choice(); @@ -389,9 +391,9 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte p.tool_arg(p.tool_arg_open(arguments.name_prefix + p.tool_arg_name(p.literal(param.name)) + arguments.name_suffix) + arguments.value_prefix + - (param.schema->may_be_string() ? - p.ac(p.tool_arg_string_value(until_suffix) + - p.tool_arg_close(p.literal(arguments.value_suffix)), arguments.value_suffix) : + (raw_strings && param.schema->may_be_string() ? + p.through(p.tool_arg_string_value(until_suffix), + p.tool_arg_close(p.literal(arguments.value_suffix))) : (p.tool_arg_json_value(p.schema( p.json(), "tool-" + std::to_string(tool_index) + "-arg-" + std::to_string(param_index) + "-schema", doc, *param.schema)) + p.tool_arg_close(p.literal(arguments.value_suffix))))); diff --git a/common/chat-auto-parser.h b/common/chat-auto-parser.h index 8ae15c91e1e5..696b9e5e66b5 100644 --- a/common/chat-auto-parser.h +++ b/common/chat-auto-parser.h @@ -71,6 +71,7 @@ struct generation_params { bool is_inference = true; bool add_inference = false; bool mark_input = true; // whether to mark input strings in the jinja context + common_peg_tokens specials; bool has_continuation() const { return continue_final_message != COMMON_CHAT_CONTINUATION_NONE && !continue_msg.empty(); diff --git a/common/chat-peg-parser.h b/common/chat-peg-parser.h index c77ec117b5aa..b39607e5cd88 100644 --- a/common/chat-peg-parser.h +++ b/common/chat-peg-parser.h @@ -71,6 +71,9 @@ constexpr size_t COMMON_CHAT_MAX_PERMUTE = 6; class common_chat_peg_builder : public common_peg_parser_builder { public: + common_chat_peg_builder() = default; + explicit common_chat_peg_builder(common_peg_tokens tokens) : common_peg_parser_builder(std::move(tokens)) {} + // Tag constants (from former common_chat_peg_base_builder) static constexpr const char * REASONING_BLOCK = "reasoning-block"; static constexpr const char * REASONING = "reasoning"; @@ -200,6 +203,14 @@ inline common_peg_arena build_chat_peg_parser( return builder.build(); } +inline common_peg_arena build_chat_peg_parser( + const common_peg_tokens & specials, + const std::function & fn) { + common_chat_peg_builder builder(specials); + builder.set_root(fn(builder)); + return builder.build(); +} + class tag_based_peg_mapper { public: std::map tags; diff --git a/common/chat.cpp b/common/chat.cpp index de5f1c490303..3cff920cf16b 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -315,6 +315,7 @@ struct common_chat_templates { bool add_bos; bool add_eos; bool has_explicit_template; // Model had builtin template or template overridden was specified. + common_peg_tokens specials; std::unique_ptr template_default; // always set (defaults to chatml) std::unique_ptr template_tool_use; std::unique_ptr template_tts; // the prompt of a text to speak @@ -802,6 +803,10 @@ void common_chat_templates_free(struct common_chat_templates * tmpls) { delete tmpls; } +void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials) { + tmpls->specials = std::move(specials); +} + bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls) { return tmpls->has_explicit_template; } @@ -978,6 +983,7 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * std::string token_eos = eos_token_override; bool add_bos = false; bool add_eos = false; + common_peg_tokens specials; if (model) { const auto * vocab = llama_model_get_vocab(model); const auto get_token = [&](llama_token token, const char * name, const char * jinja_variable_name) { @@ -997,11 +1003,13 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * token_eos = get_token(llama_vocab_eos(vocab), "EOS", "eos_token"); add_bos = llama_vocab_get_add_bos(vocab); add_eos = llama_vocab_get_add_eos(vocab); + specials = common_peg_tokens(vocab); } common_chat_templates_ptr tmpls(new common_chat_templates()); tmpls->has_explicit_template = has_explicit_template; tmpls->add_bos = add_bos; tmpls->add_eos = add_eos; + tmpls->specials = std::move(specials); try { tmpls->template_default = std::make_unique(default_template_src, token_bos, token_eos); } catch (const std::exception & e) { @@ -1543,6 +1551,7 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_ params.add_generation_prompt = inputs.add_generation_prompt; params.add_bos = tmpls->add_bos; params.add_eos = tmpls->add_eos; + params.specials = tmpls->specials; params.continue_final_message = inputs.continue_final_message; if (params.continue_final_message != COMMON_CHAT_CONTINUATION_NONE) { @@ -1825,6 +1834,7 @@ common_chat_input common_chat_input_tokenize(const llama_vocab * vocab, const st } if (input.text != text) { // the pieces do not give back the same text, keep the text without tokens + LOG_WRN("%s: token pieces do not match the text, parsing without token ids\n", __func__); return common_chat_input(text); } return input; @@ -1935,11 +1945,17 @@ common_chat_session::common_chat_session(const common_chat_templates * tm thinking_ends = std::move(applied.thinking_end_tags); parser_params.format = applied.format; - parser_params.generation_prompt = vocab ? common_chat_input_tokenize(vocab, applied.generation_prompt) - : common_chat_input(applied.generation_prompt); parser_params.debug = params.debug; parser_params.parser = std::move(applied.parser); + if (vocab) { + parser_params.generation_prompt = common_chat_input_tokenize(vocab, applied.generation_prompt); + } else if (params.tokenize) { + parser_params.generation_prompt = params.tokenize(applied.generation_prompt); + } else { + parser_params.generation_prompt = common_chat_input(applied.generation_prompt); + } + delimiters = std::move(applied.message_delimiters); if (vocab) { diff --git a/common/chat.h b/common/chat.h index 43331b16d4a0..ca324d8121c6 100644 --- a/common/chat.h +++ b/common/chat.h @@ -372,6 +372,9 @@ common_chat_templates_ptr common_chat_templates_init(const struct llama_model * const std::string & bos_token_override = "", const std::string & eos_token_override = ""); +// override special tokens for testing +void common_chat_templates_set_specials(struct common_chat_templates * tmpls, common_peg_tokens specials); + bool common_chat_templates_was_explicit(const struct common_chat_templates * tmpls); std::string common_chat_templates_source(const struct common_chat_templates * tmpls, const std::string & variant = ""); @@ -397,6 +400,9 @@ common_chat_msg common_chat_peg_parse(const common_peg_arena & src_parser, const struct common_chat_session_params { bool echo = false; // include the assistant prefill in the output when continuing a message bool debug = false; // enable debug output for the PEG parser + + // tokenize the generation prompt when there is no vocab for testing + std::function tokenize; }; class common_chat_session { diff --git a/common/json-schema-to-grammar.cpp b/common/json-schema-to-grammar.cpp index b6ea61fc3870..4690a57fa4ca 100644 --- a/common/json-schema-to-grammar.cpp +++ b/common/json-schema-to-grammar.cpp @@ -676,8 +676,8 @@ class common_chat_schema_converter { const auto & node = trie.nodes[idx]; std::string rejects; auto first = true; - for (const auto & [cpt, child] : node.children) { - std::string c = common_unicode_cpt_to_utf8(cpt); + for (const auto & [sym, child] : node.children) { + std::string c = common_unicode_cpt_to_utf8(sym.value); rejects += c; if (first) { first = false; diff --git a/common/parsers/gemma4.cpp b/common/parsers/gemma4.cpp index 2a2e929e19a3..ff4dfad6789e 100644 --- a/common/parsers/gemma4.cpp +++ b/common/parsers/gemma4.cpp @@ -24,7 +24,9 @@ struct depth_guard { // Gemma 4 value parsers void gemma4_value_rules(common_chat_peg_builder & p) { // The tags are what gemma4_to_json() in the mapper reads, the rules may wrap them freely. - p.rule("gemma4-string", p.tag(gemma4::STRING, p.literal("<|\"|>") + p.tag(gemma4::STRING_CONTENT, p.until("<|\"|>")) + p.literal("<|\"|>"))); + auto string_delim = p.token("<|\"|>"); + + p.rule("gemma4-string", p.tag(gemma4::STRING, string_delim + p.tag(gemma4::STRING_CONTENT, p.until(string_delim)) + string_delim)); p.rule("gemma4-bool", p.tag(gemma4::BOOL, p.json_bool())); @@ -34,7 +36,7 @@ void gemma4_value_rules(common_chat_peg_builder & p) { // Keys are bare in the template, but Gemma 4 occasionally wraps them in quotes p.rule("gemma4-dict-key", p.tag(gemma4::DICT_KEY, p.choice({ - p.literal("<|\"|>") + p.tag(gemma4::DICT_KEY_NAME, p.until("<|\"|>")) + p.literal("<|\"|>"), + string_delim + p.tag(gemma4::DICT_KEY_NAME, p.until(string_delim)) + string_delim, p.literal("\"") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^\"]", 1, -1)) + p.literal("\""), p.literal("'") + p.tag(gemma4::DICT_KEY_NAME, p.chars("[^']", 1, -1)) + p.literal("'"), p.tag(gemma4::DICT_KEY_NAME, p.chars("[^:}]", 1, -1)), @@ -144,7 +146,7 @@ class gemma4_schema_parser { alts |= name(); } // Gemma 4 may emit keys in its string delimiters or quotes - alts |= p_.literal("<|\"|>") + name() + p_.literal("<|\"|>"); + alts |= p_.token("<|\"|>") + name() + p_.token("<|\"|>"); if (key.find('\'') == std::string::npos) { alts |= p_.literal("'") + name() + p_.literal("'"); } @@ -331,18 +333,23 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE); auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto start = p.rule("start", p.optional(p.literal("<|turn>model\n"))); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto start = p.rule("start", p.optional(p.token("<|turn>") + p.literal("model\n"))); + auto channel_start = p.token("<|channel>"); + auto channel_end = p.token(""); + auto think_start = channel_start + p.literal("thought"); + auto tool_call_start = p.token("<|tool_call>"); + // the model may start a tool call before closing the thought channel + auto think_end = channel_end | p.peek(tool_call_start); if (extract_reasoning) { - // the model may start a tool call before closing the thought channel - p.rule("thought", p.literal("<|channel>thought") + p.space() + p.reasoning(p.until_one_of({"", "<|tool_call>"})) + (p.literal("") | p.peek(p.literal("<|tool_call>")))); + p.rule("thought", think_start + p.space() + p.reasoning(p.until(channel_end | tool_call_start)) + think_end); } else { - p.rule("thought", p.content(p.literal("<|channel>thought") + p.space() + p.until_one_of({"", "<|tool_call>"}) + (p.literal("") | p.peek(p.literal("<|tool_call>"))))); + p.rule("thought", p.content(think_start + p.space() + p.until(channel_end | tool_call_start) + think_end)); } - auto consume_empty_channels = p.gbnf(p.zero_or_more(p.literal("<|channel>") + p.negate(p.literal("thought"))), ""); - auto thought = (p.peek(p.literal("<|channel>")) + consume_empty_channels + p.ref("thought")) | p.negate(p.literal("<|channel>")); + auto consume_empty_channels = p.gbnf(p.zero_or_more(channel_start + p.negate(p.literal("thought"))), ""); + auto thought = (p.peek(channel_start) + consume_empty_channels + p.ref("thought")) | p.negate(channel_start); if (has_response_format) { auto response_format = p.literal("```json") << @@ -378,39 +385,35 @@ common_chat_params common_chat_params_init_gemma4(const common_chat_template & }))); }); - auto tool_call = p.trigger_rule("tool-call", p.repeat( - "<|tool_call>call:" + tool_choice + "", - /* min = */ inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0, - /* max = */ inputs.parallel_tool_calls ? -1 : 1 - )); + auto tool_call_rest = p.literal("call:") + tool_choice + p.token(""); + auto tool_call = p.rule("tool-call", tool_call_start + tool_call_rest); + auto more = inputs.parallel_tool_calls ? p.zero_or_more(tool_call) : p.eps(); + + auto tool_calls = p.trigger_rule("tool-calls", tool_call_start, tool_call_rest + more); if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return start + thought + tool_call; + return start + thought + tool_calls; } - auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until("<|tool_call>")); - auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", "", "<|tool_call>"}))); + auto scan_to_toolcall = p.rule("scan-to-toolcall", p.until(tool_call_start)); + auto content = p.rule("content", p.content(p.until(channel_start | channel_end | tool_call_start))); auto message = p.rule("message", thought + content); - return start + p.zero_or_more(message) + scan_to_toolcall + tool_call; + return start + p.zero_or_more(message) + scan_to_toolcall + p.optional(tool_calls); } // Gemma 4 may emit an extra <|channel>thought\n at the end of the content. It may // also emit a single trailing token. Consume all complete reasoning blocks and // then stop at the first unmatched token. - auto content = p.rule("content", p.content(p.until_one_of({"<|channel>", ""}))); + auto content = p.rule("content", p.content(p.until(channel_start | channel_end))); auto message = p.rule("message", thought + content); return start + p.one_or_more(message); }); if (include_grammar) { - data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED))); }); - - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_WORD, "<|tool_call>" }, - }; } return data; diff --git a/common/parsers/gpt-oss.cpp b/common/parsers/gpt-oss.cpp index 4cbf929f9bfd..fbc388c97c2d 100644 --- a/common/parsers/gpt-oss.cpp +++ b/common/parsers/gpt-oss.cpp @@ -65,17 +65,18 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE); auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto start = p.rule("start", p.literal("<|start|>assistant")); - auto end = p.rule("end", p.literal("<|end|>")); - auto content = p.rule("message-content", p.until("<|end|>")); - auto channel = p.literal("<|channel|>") + (p.literal("commentary") | p.literal("analysis")); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto start_assistant = p.token("<|start|>") + p.literal("assistant"); + auto start = p.rule("start", start_assistant); + auto end = p.rule("end", p.token("<|end|>")); + auto content = p.rule("message-content", p.until(p.token("<|end|>"))); + auto channel = p.token("<|channel|>") + (p.literal("commentary") | p.literal("analysis")); auto constrain_type = p.chars("[A-Za-z0-9_-]", 1, -1); - auto constraint = p.optional(p.space() + p.optional(p.literal("<|constrain|>")) + constrain_type); + auto constraint = p.optional(p.chars("[ ]", 1, -1) + p.optional(p.token("<|constrain|>")) + constrain_type); // Occasionally, gpt-oss-20b will prefix channels with this commentary - auto stray_commentary = p.optional(p.literal("<|channel|>commentary") + p.optional(p.literal(" to=assistant"))); - auto start_analysis = stray_commentary + p.literal("<|channel|>analysis<|message|>"); + auto stray_commentary = p.optional(p.token("<|channel|>") + p.literal("commentary") + p.optional(p.literal(" to=assistant"))); + auto start_analysis = stray_commentary + p.token("<|channel|>") + p.literal("analysis") + p.token("<|message|>"); if (extract_reasoning) { p.rule("analysis", start_analysis + p.reasoning(content) + end); @@ -84,8 +85,8 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & } auto analysis = p.ref("analysis"); - auto preamble = p.rule("preamble", p.literal("<|channel|>commentary<|message|>") + p.content(content) + end); - auto final_msg = p.rule("final", stray_commentary + p.literal("<|channel|>final") + constraint + p.literal("<|message|>") + p.content(content)); + auto preamble = p.rule("preamble", p.token("<|channel|>") + p.literal("commentary") + p.token("<|message|>") + p.content(content) + end); + auto final_msg = p.rule("final", stray_commentary + p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") + p.content(content)); // Consume any unsolicited tool calls, e.g. builtin functions auto unsolicited = p.rule("unsolicited", p.atomic(p.optional(channel) + p.literal(" to=") + content + end)); @@ -94,58 +95,58 @@ common_chat_params common_chat_params_init_gpt_oss(const common_chat_template & if (has_response_format) { auto response_format = p.rule("response-format", - p.literal("<|channel|>final") + constraint + p.literal("<|message|>") + + p.token("<|channel|>") + p.literal("final") + constraint + p.token("<|message|>") + p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema))); return p.zero_or_more(start + analysis) + start + response_format; } if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { - auto tool_choice = p.choice(); + auto in_role = p.choice(); + auto in_channel = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { const auto & function = tool.at("function"); std::string name = function.at("name"); const auto params = common_chat_tool_parameters(function); - auto func_name = p.literal(" to=functions.") + p.tool_name(p.literal(name)); + auto func_name = p.tool_name(p.literal(name)); auto args = p.tool_args(p.schema(p.json(), "tool-" + std::to_string(tool_index) + "-schema", params)); // recipient in role header // <|start|>assistant to=functions.NAME<|channel|>(commentary|analysis)[constraint]<|message|>ARGS - auto tool_in_role = p.tool(p.tool_open(func_name + channel + constraint + p.literal("<|message|>")) + args); + in_role |= p.rule("tool-" + std::to_string(tool_index) + "-in-role", + p.atomic(func_name + channel + constraint + p.token("<|message|>")) + args); // recipient in channel header - // <|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS - auto tool_in_channel = p.tool(p.tool_open(channel + func_name + constraint + p.literal("<|message|>")) + args); - - tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_in_role | tool_in_channel); + // <|start|>assistant<|channel|>(commentary|analysis) to=functions.NAME[constraint]<|message|>ARGS + in_channel |= p.rule("tool-" + std::to_string(tool_index) + "-in-channel", + p.atomic(func_name + constraint + p.token("<|message|>")) + args); }); - auto tool_call = p.trigger_rule("tool-call", tool_choice); + // The recipient prefix is the trigger, so the grammar constrains the name that follows it + auto to_functions = p.tool_open(p.literal(" to=functions.")); + auto tool_call = p.choice({ + p.trigger_rule("tool-call-in-role", start_assistant + to_functions, in_role), + p.trigger_rule("tool-call-in-channel", start_assistant + channel + to_functions, in_channel) + }); if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return p.zero_or_more(start + any) + start + tool_call; + return p.zero_or_more(start + any) + tool_call; } - return p.zero_or_more(start + any) + start + (tool_call | final_msg); + return p.zero_or_more(start + any) + (tool_call | (start + final_msg)); } return p.zero_or_more(start + any) + start + (final_msg | unsolicited); }); if (include_grammar) { - data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); + // The grammar scans for the triggers itself, so the sampler runs it from the first token + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO); }); - - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^\\s+to$" }, - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "^<\\|channel\\|>(?:commentary|analysis)\\s+to=functions$" }, - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(\\s+to)" }, - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|start\\|>assistant(<\\|channel\\|>(?:commentary|analysis)\\s+to)" } - }; } return data; diff --git a/common/parsers/harmony-xml.cpp b/common/parsers/harmony-xml.cpp index bf05fac5d680..1a7e3cb82a55 100644 --- a/common/parsers/harmony-xml.cpp +++ b/common/parsers/harmony-xml.cpp @@ -99,8 +99,11 @@ common_chat_params common_chat_params_init_harmony_xml(const common_chat_templat auto arg_close = p.tool_arg_close(p.gbnf( p.literal(PARAM_CLOSE) | (p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open)), gbnf_format_literal("\n") + " " + gbnf_format_literal(PARAM_CLOSE.substr(1)) + "?")); - auto arg_string = p.rule("rfl-arg-string", - p.ac(p.tool_arg_string_value(p.until_one_of(string_ends)) + arg_close, PARAM_CLOSE)); + auto string_value = p.tool_arg_string_value(p.until_one_of(string_ends)); + auto arg_string = p.rule("rfl-arg-string", p.through(string_value, p.tool_arg_close(p.literal(PARAM_CLOSE)))); + // the parser also accepts a value with no closing tag, the grammar still requires the closing tag + auto missing_close = string_value + p.tool_arg_close(p.literal("\n") + p.peek(p.optional(p.literal("\n")) + next_open)); + arg_string = p.gbnf(arg_string | missing_close, "rfl-arg-string"); auto arg_sep = p.optional(p.literal("\n")); std::string call_close_gbnf = gbnf_format_literal("<|end|>"); diff --git a/common/parsers/k2-horizon.cpp b/common/parsers/k2-horizon.cpp index e688cd919382..b02330d2dc95 100644 --- a/common/parsers/k2-horizon.cpp +++ b/common/parsers/k2-horizon.cpp @@ -91,7 +91,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template } auto think_body = p.until_one_of(data.thinking_end_tags); auto think_block = [&](const common_peg_parser & body) { - return p.optional(THINK_START + p.space() + p.ac(body + think_end, data.thinking_end_tags)); + return p.optional(THINK_START + p.space() + p.through(body, think_end)); }; auto reasoning = extract_reasoning ? think_block(p.reasoning(think_body)) : p.eps(); @@ -110,7 +110,7 @@ common_chat_params common_chat_params_init_k2_horizon(const common_chat_template tool_choice = p.standard_json_tools(CALL_START, CALL_END, inputs.tools, false, true); } else { auto arg_close = p.tool_arg_close(p.literal(ARG_VAL_END)); - auto arg_string = p.rule("xml-arg-string", p.ac(p.tool_arg_string_value(p.until(ARG_VAL_END)) + arg_close, ARG_VAL_END)); + auto arg_string = p.rule("xml-arg-string", p.through(p.tool_arg_string_value(p.until(ARG_VAL_END)), arg_close)); // The models leave out even when asked for xml_typed auto arg_type = call_format == "xml_typed" ? p.optional(ARG_TYPE + p.until(ARG_TYPE_END) + ARG_TYPE_END + p.space()) : p.eps(); diff --git a/common/parsers/minicpm5.cpp b/common/parsers/minicpm5.cpp index 7609865e08c9..ef0fed7fcda5 100644 --- a/common/parsers/minicpm5.cpp +++ b/common/parsers/minicpm5.cpp @@ -63,8 +63,8 @@ common_chat_params common_chat_params_init_minicpm5(const common_chat_template & // CDATA lets a value carry characters that would otherwise close the tag (e.g. // ); capture the inner text only, excluding the CDATA markers. auto string_value = p.choice({ - p.literal("")) + p.literal("]]>"), "]]>") + p.tool_arg_close(p.literal("")), - p.negate(p.literal("")) + p.tool_arg_close(p.literal("")), "") + p.literal("")), "]]>") + p.tool_arg_close(p.literal("")), + p.negate(p.literal("")), p.tool_arg_close(p.literal(""))) }); auto tool_choice = p.choice(); diff --git a/common/parsers/minimax-m3.cpp b/common/parsers/minimax-m3.cpp index 6080bfb00a98..dba02b238ef7 100644 --- a/common/parsers/minimax-m3.cpp +++ b/common/parsers/minimax-m3.cpp @@ -64,8 +64,8 @@ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template if (extract_reasoning) { auto block = inputs.enable_thinking ? p.literal(THINK_START) + p.space() + - p.ac(p.reasoning(p.until(THINK_END)) + p.literal(THINK_END), THINK_END) - : p.literal(THINK_START) + p.ac(p.until(THINK_END) + p.literal(THINK_END), THINK_END); + p.through(p.reasoning(p.until(THINK_END)), THINK_END) + : p.literal(THINK_START) + p.through(p.until(THINK_END), THINK_END); // A turn without reasoning is prefixed with a bare , written either by the // generation prompt (thinking_mode = "disabled") or by the model itself. @@ -113,7 +113,7 @@ common_chat_params common_chat_params_init_minimax_m3(const common_chat_template // A string accepts anything, so a union with a string alternative is a string if (schema.may_be_string()) { - return p.ac(p.tool_arg_string_value(p.until(close)) + close_tag, close); + return p.through(p.tool_arg_string_value(p.until(close)), close_tag); } if (schema.kind() == common_chat_schema::KIND_ANY_OF) { diff --git a/common/parsers/muse-glimmer.cpp b/common/parsers/muse-glimmer.cpp index 78ff50727aa2..a1ee40f498cb 100644 --- a/common/parsers/muse-glimmer.cpp +++ b/common/parsers/muse-glimmer.cpp @@ -17,7 +17,7 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa data.supports_thinking = true; data.preserved_tokens = { - "<|start|>", "<|message|>", "<|eom|>", "<|eot|>", + "<|start|>", "<|message|>", "<|eom|>", // ATEM tool-call markup emitted on " to=" turns. "", "", "", "", @@ -48,37 +48,38 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa // Constrained grammar whenever tools are offered or a response format is requested. auto include_grammar = has_response_format || (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE); - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto start = p.rule("start", p.literal("<|start|>assistant")); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto start_token = p.token("<|start|>"); + auto message = p.token("<|message|>"); + auto eom = p.token("<|eom|>"); + auto start = p.rule("start", start_token + p.literal("assistant")); if (!extract_reasoning && !include_grammar) { return start + p.content(p.rest()); } if (extract_reasoning) { - p.rule("analysis", p.literal(" to=self<|message|>") + p.reasoning(p.until("<|eom|>")) + p.literal("<|eom|>")); + p.rule("analysis", p.literal(" to=self") + message + p.reasoning(p.until(eom)) + eom); } else { - p.rule("analysis", p.literal(" to=self<|message|>") + p.content(p.until("<|eom|>")) + p.literal("<|eom|>")); + p.rule("analysis", p.literal(" to=self") + message + p.content(p.until(eom)) + eom); } auto analysis = p.ref("analysis"); auto recipient = p.optional(p.literal(" to=user")); - auto final_msg = p.rule("final", recipient + p.literal("<|message|>") + - p.content(p.until_one_of({ "<|eot|>", "<|eom|>" }))); + auto final_msg = p.rule("final", recipient + message + p.content(p.until(eom))); if (has_response_format) { auto response_json = p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)); auto response_format = p.rule("response-format", - recipient + p.literal("<|message|>") + + recipient + message + ((p.literal("```json") + p.space() + response_json + p.space() + p.literal("```")) | response_json)); return p.zero_or_more(start + analysis) + start + response_format; } if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { - auto string_value = p.ac( - p.tool_arg_string_value(p.until("")) + p.tool_arg_close(p.literal("")), - ""); + auto string_value = p.through(p.tool_arg_string_value(p.until("")), + p.tool_arg_close(p.literal(""))); auto tool_choice = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { @@ -106,40 +107,35 @@ common_chat_params common_chat_params_init_muse_glimmer(const common_chat_templa args = p.zero_or_more(p.choice(arg_rules) + p.space()); } - auto tool_parser = p.tool( - p.tool_open(p.literal(" to=") + p.until("<|message|>") + - p.literal("<|message|>") + p.space() + - p.literal("") + p.space()) + auto open = p.tool_open(start_token + p.literal("assistant to=") + p.tool_name(p.literal(name)) + message); + auto body = p.rule("tool-" + std::to_string(tool_index), + p.literal("") + p.space() + p.literal("") + p.space() << p.tool_args(args) << p.tool_close(p.literal("") + p.space() + p.literal(""))); - tool_choice |= p.rule("tool-" + std::to_string(tool_index), tool_parser); + tool_choice |= open + body; }); - auto tool_calls = inputs.parallel_tool_calls - ? p.trigger_rule("tool-call", tool_choice + p.zero_or_more(p.literal("<|eom|>") + start + tool_choice)) - : p.trigger_rule("tool-call", tool_choice); - + auto more = inputs.parallel_tool_calls ? p.zero_or_more(eom + tool_choice) : p.eps(); + auto tool_calls = p.rule("tool-calls", tool_choice + more); if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return p.zero_or_more(start + analysis) + start + tool_calls; + return p.zero_or_more(start + analysis) + tool_calls; } - auto trailing_calls = p.optional(p.literal("<|eom|>") + start + tool_calls); - return p.zero_or_more(start + analysis) + start + (tool_calls | (final_msg + trailing_calls)); + auto trailing_calls = p.optional(eom + tool_calls); + return p.zero_or_more(start + analysis) + (tool_calls | (start + final_msg + trailing_calls)); } return p.zero_or_more(start + analysis) + start + final_msg; }); if (include_grammar) { - data.grammar_lazy = !(has_response_format || (has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED)); + // Every message starts with a recipient header, so the grammar is not lazy. + // The model cannot generate a recipient that is not self, user, or a tool. + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder); }); - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, - "(?:^|<\\|start\\|>assistant)( to=(?!self<\\|message\\|>)(?!user<\\|message\\|>)[^<]*?<\\|message\\|>)" }, - }; } return data; diff --git a/common/parsers/muse-spark.cpp b/common/parsers/muse-spark.cpp index 945ee2aaf7ba..74a393f4e08c 100644 --- a/common/parsers/muse-spark.cpp +++ b/common/parsers/muse-spark.cpp @@ -86,9 +86,8 @@ common_chat_params common_chat_params_init_muse_spark(const common_chat_template } if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { - auto string_value = p.ac( - p.tool_arg_string_value(p.until("")) + p.tool_arg_close(p.literal("")), - ""); + auto string_value = p.through(p.tool_arg_string_value(p.until("")), + p.tool_arg_close(p.literal(""))); auto tool_choice = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { diff --git a/common/parsers/qwen3-coder.cpp b/common/parsers/qwen3-coder.cpp index b8dc0226722b..c943b93f3be2 100644 --- a/common/parsers/qwen3-coder.cpp +++ b/common/parsers/qwen3-coder.cpp @@ -59,27 +59,16 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat data.prompt.append(data.generation_prompt); } - std::vector tool_call_starts = { "" }; - - if (is_qwen3_coder) { - // Match complete opener for Qwen3-Coder models that occasionally omit the - // starting . The model may hallucinate a tool name, but it is preferable over - // constraining on - foreach_function(inputs.tools, [&](size_t, const json & tool) { - const std::string name = tool.at("function").at("name"); - tool_call_starts.push_back(""); - }); - } - - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { auto generation_prompt = p.literal(GEN_PREFIX); // The template strips the newline before , so leave it out of the reasoning - auto think_body = p.until_one_of({ "\n", "", "" }); - auto think_close = p.literal("\n") | p.literal("") | p.peek(p.literal("")); + auto think_end = (p.literal("\n") + p.token("")) | p.token(""); + auto think_body = p.until(think_end | p.token("")); + auto think_close = think_end | p.peek(p.token("")); - auto reasoning_extracted = p.optional("" + p.space() + p.reasoning(think_body) + think_close); - auto reasoning_skipped = p.optional("" + p.space() + think_body + think_close); + auto reasoning_extracted = p.optional(p.token("") + p.space() + p.reasoning(think_body) + think_close); + auto reasoning_skipped = p.optional(p.token("") + p.space() + think_body + think_close); auto reasoning = p.eps(); if (supports_reasoning && extract_reasoning) { @@ -99,7 +88,13 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE) { auto arg_close = p.tool_arg_close(p.literal("\n\n")); auto arg_string = p.rule("xml-arg-string", - p.ac(p.tool_arg_string_value(p.until("\n\n")) + arg_close, "\n\n")); + p.through(p.tool_arg_string_value(p.until("\n\n")), arg_close)); + + auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0; + + auto more = inputs.parallel_tool_calls ? p.zero_or_more(p.ref("tool-call")) : p.eps(); + auto starts = p.token(""); + auto tool_calls = p.choice(); auto tool_choice = p.choice(); foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { @@ -155,35 +150,29 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat args = args + p.zero_or_more(p.choice(optional_args)); } - auto func = p.tool(p.tool_open("\n") + - p.tool_args(args) + - p.tool_close(p.literal("\n"))); - - tool_choice |= p.rule("tool-" + std::to_string(tool_index), func); - }); + auto opener = p.tool_open(""); + auto body = p.literal("\n") + p.tool_args(args) + p.tool_close(p.literal("\n")); - auto min_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED ? 1 : 0; + tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(opener + body)); - auto tool_call_body = tool_choice + "" + p.space(); - auto tool_call = p.rule("tool-call", "\n" + tool_call_body); + if (is_qwen3_coder) { + // Qwen3-Coder models sometimes omit , so the full opener is also a trigger. + // Do not trigger on . + tool_calls |= p.trigger_rule("tool-calls-" + std::to_string(tool_index), opener, body + p.token("") + p.space() + more); + starts |= opener; + } + }); - // Qwen3-Coder models may occasionally omit the token. - auto tool_call_first = is_qwen3_coder ? - p.rule("tool-call-first", p.optional(p.literal("\n")) + tool_call_body) : - tool_call; + auto tool_call_body = tool_choice + p.token("") + p.space(); + p.rule("tool-call", p.token("") + p.literal("\n") + tool_call_body); - auto calls = inputs.parallel_tool_calls ? tool_call_first + p.zero_or_more(tool_call) : tool_call_first; - auto tool_calls = p.trigger_rule("tool-call-root", p.repeat(calls, min_calls, 1)); + tool_calls |= p.trigger_rule("tool-calls", p.token(""), p.literal("\n") + tool_call_body + more); // The templates separate content from the tool calls with one or two newlines, // stop the content before them - std::vector content_ends; - for (const auto & start : tool_call_starts) { - content_ends.insert(content_ends.end(), { "\n\n" + start, "\n" + start, start }); - } + auto content_end = (p.literal("\n\n") + starts) | (p.literal("\n") + starts) | starts; - return generation_prompt + - (reasoning << p.content(p.until_one_of(content_ends)) << tool_calls); + return generation_prompt + (reasoning << p.content(p.until(content_end)) << p.repeat(tool_calls, min_calls, 1)); } // Content only parser @@ -191,17 +180,11 @@ common_chat_params common_chat_params_init_qwen3_coder(const common_chat_templat }); if (include_grammar) { - data.grammar_lazy = !has_response_format && has_tools && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO; - + // The grammar scans for the triggers itself, so the sampler runs it from the first token + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO); }); - - if (data.grammar_lazy) { - for (const auto & start : tool_call_starts) { - data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, start }); - } - } } return data; diff --git a/common/peg-parser.cpp b/common/peg-parser.cpp index d980cfc76dca..924289097752 100644 --- a/common/peg-parser.cpp +++ b/common/peg-parser.cpp @@ -208,6 +208,89 @@ void common_peg_ast_arena::visit(const common_peg_parse_result & result, const c } } +common_peg_tokens::common_peg_tokens(const llama_vocab * vocab) { + const llama_token n_tokens = llama_vocab_n_tokens(vocab); + for (llama_token id = 0; id < n_tokens; ++id) { + const auto attr = llama_vocab_get_attr(vocab, id); + if (attr & (LLAMA_TOKEN_ATTR_CONTROL | LLAMA_TOKEN_ATTR_USER_DEFINED)) { + std::string text = llama_vocab_get_text(vocab, id); + ids.emplace(text, id); + tokens.emplace(id, common_peg_token{ std::move(text), attr }); + } + } +} + +llama_token common_peg_tokens::token_id(const std::string & text) const { + auto it = ids.find(text); + return it != ids.end() ? it->second : LLAMA_TOKEN_NULL; +} + +// Insert every delimiter the parser matches into the trie, starting from each node in from. Returns the end nodes. +// A choice adds the delimiters of each branch. A sequence joins every combination of its children. +static std::set insert_delimiter(common_trie & trie, const common_peg_arena & arena, common_peg_parser_id id, + std::set from = { 0 }) { + return std::visit([&](const auto & p) -> std::set { + using T = std::decay_t; + if constexpr (std::is_same_v || std::is_same_v) { + return insert_delimiter(trie, arena, p.child, std::move(from)); + } else if constexpr (std::is_same_v) { + std::set ends; + for (size_t node : from) { + size_t pos = 0; + while (pos < p.literal.size()) { + auto result = common_parse_utf8_codepoint(p.literal, pos); + if (result.status != utf8_parse_result::SUCCESS) { + break; + } + node = trie.extend(node, common_trie::symbol::codepoint(result.codepoint)); + pos += result.bytes_consumed; + } + ends.insert(node); + } + return ends; + } else if constexpr (std::is_same_v) { + std::set ends; + for (size_t node : from) { + ends.insert(trie.extend(node, common_trie::symbol::token(p.token))); + } + return ends; + } else if constexpr (std::is_same_v) { + std::set ends; + for (auto child : p.children) { + ends.merge(insert_delimiter(trie, arena, child, from)); + } + return ends; + } else if constexpr (std::is_same_v) { + for (auto child : p.children) { + from = insert_delimiter(trie, arena, child, std::move(from)); + } + return from; + } else { + throw std::invalid_argument("a delimiter may only be a sequence of literals, tokens, and choices of them, possibly wrapped in tags and atomics"); + } + }, arena.get(id)); +} + +// Build the matcher of an until parser, each pattern valued by the branch it belongs to +static common_trie build_until_matcher(const common_peg_arena & arena, + const std::vector & branches, + bool include) { + common_trie matcher; + for (size_t b = 0; b < branches.size(); b++) { + for (size_t end : insert_delimiter(matcher, arena, branches[b].delimiter)) { + if (end == 0) { + throw std::invalid_argument("delimiter must not match the empty string"); + } + // nothing follows a delimiter without include, so the first branch to claim it wins + auto owner = matcher.mark(end, (int32_t) b); + if (owner != (int32_t) b && include) { + throw std::invalid_argument("until branches " + std::to_string(owner) + " and " + std::to_string(b) + " must not share a delimiter"); + } + } + } + return matcher; +} + struct parser_executor; common_peg_parser_id common_peg_arena::add_parser(common_peg_parser_variant parser) { @@ -298,6 +381,49 @@ struct parser_executor { return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos); } + common_peg_parse_result operator()(const common_peg_token_parser & p) { + if (start_pos >= ctx.input.size()) { + if (!ctx.is_lenient()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos); + } + + if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] != p.token) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + + // Skip the rest of the piece, up to the next token or the end of the input + auto pos = start_pos + 1; + while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) { + ++pos; + } + + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos); + } + + common_peg_parse_result operator()(const common_peg_token_not_parser & p) { + if (start_pos >= ctx.input.size()) { + if (!ctx.is_lenient()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos); + } + + if (start_pos >= ctx.tokens.size() || ctx.tokens[start_pos] == LLAMA_TOKEN_NULL || + std::find(p.tokens.begin(), p.tokens.end(), ctx.tokens[start_pos]) != p.tokens.end()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos); + } + + // Skip the rest of the piece, up to the next token or the end of the input + auto pos = start_pos + 1; + while (pos < ctx.input.size() && ctx.tokens[pos] == LLAMA_TOKEN_NULL) { + ++pos; + } + + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos); + } + common_peg_parse_result operator()(const common_peg_sequence_parser & p) { if (ctx.is_debug()) { LOG_DBG("%sSEQ start at %zu '%s' (%zu children)\n", debug_indent().c_str(), start_pos, @@ -689,7 +815,11 @@ struct parser_executor { } common_peg_parse_result operator()(const common_peg_until_parser & p) const { - common_trie matcher(p.delimiters); + if (p.include) { + return parse_through(p); + } + + const auto & matcher = p.matcher; // Scan input and check for delimiters size_t pos = start_pos; @@ -697,24 +827,24 @@ struct parser_executor { std::vector invalid_utf8; while (pos < ctx.input.size()) { - auto utf8_result = common_parse_utf8_codepoint(ctx.input, pos); + auto step = matcher.next(ctx.input, ctx.tokens, pos); - if (utf8_result.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) { + if (step.status == utf8_parse_result::INCOMPLETE && ctx.is_lenient()) { // The rest of the sequence may still arrive, return what we have so far return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, last_valid_pos, {}, std::move(invalid_utf8)); } - if (utf8_result.status != utf8_parse_result::SUCCESS) { + if (step.status != utf8_parse_result::SUCCESS) { // Malformed UTF-8, or a sequence truncated by the end of a complete input. // A delimiter cannot start inside bytes that fail to decode, so consume them and move on - invalid_utf8.push_back({pos, utf8_result.bytes_consumed}); - pos += utf8_result.bytes_consumed; + invalid_utf8.push_back({pos, step.bytes_consumed}); + pos += step.bytes_consumed; last_valid_pos = pos; continue; } // Check if a delimiter starts at this position - auto match = matcher.check_at(ctx.input, pos); + auto match = matcher.check_at(ctx.input, ctx.tokens, pos); if (match == common_trie::COMPLETE_MATCH) { // Found a complete delimiter, return everything before it @@ -727,7 +857,7 @@ struct parser_executor { return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, pos, {}, std::move(invalid_utf8)); } - pos += utf8_result.bytes_consumed; + pos += step.bytes_consumed; last_valid_pos = pos; } @@ -738,6 +868,48 @@ struct parser_executor { return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, last_valid_pos, {}, std::move(invalid_utf8)); } + // Parse content, then the first branch whose delimiter and rest follow it, like C (D1 R1 | D2 R2 | ...) + common_peg_parse_result parse_through(const common_peg_until_parser & p) const { + auto content = arena.parse(p.content, ctx, start_pos); + if (content.fail() || content.need_more_input()) { + return content; + } + + auto pos = content.end; + for (const auto & branch : p.branches) { + auto nodes = content.nodes; + auto invalid_utf8 = content.invalid_utf8; + auto end = pos; + bool matched = true; + + for (auto id : { branch.delimiter, branch.rest }) { + if (id == COMMON_PEG_INVALID_PARSER_ID) { + continue; + } + auto result = arena.parse(id, ctx, end); + if (result.fail()) { + matched = false; + break; + } + nodes.insert(nodes.end(), result.nodes.begin(), result.nodes.end()); + invalid_utf8.insert(invalid_utf8.end(), result.invalid_utf8.begin(), result.invalid_utf8.end()); + end = result.end; + if (result.need_more_input()) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT, start_pos, end, std::move(nodes), std::move(invalid_utf8)); + } + } + if (matched) { + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_SUCCESS, start_pos, end, std::move(nodes), std::move(invalid_utf8)); + } + } + + if (p.optional && pos == ctx.input.size()) { + auto type = ctx.is_lenient() ? COMMON_PEG_PARSE_RESULT_NEED_MORE_INPUT : COMMON_PEG_PARSE_RESULT_SUCCESS; + return common_peg_parse_result(type, start_pos, pos, std::move(content.nodes), std::move(content.invalid_utf8)); + } + return common_peg_parse_result(COMMON_PEG_PARSE_RESULT_FAIL, start_pos, pos); + } + common_peg_parse_result operator()(const common_peg_schema_parser & p) { return arena.parse(p.child, ctx, start_pos); } @@ -823,10 +995,6 @@ struct parser_executor { common_peg_parse_result operator()(const common_peg_gbnf_parser & p) { return arena.parse(p.child, ctx, start_pos); } - - common_peg_parse_result operator()(const common_peg_ac_parser & p) { - return arena.parse(p.child, ctx, start_pos); - } }; common_peg_parse_result common_peg_arena::parse(common_peg_parse_context & ctx, size_t start) const { @@ -899,19 +1067,33 @@ void common_peg_arena::resolve_refs() { std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || - std::is_same_v) { + std::is_same_v) { p.child = resolve_ref(p.child); + } else if constexpr (std::is_same_v) { + if (p.content != COMMON_PEG_INVALID_PARSER_ID) { + p.content = resolve_ref(p.content); + } + for (auto & branch : p.branches) { + branch.delimiter = resolve_ref(branch.delimiter); + if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) { + branch.rest = resolve_ref(branch.rest); + } + } } else if constexpr (std::is_same_v) { p.child = resolve_ref(p.child); + if (p.start != COMMON_PEG_INVALID_PARSER_ID) { + p.start = resolve_ref(p.start); + p.rest = resolve_ref(p.rest); + } } else if constexpr (std::is_same_v) { p.child = resolve_ref(p.child); } else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || + std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || @@ -955,6 +1137,14 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id return "End"; } else if constexpr (std::is_same_v) { return "Literal(" + p.literal + ")"; + } else if constexpr (std::is_same_v) { + return "Token(" + p.piece + ", " + std::to_string(p.token) + ")"; + } else if constexpr (std::is_same_v) { + std::vector parts; + for (auto token : p.tokens) { + parts.push_back(std::to_string(token)); + } + return "TokenNot(" + string_join(parts, ", ") + ")"; } else if constexpr (std::is_same_v) { std::vector parts; for (const auto & child : p.children) { @@ -981,8 +1171,6 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id return "Atomic(" + dump_impl(p.child, visited) + ")"; } else if constexpr (std::is_same_v) { return "Gbnf(" + p.grammar + ", " + dump_impl(p.child, visited) + ")"; - } else if constexpr (std::is_same_v) { - return "Ac(" + string_join(p.delimiters, " | ") + ", " + dump_impl(p.child, visited) + ")"; } else if constexpr (std::is_same_v) { return "Any"; } else if constexpr (std::is_same_v) { @@ -995,7 +1183,18 @@ std::string common_peg_arena::dump_impl(common_peg_parser_id } else if constexpr (std::is_same_v) { return "String(" + std::string(1, p.delimiter) + ")"; } else if constexpr (std::is_same_v) { - return "Until(" + string_join(p.delimiters, " | ") + ")"; + std::vector branches; + for (const auto & branch : p.branches) { + auto text = dump_impl(branch.delimiter, visited); + if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) { + text += " " + dump_impl(branch.rest, visited); + } + branches.push_back(std::move(text)); + } + if (p.include) { + return "Until(" + dump_impl(p.content, visited) + ", " + string_join(branches, " | ") + (p.optional ? ", optional" : "") + ")"; + } + return "Until(" + string_join(branches, " | ") + ")"; } else if constexpr (std::is_same_v) { return "Schema(" + dump_impl(p.child, visited) + ", " + (p.node ? common_chat_schema::kind_name(p.node->kind()) : "null") + ")"; } else if constexpr (std::is_same_v) { @@ -1089,6 +1288,67 @@ common_peg_parser operator|(const std::string & str, const common_peg_parser & p common_peg_parser_builder::common_peg_parser_builder() {} +common_peg_parser_builder::common_peg_parser_builder(common_peg_tokens tokens) { + arena_.tokens_ = std::move(tokens); +} + +common_peg_parser common_peg_parser_builder::until_one_of(const std::vector & delimiters) { + common_peg_until_parser p; + for (const auto & d : delimiters) { + p.branches.push_back({ literal(d).id() }); + } + p.matcher = build_until_matcher(arena_, p.branches, p.include); + return add(std::move(p)); +} + +common_peg_parser common_peg_parser_builder::until(const common_peg_parser & delimiter) { + common_peg_until_parser p; + p.branches = { { delimiter.id() } }; + p.matcher = build_until_matcher(arena_, p.branches, p.include); + return add(std::move(p)); +} + +common_peg_parser common_peg_parser_builder::through(const common_peg_parser & content, const std::vector & branches, bool optional) { + if (branches.empty()) { + throw std::runtime_error("through requires at least one branch"); + } + common_peg_until_parser p; + p.branches = branches; + p.include = true; + p.optional = optional; + p.content = content.id(); + p.matcher = build_until_matcher(arena_, p.branches, p.include); + return add(std::move(p)); +} + +common_peg_parser common_peg_parser_builder::token(const std::string & piece) { + auto token = arena_.tokens_.token_id(piece); + if (token == LLAMA_TOKEN_NULL) { + return literal(piece); + } + return add(common_peg_token_parser{token, piece}); +} + +common_peg_parser common_peg_parser_builder::token(const std::vector & pieces, bool negate) { + if (!negate) { + std::vector alts; + for (const auto & piece : pieces) { + alts.push_back(token(piece)); + } + return choice(alts); + } + + common_peg_token_not_parser p; + for (const auto & piece : pieces) { + auto token = arena_.tokens_.token_id(piece); + if (token == LLAMA_TOKEN_NULL) { + throw std::invalid_argument("token is not registered with the builder: " + piece); + } + p.tokens.push_back(token); + } + return add(p); +} + common_peg_parser common_peg_parser_builder::sequence(const std::vector & parsers) { // Flatten nested sequences std::vector flattened; @@ -1195,6 +1455,17 @@ common_peg_parser common_peg_parser_builder::rule(const std::string & name, cons return ref(clean_name); } +common_peg_parser common_peg_parser_builder::trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest) { + common_trie scratch; + if (insert_delimiter(scratch, arena_, start.id()).count(0)) { + throw std::invalid_argument("trigger start must not match the empty string"); + } + auto clean_name = gbnf_format_rule_name(name); + auto rule_id = arena_.add_parser(common_peg_rule_parser{clean_name, (start + rest).id(), true, start.id(), rest.id()}); + arena_.add_rule(clean_name, rule_id); + return ref(clean_name); +} + void common_peg_parser_builder::set_root(const common_peg_parser & p) { arena_.set_root(p.id()); } @@ -1392,13 +1663,6 @@ common_peg_parser common_peg_parser_builder::json_member(const std::string & key }); } -common_peg_parser common_peg_parser_builder::ac(const common_peg_parser & p, const std::vector & delimiters) { - if (delimiters.empty()) { - throw std::runtime_error("ac parser requires at least one delimiter"); - } - return add(common_peg_ac_parser{p, delimiters}); -} - static std::string gbnf_escape_char_class(uint32_t c) { if (c == '-' || c == ']' || c == '[' || c == '\\') { return "\\" + std::string(1, (char) c); @@ -1457,15 +1721,63 @@ static std::string gbnf_char_class(const std::vector & chars, bool neg return s + "]"; } +// Token set such as <[1,5-9]>, with consecutive ids collapsed into ranges +static std::string gbnf_token_set(const std::vector & tokens, bool negate) { + std::string s = negate ? "!<[" : "<["; + for (size_t i = 0; i < tokens.size();) { + size_t j = i; + while (j + 1 < tokens.size() && tokens[j + 1] == tokens[j] + 1) { + j++; + } + s += (i == 0 ? "" : ",") + std::to_string(tokens[i]); + if (j > i) { + s += "-" + std::to_string(tokens[j]); + } + i = j + 1; + } + return s + "]>"; +} + +// Symbols on the transitions out of an automaton state, codepoints and tokens kept apart +struct gbnf_ac_symbols { + std::vector chars; + std::vector tokens; + + void add(const common_trie::symbol & sym) { + (sym.is_token() ? tokens : chars).push_back(sym.value); + } + + // One alternative for the codepoints and one for the tokens, each followed by next if given + std::vector alternatives(const std::string & next = "") const { + std::vector alts; + const std::string tail = next.empty() ? "" : " " + next; + if (!chars.empty()) { + alts.push_back(gbnf_char_class(chars, false) + tail); + } + if (!tokens.empty()) { + alts.push_back(gbnf_token_set(tokens, false) + tail); + } + return alts; + } +}; + static std::string gbnf_ac_grammar( - const common_grammar_builder & builder, - const std::string & prefix, - const std::vector & strings, - const std::function &, - const std::map> &, - const std::vector &, + const common_grammar_builder & builder, + const std::string & prefix, + const common_trie & trie, + const std::set & opaque, + const std::function &, + const std::map &, + const std::string &, const std::function &)> & build_rule) { - common_aho_corasick ac(strings); + common_aho_corasick ac(trie); + + // With only tokens in the alphabet, the grammar can step a whole token at a time + bool token_only = true; + for (const auto & sym : ac.alphabet) { + token_only = token_only && sym.is_token(); + } auto state_name = [&](size_t s) -> std::string { if (s == 0) { @@ -1481,27 +1793,43 @@ static std::string gbnf_ac_grammar( continue; // match states } - std::map> buckets; - std::vector completing; // chars that complete a delimiter - std::vector specific; // chars with an explicit transition - for (uint32_t c : ac.alphabet) { - size_t d = ac.next(q, c); + std::map buckets; + std::map completing_to; // completing symbols by the match state they reach + gbnf_ac_symbols completing; // symbols that complete a delimiter + gbnf_ac_symbols specific; // symbols with an explicit transition + for (const auto & sym : ac.alphabet) { + size_t d = ac.next(q, sym); if (ac.is_terminal(d)) { - completing.push_back(c); - specific.push_back(c); + completing.add(sym); + completing_to[d].add(sym); + specific.add(sym); } else if (d != 0) { - buckets[d].push_back(c); // specific non-root destination - specific.push_back(c); + buckets[d].add(sym); // specific non-root destination + specific.add(sym); } } - builder.add_rule(state_name(q), build_rule(completing, buckets, specific, state_name)); - } + // every other symbol goes back to the start + std::string fallback; + if (token_only) { + fallback = gbnf_token_set(specific.tokens, true); + } else { + fallback = specific.chars.empty() ? "." : gbnf_char_class(specific.chars, true); - // An empty delimiter makes the start state terminal. Emit an entry rule - // that matches the empty string so the returned reference stays valid. - if (ac.is_terminal(0)) { - builder.add_rule(prefix, "|"); + // Char rules never match a token named by a token rule, so allow the other named tokens by name + std::vector others; + for (auto token : opaque) { + if (std::find(specific.tokens.begin(), specific.tokens.end(), token) == specific.tokens.end()) { + others.push_back(token); + } + } + if (!others.empty()) { + fallback = "(" + fallback + " | " + gbnf_token_set(others, false) + ")"; + } + } + fallback += " " + state_name(0); + + builder.add_rule(state_name(q), build_rule(completing, completing_to, buckets, fallback, state_name)); } return state_name(0); @@ -1514,52 +1842,104 @@ static std::string gbnf_ac_grammar( // ref: https://github.com/ggml-org/llama.cpp/pull/24839 static std::string gbnf_excluding_grammar(const common_grammar_builder & builder, const std::string & prefix, - const std::vector & strings) { - return gbnf_ac_grammar(builder, prefix, strings, - [](const std::vector & /*completing*/, - const std::map> & buckets, - const std::vector & specific, + const common_trie & trie, + const std::set & opaque) { + return gbnf_ac_grammar(builder, prefix, trie, opaque, + [](const gbnf_ac_symbols & /*completing*/, + const std::map & /*completing_to*/, + const std::map & buckets, + const std::string & fallback, const std::function & state_name) { - // every state is accepting and completing chars get no - // alternative, so a forbidden string can never be matched + // every state accepts and completing symbols get no alternative, so a forbidden string never matches std::string rhs = "|"; - for (const auto & [d, chars] : buckets) { - rhs += " " + gbnf_char_class(chars, false) + " " + state_name(d) + " |"; + for (const auto & [d, symbols] : buckets) { + for (const auto & alt : symbols.alternatives(state_name(d))) { + rhs += " " + alt + " |"; + } } - rhs += " " + gbnf_char_class(specific, true) + " " + state_name(0); + rhs += " " + fallback; return rhs; }); } -// GBNF grammar matching everything up to and including the first occurrence of -// any string in `strings`. Emits the Aho-Corasick automaton DFA and returns -// the start state rule name. -static std::string gbnf_including_grammar(const common_grammar_builder & builder, - const std::string & prefix, - const std::vector & strings) { - return gbnf_ac_grammar(builder, prefix, strings, - [](const std::vector & completing, - const std::map> & buckets, - const std::vector & specific, - const std::function & state_name) { +// GBNF grammar matching up to the first pattern in the trie, then the rest rule of that pattern's value. +// For the pattern "ab" with rest "x": +// +// prefix ::= [a] prefix-01 | [^a] prefix +// prefix-01 ::= [b] rest | [a] prefix-01 | [^ab] prefix +// rest ::= "x" +static std::string gbnf_including_grammar(const common_grammar_builder & builder, + const std::string & prefix, + const common_trie & trie, + const std::set & opaque, + const std::vector & rests, + bool optional) { + common_aho_corasick ac(trie); + + // every pattern ending at a match state, the longest and the ones reached by suffix links + auto rests_at = [&](size_t s, bool & terminal) { + std::vector alts; + terminal = false; + for (; s != 0; s = ac.fail[s]) { + auto pattern = ac.t.nodes[s].pattern; + if (pattern < 0) { + continue; + } + if (rests[pattern].empty()) { + terminal = true; + } else if (std::find(alts.begin(), alts.end(), rests[pattern]) == alts.end()) { + alts.push_back(rests[pattern]); + } + } + return alts; + }; + + return gbnf_ac_grammar(builder, prefix, trie, opaque, + [&](const gbnf_ac_symbols & /*completing*/, + const std::map & completing_to, + const std::map & buckets, + const std::string & fallback, + const std::function & state_name) { std::vector alts; - if (!completing.empty()) { - alts.push_back(gbnf_char_class(completing, false)); // terminate on match + gbnf_ac_symbols terminating; // symbols that complete a pattern with no rest + for (const auto & [d, symbols] : completing_to) { + bool terminal = false; + auto rest = rests_at(d, terminal); + if (!rest.empty()) { + for (auto & alt : symbols.alternatives(rest.size() == 1 ? rest[0] : "(" + string_join(rest, " | ") + ")")) { + alts.push_back(std::move(alt)); + } + } + if (terminal) { + terminating.chars.insert(terminating.chars.end(), symbols.chars.begin(), symbols.chars.end()); + terminating.tokens.insert(terminating.tokens.end(), symbols.tokens.begin(), symbols.tokens.end()); + } } - for (const auto & [d, chars] : buckets) { - alts.push_back(gbnf_char_class(chars, false) + " " + state_name(d)); + for (auto & alt : terminating.alternatives()) { + alts.push_back(std::move(alt)); } - // every other character keeps scanning from the start state - alts.push_back(gbnf_char_class(specific, true) + " " + state_name(0)); - return string_join(alts, " | "); + for (const auto & [d, symbols] : buckets) { + for (auto & alt : symbols.alternatives(state_name(d))) { + alts.push_back(std::move(alt)); + } + } + // every other symbol keeps scanning from the start state + alts.push_back(fallback); + return (optional ? "| " : "") + string_join(alts, " | "); }); } -static std::set collect_reachable_rules( +// The rules and the tokens named by token rules that the grammar of a parser reaches +struct common_peg_reachable { + std::set rules; + std::set tokens; +}; + +static void collect_reachable( const common_peg_arena & arena, - const common_peg_parser_id & rule + const common_peg_parser_id & root, + common_peg_reachable & reachable ) { - std::set reachable; std::set visited; std::function visit = [&](common_peg_parser_id id) { @@ -1571,13 +1951,27 @@ static std::set collect_reachable_rules( if constexpr (std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) { // These parsers do not have any children + } else if constexpr (std::is_same_v) { + reachable.tokens.insert(p.token); + } else if constexpr (std::is_same_v) { + reachable.tokens.insert(p.tokens.begin(), p.tokens.end()); + } else if constexpr (std::is_same_v) { + // The delimiters name their tokens in the grammar + if (p.content != COMMON_PEG_INVALID_PARSER_ID) { + visit(p.content); + } + for (const auto & branch : p.branches) { + visit(branch.delimiter); + if (branch.rest != COMMON_PEG_INVALID_PARSER_ID) { + visit(branch.rest); + } + } } else if constexpr (std::is_same_v) { for (auto child : p.children) { visit(child); @@ -1592,13 +1986,12 @@ static std::set collect_reachable_rules( std::is_same_v || std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v) { visit(p.child); } else if constexpr (std::is_same_v) { if (visited.find(p.name) == visited.end()) { visited.insert(p.name); - reachable.insert(p.name); + reachable.rules.insert(p.name); visit(p.child); } } else if constexpr (std::is_same_v) { @@ -1611,12 +2004,13 @@ static std::set collect_reachable_rules( }, parser); }; - visit(rule); - return reachable; + visit(root); } // GBNF generation implementation void common_peg_arena::build_grammar(const common_grammar_builder & builder, bool lazy) const { + common_peg_reachable reachable; + // A raw string value is parsed by the child rather than constrained by the schema auto schema_delegates = [](const common_peg_schema_parser & s) -> bool { return !s.node || (s.raw && s.node->may_be_string()); @@ -1655,6 +2049,10 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo return ""; } else if constexpr (std::is_same_v) { return gbnf_format_literal(p.literal); + } else if constexpr (std::is_same_v) { + return "<[" + std::to_string(p.token) + "]>"; + } else if constexpr (std::is_same_v) { + return gbnf_token_set(std::vector(p.tokens.begin(), p.tokens.end()), true); } else if constexpr (std::is_same_v) { std::string s; for (const auto & child : p.children) { @@ -1746,10 +2144,19 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo const std::string delim(1, p.delimiter); return R"(( [^)" + delim + R"(\\] | "\\" ( [)" + delim + R"(\\/ bfnrt] | "u" [0-9a-fA-F]{4} ) )*)"; } else if constexpr (std::is_same_v) { - if (p.delimiters.empty()) { - return ".*"; + auto prefix = "until-" + std::to_string(id); + if (!p.include) { + if (p.branches.empty()) { + return ".*"; + } + return gbnf_excluding_grammar(builder, prefix, p.matcher, reachable.tokens); + } + std::vector branch_rests; + for (size_t b = 0; b < p.branches.size(); b++) { + auto rest = p.branches[b].rest; + branch_rests.push_back(rest == COMMON_PEG_INVALID_PARSER_ID ? "" : builder.add_rule(prefix + "-rest-" + std::to_string(b), to_gbnf(rest))); } - return gbnf_excluding_grammar(builder, "until-" + std::to_string(id), p.delimiters); + return gbnf_including_grammar(builder, prefix, p.matcher, reachable.tokens, branch_rests, p.optional); } else if constexpr (std::is_same_v) { if (schema_delegates(p)) { return to_gbnf(p.child); @@ -1766,38 +2173,52 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo return to_gbnf(p.child); } else if constexpr (std::is_same_v) { return p.grammar; - } else if constexpr (std::is_same_v) { - return gbnf_including_grammar(builder, "ac-" + std::to_string(id), p.delimiters); } else { static_assert(is_always_false_v); } }, parser); }; - // Collect reachable rules - std::set reachable_rules; - - if (lazy) { - // Collect rules reachable from trigger rules - for (const auto & [name, id] : rules_) { - const auto & parser = parsers_.at(id); - if (auto rule = std::get_if(&parser)) { - if (rule->trigger) { - // Mark trigger as reachable and visit it - reachable_rules.insert(name); - auto add_rules = collect_reachable_rules(*this, id); - reachable_rules.insert(add_rules.begin(), add_rules.end()); - } + // Trigger rules, sorted for a predictable order + std::vector trigger_rules; + for (const auto & [name, id] : rules_) { + if (auto rule = std::get_if(&parsers_.at(id))) { + if (rule->trigger) { + trigger_rules.push_back(rule); + } + } + } + std::sort(trigger_rules.begin(), trigger_rules.end(), [](const auto * a, const auto * b) { return a->name < b->name; }); + + // A lazy grammar scans for the starts when the trigger rules were built from a start and rest + bool scans = false; + for (const auto * rule : trigger_rules) { + scans = scans || rule->start != COMMON_PEG_INVALID_PARSER_ID; + } + if (scans) { + for (const auto * rule : trigger_rules) { + if (rule->start == COMMON_PEG_INVALID_PARSER_ID) { + throw std::runtime_error("trigger rule without a start in a scanning grammar: " + rule->name); } } + } + + if (lazy && scans) { + for (const auto * rule : trigger_rules) { + collect_reachable(*this, rule->start, reachable); + collect_reachable(*this, rule->rest, reachable); + } + } else if (lazy) { + for (const auto * rule : trigger_rules) { + collect_reachable(*this, rules_.at(rule->name), reachable); + } } else { - // Collect rules reachable from root - reachable_rules = collect_reachable_rules(*this, root_); + collect_reachable(*this, root_, reachable); } // Create GBNF rules for all reachable rules for (const auto & [name, rule_id] : rules_) { - if (reachable_rules.find(name) == reachable_rules.end()) { + if (reachable.rules.find(name) == reachable.rules.end()) { continue; } @@ -1807,20 +2228,27 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo } } - if (lazy) { - // Generate root rule from trigger rules only - std::vector trigger_names; - for (const auto & [name, rule_id] : rules_) { - const auto & parser = parsers_.at(rule_id); - if (auto rule = std::get_if(&parser)) { - if (rule->trigger) { - trigger_names.push_back(rule->name); + if (lazy && scans) { + // The root scans for a trigger start and then constrains its rest + common_trie starts; + std::vector rests; + for (const auto * rule : trigger_rules) { + auto value = (int32_t) rests.size(); + rests.push_back(builder.add_rule(rule->name + "-rest", to_gbnf(rule->rest))); + for (size_t end : insert_delimiter(starts, *this, rule->start)) { + auto owner = starts.mark(end, value); + if (owner != value) { + throw std::runtime_error("trigger rules " + trigger_rules[owner]->name + " and " + rule->name + " must not share a start"); } } } - - // Sort for predictable order - std::sort(trigger_names.begin(), trigger_names.end()); + builder.add_rule("root", gbnf_including_grammar(builder, "trigger", starts, reachable.tokens, rests, /* optional = */ true)); + } else if (lazy) { + // Generate root rule from trigger rules only + std::vector trigger_names; + for (const auto * rule : trigger_rules) { + trigger_names.push_back(rule->name); + } builder.add_rule("root", string_join(trigger_names, " | ")); } else if (root_ != COMMON_PEG_INVALID_PARSER_ID) { builder.add_rule("root", to_gbnf(root_)); diff --git a/common/peg-parser.h b/common/peg-parser.h index 46df99875d35..b7e97083b386 100644 --- a/common/peg-parser.h +++ b/common/peg-parser.h @@ -3,6 +3,7 @@ #include "json-schema.h" #include "json.h" #include "llama.h" +#include "trie.h" #include #include @@ -188,6 +189,22 @@ struct common_peg_recursion_error : std::invalid_argument { using std::invalid_argument::invalid_argument; }; +struct common_peg_token { + std::string text; + llama_token_attr attr; +}; + +struct common_peg_tokens { + std::unordered_map tokens; + std::unordered_map ids; + + common_peg_tokens() = default; + explicit common_peg_tokens(const llama_vocab * vocab); + + // LLAMA_TOKEN_NULL if text is not a special token + llama_token token_id(const std::string & text) const; +}; + struct common_peg_parse_context { std::string input; // [h, e, l, l, o, _, w, o, r, l, d] std::vector tokens; // [id, -1, -1, -1, -1, id, -1, -1, -1, -1, -1] @@ -226,6 +243,16 @@ struct common_peg_literal_parser { std::string literal; }; +struct common_peg_token_parser { + llama_token token; + std::string piece; +}; + +// Matches one token that is not one of the tokens +struct common_peg_token_not_parser { + std::vector tokens; +}; + struct common_peg_sequence_parser { std::vector children; }; @@ -270,8 +297,18 @@ struct common_peg_string_parser { char delimiter; }; +// A delimiter an until parser stops at, and the parser that follows it when the delimiter is consumed +struct common_peg_until_branch { + common_peg_parser_id delimiter; + common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID; +}; + struct common_peg_until_parser { - std::vector delimiters; + std::vector branches; + bool include = false; // consume the first delimiter and parse the rest of its branch + bool optional = false; // with include, the input may end before any delimiter + common_peg_parser_id content = COMMON_PEG_INVALID_PARSER_ID; // with include, parsed up to the delimiter + common_trie matcher; // each pattern valued by its branch }; struct common_peg_schema_parser { @@ -288,6 +325,9 @@ struct common_peg_rule_parser { std::string name; common_peg_parser_id child; bool trigger; + // set when the rule has a start and rest, the lazy grammar scans for the start + common_peg_parser_id start = COMMON_PEG_INVALID_PARSER_ID; + common_peg_parser_id rest = COMMON_PEG_INVALID_PARSER_ID; }; struct common_peg_ref_parser { @@ -308,17 +348,14 @@ struct common_peg_gbnf_parser { std::string grammar; }; -struct common_peg_ac_parser { - common_peg_parser_id child; - std::vector delimiters; -}; - // Variant holding all parser types using common_peg_parser_variant = std::variant< common_peg_epsilon_parser, common_peg_start_parser, common_peg_end_parser, common_peg_literal_parser, + common_peg_token_parser, + common_peg_token_not_parser, common_peg_sequence_parser, common_peg_choice_parser, common_peg_repetition_parser, @@ -334,14 +371,14 @@ using common_peg_parser_variant = std::variant< common_peg_ref_parser, common_peg_atomic_parser, common_peg_tag_parser, - common_peg_gbnf_parser, - common_peg_ac_parser + common_peg_gbnf_parser >; class common_peg_arena { std::vector parsers_; std::unordered_map rules_; common_peg_parser_id root_ = COMMON_PEG_INVALID_PARSER_ID; + common_peg_tokens tokens_; public: const common_peg_parser_variant & get(common_peg_parser_id id) const { return parsers_.at(id); } @@ -356,6 +393,8 @@ class common_peg_arena { common_peg_parser_id root() const { return root_; } void set_root(common_peg_parser_id id) { root_ = id; } + const common_peg_tokens & tokens() const { return tokens_; } + common_peg_parse_result parse(common_peg_parse_context & ctx, size_t start = 0) const; common_peg_parse_result parse(common_peg_parser_id id, common_peg_parse_context & ctx, size_t start) const; @@ -384,6 +423,7 @@ class common_peg_parser_builder { public: common_peg_parser_builder(); + explicit common_peg_parser_builder(common_peg_tokens tokens); // Match nothing, always succeed. // S -> ε @@ -401,6 +441,16 @@ class common_peg_parser_builder { // S -> "hello" common_peg_parser literal(const std::string & literal) { return add(common_peg_literal_parser{literal}); } + // Matches a token. Falls back to a literal if the token is not registered with the builder. + // S -> <[token-id]> + common_peg_parser token(const std::string & piece); + + // Matches one of the tokens. With negate, matches one token that is not in the set. + // A negated set may only name tokens registered with the builder. + // S -> <[id1]> | <[id2]> | ... or !<[id1,id2,...]> + common_peg_parser token(const std::vector & pieces, bool negate = false); + common_peg_parser token(std::initializer_list pieces, bool negate = false) { return token(std::vector(pieces), negate); } + // Matches a sequence of parsers in order, all must succeed. // S -> A B C common_peg_parser sequence() { return add(common_peg_sequence_parser{}); } @@ -457,16 +507,29 @@ class common_peg_parser_builder { // Matches all characters until a delimiter is found (delimiter not consumed). // Invalid UTF-8 is consumed and recorded on the AST nodes. // S -> (!delim .)* - common_peg_parser until(const std::string & delimiter) { return add(common_peg_until_parser{{delimiter}}); } + common_peg_parser until(const std::string & delimiter) { return until_one_of({delimiter}); } // Matches all characters until one of the delimiters in the list is found (delimiter not consumed). // S -> (!delim .)* - common_peg_parser until_one_of(const std::vector & delimiters) { return add(common_peg_until_parser{delimiters}); } + common_peg_parser until_one_of(const std::vector & delimiters); + + // Matches all characters until the delimiter is found (delimiter not consumed). + // The delimiter may only be a sequence of literals, tokens, and choices of them. Tags and atomics may wrap them. + // S -> (!delim .)* + common_peg_parser until(const common_peg_parser & delimiter); // Matches everything // S -> .* common_peg_parser rest() { return until_one_of({}); } + // Matches content, then the first delimiter, then the rest of the branch of that delimiter. + // Branches must not share a delimiter. With optional, the input may end before any delimiter. + // S -> C (D1 R1 | D2 R2 | ...) + common_peg_parser through(const common_peg_parser & content, const std::vector & branches, bool optional = false); + common_peg_parser through(const common_peg_parser & content, std::initializer_list branches, bool optional = false) { return through(content, std::vector(branches), optional); } + common_peg_parser through(const common_peg_parser & content, const common_peg_parser & delimiter) { return through(content, { { delimiter } }); } + common_peg_parser through(const common_peg_parser & content, const std::string & delimiter) { return through(content, literal(delimiter)); } + // Matches between min and max repetitions of a parser (inclusive). // S -> A{m,n} // Use -1 for max to represent unbounded repetition (equivalent to {m,}) @@ -537,6 +600,10 @@ class common_peg_parser_builder { common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & p) { return rule(name, p, true); } common_peg_parser trigger_rule(const std::string & name, const std::function & builder) { return rule(name, builder, true); } + // Creates a trigger rule that matches start followed by rest. A lazy grammar scans for the start of any such rule, then only allows its rest. + // The start has the same limits as an until() delimiter. + common_peg_parser trigger_rule(const std::string & name, const common_peg_parser & start, const common_peg_parser & rest); + // Creates an atomic parser. Atomic parsers do not create an AST node if // the child results in a partial parse, i.e. NEEDS_MORE_INPUT. This is // intended for situations where partial output is undesirable. @@ -550,13 +617,6 @@ class common_peg_parser_builder { // the child's grammar. Parsing delegates entirely to the child. common_peg_parser gbnf(const common_peg_parser & p, const std::string & grammar) { return add(common_peg_gbnf_parser{p, grammar}); } - // Wraps a child parser but emits a GBNF grammar built from the Aho-Corasick - // automaton of `delimiters`, matching everything up to and including the - // first delimiter. Parsing delegates entirely to the child, which is - // responsible for consuming the delimiter (e.g. until(D) + literal(D)). - common_peg_parser ac(const common_peg_parser & p, const std::vector & delimiters); - common_peg_parser ac(const common_peg_parser & p, const std::string & delimiter) { return ac(p, std::vector{delimiter}); } - void set_root(const common_peg_parser & p); common_peg_arena build(); diff --git a/common/reasoning-budget.cpp b/common/reasoning-budget.cpp index 81b7c3e56cdb..ac2cd261db08 100644 --- a/common/reasoning-budget.cpp +++ b/common/reasoning-budget.cpp @@ -31,14 +31,18 @@ struct token_matcher { static common_trie build_trie(const std::vector & seqs) { common_trie t; for (const auto & seq : seqs) { - t.insert(std::vector(seq.begin(), seq.end())); + std::vector symbols; + for (llama_token token : seq) { + symbols.push_back(common_trie::symbol::token(token)); + } + t.insert(symbols); } return t; } // returns the index into seqs of the longest sequence ending at this token, or -1 int32_t advance(llama_token token) { - state = ac.next(state, (uint32_t) token); + state = ac.next(state, common_trie::symbol::token(token)); const int32_t p = ac.match_pattern(state); if (p >= 0) { state = 0; diff --git a/common/trie.cpp b/common/trie.cpp index b5c9666ba2ee..b009b7044fa2 100644 --- a/common/trie.cpp +++ b/common/trie.cpp @@ -4,26 +4,46 @@ #include +common_trie::step common_trie::next(std::string_view sv, const std::vector & token_map, size_t pos) const { + if (!tokens.empty() && pos < token_map.size()) { + const int32_t id = token_map[pos]; + if (id >= 0 && tokens.find(id) != tokens.end()) { + size_t end = pos + 1; + while (end < token_map.size() && token_map[end] < 0) { + ++end; + } + return { utf8_parse_result::SUCCESS, symbol::token(id), end - pos }; + } + } + + auto result = common_parse_utf8_codepoint(sv, pos); + return { result.status, symbol::codepoint(result.codepoint), result.bytes_consumed }; +} + common_trie::match_result common_trie::check_at(std::string_view sv, size_t start_pos) const { + return check_at(sv, {}, start_pos); +} + +common_trie::match_result common_trie::check_at(std::string_view sv, const std::vector & token_map, size_t start_pos) const { size_t current = 0; // Start at root size_t pos = start_pos; // LOG_DBG("%s: checking at pos %zu, sv='%s'\n", __func__, start_pos, std::string(sv).c_str()); while (pos < sv.size()) { - auto result = common_parse_utf8_codepoint(sv, pos); - if (result.status != utf8_parse_result::SUCCESS) { + auto step = next(sv, token_map, pos); + if (step.status != utf8_parse_result::SUCCESS) { break; } - auto it = nodes[current].children.find(result.codepoint); + auto it = nodes[current].children.find(step.symbol); if (it == nodes[current].children.end()) { // Can't continue matching return match_result{match_result::NO_MATCH}; } current = it->second; - pos += result.bytes_consumed; + pos += step.bytes_consumed; // Check if we've matched a complete word if (nodes[current].pattern >= 0) { @@ -42,7 +62,7 @@ common_trie::match_result common_trie::check_at(std::string_view sv, size_t star } int32_t common_trie::insert(const std::string & word) { - std::vector symbols; + std::vector symbols; size_t pos = 0; while (pos < word.length()) { auto result = common_parse_utf8_codepoint(word, pos); @@ -50,28 +70,42 @@ int32_t common_trie::insert(const std::string & word) { break; } - symbols.push_back(result.codepoint); + symbols.push_back(symbol::codepoint(result.codepoint)); pos += result.bytes_consumed; } return insert(symbols); } -int32_t common_trie::insert(const std::vector & symbols) { +int32_t common_trie::insert(const std::vector & symbols) { size_t current = 0; - for (uint32_t ch : symbols) { - auto it = nodes[current].children.find(ch); - if (it == nodes[current].children.end()) { - size_t child = create_node(); - nodes[current].children[ch] = child; - current = child; - } else { - current = it->second; - } + for (symbol ch : symbols) { + current = extend(current, ch); + } + int32_t pattern = mark(current, n_patterns); + if (pattern == n_patterns) { + n_patterns++; } - if (nodes[current].pattern < 0) { - nodes[current].pattern = n_patterns++; + return pattern; +} + +size_t common_trie::extend(size_t node, symbol ch) { + if (ch.is_token()) { + tokens.insert((int32_t) ch.value); + } + auto it = nodes[node].children.find(ch); + if (it != nodes[node].children.end()) { + return it->second; + } + size_t child = create_node(); + nodes[node].children[ch] = child; + return child; +} + +int32_t common_trie::mark(size_t node, int32_t value) { + if (nodes[node].pattern < 0) { + nodes[node].pattern = value; } - return nodes[current].pattern; + return nodes[node].pattern; } common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie)) { @@ -113,7 +147,7 @@ common_aho_corasick::common_aho_corasick(common_trie trie) : t(std::move(trie)) } } -size_t common_aho_corasick::next(size_t state, uint32_t ch) const { +size_t common_aho_corasick::next(size_t state, common_trie::symbol ch) const { const auto & nodes = t.nodes; while (state && nodes[state].children.find(ch) == nodes[state].children.end()) { state = fail[state]; diff --git a/common/trie.h b/common/trie.h index 0f7b16a36ad2..8c31d7263ddb 100644 --- a/common/trie.h +++ b/common/trie.h @@ -1,5 +1,7 @@ #pragma once +#include "unicode.h" + #include #include #include @@ -10,13 +12,42 @@ // Trie for matching multiple literals. // This is used in common_peg_until_parser and to build a GBNF exclusion grammar struct common_trie { + // A symbol is either a UTF-8 codepoint or a token + struct symbol { + enum kind_type : uint8_t { CODEPOINT, TOKEN }; + + kind_type kind = CODEPOINT; + uint32_t value = 0; + + static symbol codepoint(uint32_t cpt) { return { CODEPOINT, cpt }; } + static symbol token(int32_t id) { return { TOKEN, (uint32_t) id }; } + + bool is_token() const { return kind == TOKEN; } + + bool operator<(const symbol & other) const { + return kind != other.kind ? kind < other.kind : value < other.value; + } + bool operator==(const symbol & other) const { + return kind == other.kind && value == other.value; + } + }; + + struct step { + enum utf8_parse_result::status status; + common_trie::symbol symbol; + size_t bytes_consumed; + }; + struct node { - std::map children; // Use uint32_t to store Unicode codepoints + std::map children; int32_t pattern = -1; // index of the pattern ending at this node, -1 if none }; std::vector nodes; + // every token id used by a pattern, the input is split so these match as single symbols + std::set tokens; + common_trie() { create_node(); // root node } @@ -29,15 +60,25 @@ struct common_trie { enum match_result { NO_MATCH, PARTIAL_MATCH, COMPLETE_MATCH }; + // Read the symbol at pos. It is a token if a pattern uses the token at pos, else a UTF-8 codepoint. + step next(std::string_view sv, const std::vector & token_map, size_t pos) const; + // Check if a delimiter starts at the given position match_result check_at(std::string_view sv, size_t start_pos) const; + match_result check_at(std::string_view sv, const std::vector & token_map, size_t start_pos) const; // Insert a word as a sequence of Unicode codepoints, returns its pattern index int32_t insert(const std::string & word); - // Insert a raw symbol sequence, returns its pattern index (insertion order, - // duplicates keep the first index) - int32_t insert(const std::vector & symbols); + // Insert a symbol sequence, returns its pattern index (insertion order, duplicates keep the first index) + int32_t insert(const std::vector & symbols); + + // Child of node on a symbol, created if missing + size_t extend(size_t node, symbol ch); + + // Mark node as the end of a pattern with a value from the caller. Returns the value already there, or value if the node had none. + // A trie must take its values from mark or from insert, not both. + int32_t mark(size_t node, int32_t value); private: int32_t n_patterns = 0; @@ -51,11 +92,11 @@ struct common_trie { // Aho-Corasick automaton struct common_aho_corasick { - common_trie t; - std::vector fail; // failure links - std::vector order; // states in BFS order - std::vector match; // longest pattern ending at each state (directly or via a suffix link), -1 if none - std::set alphabet; // every character with a transition + common_trie t; + std::vector fail; // failure links + std::vector order; // states in BFS order + std::vector match; // longest pattern ending at each state (directly or via a suffix link), -1 if none + std::set alphabet; // every symbol with a transition common_aho_corasick(common_trie trie); @@ -69,5 +110,5 @@ struct common_aho_corasick { int32_t match_pattern(size_t s) const { return match[s]; } // follow failure links until a transition on `ch` exists. - size_t next(size_t state, uint32_t ch) const; + size_t next(size_t state, common_trie::symbol ch) const; }; diff --git a/docs/development/parsing.md b/docs/development/parsing.md index ab0ccad80bfa..faa64afded0c 100644 --- a/docs/development/parsing.md +++ b/docs/development/parsing.md @@ -67,6 +67,8 @@ For a more complete example, see `test_example_native()` in - **`end()`** - Matches the end of input (anchor `$`) - **`literal(string)`** - Matches an exact literal string - **`any()`** - Matches any single character (`.`) +- **`token(piece)`** - Matches a special token, or the literal `piece` if it is not registered with the builder (see [Special Tokens](#special-tokens)) +- **`token(pieces, negate)`** - Matches one of the tokens, or with `negate` one token that is not one of them ### Combinators @@ -89,6 +91,8 @@ For a more complete example, see `test_example_native()` in - **`space()`** - Matches zero or more whitespace characters (space, tab, newline) - **`until(delimiter)`** - Matches characters until delimiter is found (delimiter not consumed) - **`until_one_of(delimiters)`** - Matches characters until any delimiter in the list is found +- **`until(parser)`** - Matches characters until a delimiter built from literals and tokens is found (delimiter not consumed, see [until(parser)](#untilparser)) +- **`through(content, branches, optional)`** - Matches content, then the first delimiter found and the rest of its branch (delimiter consumed). The grammar scans for the delimiters instead of following content - **`rest()`** - Matches everything remaining (`.*`) ### JSON Parsers @@ -108,6 +112,7 @@ For a more complete example, see `test_example_native()` in - **`ref(name)`** - Creates a lightweight reference to a named rule (for recursive grammars) - **`rule(name, p, trigger)`** - Creates a named rule and returns a reference - **`trigger_rule(name, p)`** - Creates a trigger rule (entry point for lazy grammar generation) +- **`trigger_rule(name, start, rest)`** - Creates a trigger rule matching `start` then `rest`, gating the lazy grammar on the start - **`schema(p, name, schema, raw)`** - Wraps parser with JSON schema metadata for grammar generation - **`schema(p, name, doc, node, raw)`** - Same, for a node of a `common_chat_schema_document` built earlier, e.g. one tool parameter @@ -116,6 +121,110 @@ For a more complete example, see `test_example_native()` in - **`atomic(p)`** - Prevents AST node creation for partial parses - **`tag(tag, p)`** - Creates AST nodes with semantic tags (multiple nodes can share tags) +## Special Tokens + +Matching a special token by its text alone is ambiguous: a model may emit +`<|end|>` as a single control token, or spell it out as plain text, such as +when quoting a chat template. The parser can tell them apart when the builder +knows the special tokens of the vocabulary, and the input carries the ids of +the tokens that produced it. + +A `common_peg_tokens` table constructed from a `llama_vocab` registers every +control and user-defined token. Pass it to the builder: + +```cpp +common_peg_tokens specials(vocab); + +auto parser = build_chat_peg_parser(specials, [&](common_chat_peg_builder & p) { + return p.content(p.until(p.token("<|end|>"))) + p.token("<|end|>"); +}); +``` + +Chat templates initialized with a model build this table from its vocabulary, +and format handlers receive it as `inputs.specials`. + +### token() + +`token(piece)` matches only where the input holds the id of that token, and +consumes the whole piece. The same characters without the id do not match. +If `piece` is not registered with the builder, it falls back to +`literal(piece)`. + +`token(pieces)` matches any of the tokens, and `token(pieces, true)` matches one +token that is not in the set. Every piece of a negated set must be registered, +otherwise it throws `std::invalid_argument`. + +In the grammar, a token emits `<[id]>` and a negated set emits `!<[...]>`: + +```cpp +p.token({ "
", "" }) + p.token({ "", "" }, true) +``` + +``` +root ::= (<[1]> | <[2]>) !<[1-2]> +``` + +### until(parser) + +`until(delimiter)` with a parser instead of a string stops at a delimiter that +may contain tokens, or several literals joined in a sequence: + +```cpp +auto end = p.token("<|end|>"); +auto final = p.token("<|channel|>") + p.literal("final"); + +p.reasoning(p.until(end | final)) +``` + +The delimiter may only be built from: + +- `literal()` and `token()` +- `sequence()` and `choice()` of the above +- `tag()` and `atomic()` wrapping any of the above + +Any other parser throws `std::invalid_argument`. A choice inside a sequence +expands to every combination, so `"a" + ("b" | "d")` stops at both `ab` and +`ad`. + +The grammar scans for the delimiters the same way as `until_one_of()`: + +```cpp +p.until((p.literal("a") + p.literal("b")) | p.literal("cd")) +``` + +``` +root ::= until-5 +until-5 ::= | [a] until-5-01 | [c] until-5-03 | [^ac] until-5 +until-5-01 ::= | [a] until-5-01 | [c] until-5-03 | [^abc] until-5 +until-5-03 ::= | [a] until-5-01 | [c] until-5-03 | [^acd] until-5 +``` + +A token never matches a character rule such as `.` or `[^a]`, so the scan lets +the other tokens named elsewhere in the grammar through by name. Here `` is +token 2: + +```cpp +p.until(p.token("") + p.literal("x")) + p.token("") + p.literal("x") + p.token("") +``` + +``` +root ::= until-3 <[1]> "x" <[2]> +until-3 ::= | <[1]> until-3-01 | (. | <[2]>) until-3 +until-3-01 ::= | <[1]> until-3-01 | ([^x] | <[2]>) until-3 +``` + +When the delimiters are made of tokens alone, the scan consumes whole tokens +with a negated token set instead: + +```cpp +p.until(p.token("")) + p.token("") +``` + +``` +root ::= until-1 <[1]> +until-1 ::= | !<[1]> until-1 +``` + ## GBNF Grammar Generation The PEG parser also acts as a convenient DSL for generating GBNF grammars, with @@ -143,6 +252,28 @@ are emitted in the grammar. All trigger rules are added as alternations in the root rule. It is still necessary to define trigger patterns, as the parser has no interaction with the grammar sampling. +With `trigger_rule(name, start, rest)`, the grammar instead scans for a start and +then constrains the rest. It runs from the first token, so `grammar_lazy` is false +and no trigger patterns are needed. For example: + +```cpp +auto ab = p.literal("ab"); +auto cd = p.literal("cd"); +return p.until(ab | cd) + (p.trigger_rule("one", ab, p.literal("x")) | p.trigger_rule("two", cd, p.literal("y"))); +``` + +``` +root ::= trigger +trigger ::= | [a] trigger-01 | [c] trigger-03 | [^ac] trigger +trigger-01 ::= | [b] one-rest | [a] trigger-01 | [c] trigger-03 | [^abc] trigger +trigger-03 ::= | [d] two-rest | [a] trigger-01 | [c] trigger-03 | [^acd] trigger +one-rest ::= "x" +two-rest ::= "y" +``` + +A start may only be a sequence of literals, tokens, and choices of them, possibly +wrapped in tags and atomics. + ### JSON Schema The `schema(p, name, schema, raw)` parser will use the `json-schema-to-grammar` diff --git a/grammars/README.md b/grammars/README.md index f005fc2522b8..b35946a4afe8 100644 --- a/grammars/README.md +++ b/grammars/README.md @@ -73,11 +73,13 @@ Tokens allow grammars to match specific tokenizer tokens rather than character s Tokens can be specified in two ways: -1. **Token ID**: Use angle brackets with the token ID in square brackets: `<[token-id]>`. For example, `<[1000]>` matches the token with ID 1000. +1. **Token ID**: Use angle brackets with the token ID in square brackets: `<[token-id]>`. For example, `<[1000]>` matches the token with ID 1000. Multiple IDs and inclusive ranges can be combined: `<[1000,1005-1010]>` matches token 1000 or any token from 1005 to 1010. 2. **Token string**: Use angle brackets with the token text directly: ``. For example, `` will match the token whose text is exactly ``. This only works if the string tokenizes to exactly one token in the vocabulary, otherwise the grammar will fail to parse. -You can negate token matches using the `!` prefix: `!<[1000]>` or `!` matches any token *except* the specified one. +You can negate token matches using the `!` prefix: `!<[1000]>` or `!` matches any token *except* the specified one, and `!<[1000,1005-1010]>` matches any token outside the set. + +Tokens are matched whole, so a token rule can only match at the start of a token, never after a character rule has consumed part of its text. Any token named by a token rule is also excluded from character rules: once `` appears as a token in a grammar, `.*` in that grammar will not match the `` token. ``` # Match a thinking block: ... diff --git a/src/llama-grammar.cpp b/src/llama-grammar.cpp index 9a0de14307e5..21a018c8c709 100644 --- a/src/llama-grammar.cpp +++ b/src/llama-grammar.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -33,9 +34,9 @@ static std::pair decode_utf8(const char * src) { return std::make_pair(value, pos); } -static std::pair, llama_partial_utf8> decode_utf8( - const std::string & src, - llama_partial_utf8 partial_start) { +std::pair, llama_partial_utf8> llama_grammar_decode_utf8( + const std::string & src, + llama_partial_utf8 partial_start) { static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 }; const char * pos = src.c_str(); std::vector code_points; @@ -185,23 +186,45 @@ static std::pair parse_char(const char * src) { throw std::runtime_error("unexpected end of input"); } -static std::pair parse_token(const llama_vocab * vocab, const char * src) { +static std::pair parse_token_id(const char * src) { + const char * int_end = parse_int(src); + unsigned long id = std::stoul(std::string(src, int_end - src)); + if (id > std::numeric_limits::max()) { + throw std::runtime_error(std::string("parsed token id is too big at ") + src); + } + return std::make_pair(static_cast(id), int_end); +} + +static const char * parse_token(const llama_vocab * vocab, const char * src, llama_gretype type, llama_grammar_rule & rule) { const char * pos = src; if (*pos != '<') { throw std::runtime_error(std::string("expecting '<' at ") + pos); } pos++; - // Parse <[id]> + // Parse <[id,id-id,...]> if (*pos == '[') { pos++; - const char * int_end = parse_int(pos); - unsigned long id = std::stoul(std::string(pos, int_end - pos)); - if (id > std::numeric_limits::max()) { - throw std::runtime_error(std::string("parsed token id is too big at ") + pos); + const size_t start = rule.size(); + while (true) { + auto id_pair = parse_token_id(pos); + uint32_t token_id = id_pair.first; + pos = id_pair.second; + rule.push_back({rule.size() == start ? type : LLAMA_GRETYPE_TOKEN_ALT, token_id}); + if (*pos == '-') { + pos++; + auto end_pair = parse_token_id(pos); + if (end_pair.first < token_id) { + throw std::runtime_error(std::string("invalid token range at ") + pos); + } + pos = end_pair.second; + rule.push_back({LLAMA_GRETYPE_TOKEN_RNG_UPPER, end_pair.first}); + } + if (*pos != ',') { + break; + } + pos++; } - uint32_t token_id = static_cast(id); - pos = int_end; if (*pos != ']') { throw std::runtime_error(std::string("expecting ']' at ") + pos); } @@ -210,7 +233,7 @@ static std::pair parse_token(const llama_vocab * vocab, throw std::runtime_error(std::string("expecting '>' at ") + pos); } pos++; - return std::make_pair(token_id, pos); + return pos; } if (vocab == nullptr) { @@ -232,7 +255,8 @@ static std::pair parse_token(const llama_vocab * vocab, // must tokenize to exactly 1 token throw std::runtime_error("invalid token '" + std::string(src, pos - src) + "'"); } - return std::make_pair(tokens[0], pos); + rule.push_back({type, static_cast(tokens[0])}); + return pos; } static void print_grammar_char(FILE * file, uint32_t c) { @@ -244,6 +268,16 @@ static void print_grammar_char(FILE * file, uint32_t c) { } } +static bool is_token_element(llama_grammar_element elem) { + switch (elem.type) { + case LLAMA_GRETYPE_TOKEN: return true; + case LLAMA_GRETYPE_TOKEN_NOT: return true; + case LLAMA_GRETYPE_TOKEN_ALT: return true; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: return true; + default: return false; + } +} + static bool is_char_element(llama_grammar_element elem) { switch (elem.type) { case LLAMA_GRETYPE_CHAR: return true; @@ -258,16 +292,18 @@ static bool is_char_element(llama_grammar_element elem) { static void print_rule_binary(FILE * file, const llama_grammar_rule & rule) { for (auto elem : rule) { switch (elem.type) { - case LLAMA_GRETYPE_END: fprintf(file, "END"); break; - case LLAMA_GRETYPE_ALT: fprintf(file, "ALT"); break; - case LLAMA_GRETYPE_RULE_REF: fprintf(file, "RULE_REF"); break; - case LLAMA_GRETYPE_CHAR: fprintf(file, "CHAR"); break; - case LLAMA_GRETYPE_CHAR_NOT: fprintf(file, "CHAR_NOT"); break; - case LLAMA_GRETYPE_CHAR_RNG_UPPER: fprintf(file, "CHAR_RNG_UPPER"); break; - case LLAMA_GRETYPE_CHAR_ALT: fprintf(file, "CHAR_ALT"); break; - case LLAMA_GRETYPE_CHAR_ANY: fprintf(file, "CHAR_ANY"); break; - case LLAMA_GRETYPE_TOKEN: fprintf(file, "TOKEN"); break; - case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "TOKEN_NOT"); break; + case LLAMA_GRETYPE_END: fprintf(file, "END"); break; + case LLAMA_GRETYPE_ALT: fprintf(file, "ALT"); break; + case LLAMA_GRETYPE_RULE_REF: fprintf(file, "RULE_REF"); break; + case LLAMA_GRETYPE_CHAR: fprintf(file, "CHAR"); break; + case LLAMA_GRETYPE_CHAR_NOT: fprintf(file, "CHAR_NOT"); break; + case LLAMA_GRETYPE_CHAR_RNG_UPPER: fprintf(file, "CHAR_RNG_UPPER"); break; + case LLAMA_GRETYPE_CHAR_ALT: fprintf(file, "CHAR_ALT"); break; + case LLAMA_GRETYPE_CHAR_ANY: fprintf(file, "CHAR_ANY"); break; + case LLAMA_GRETYPE_TOKEN: fprintf(file, "TOKEN"); break; + case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "TOKEN_NOT"); break; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: fprintf(file, "TOKEN_RNG_UPPER"); break; + case LLAMA_GRETYPE_TOKEN_ALT: fprintf(file, "TOKEN_ALT"); break; } switch (elem.type) { case LLAMA_GRETYPE_END: @@ -295,6 +331,10 @@ static void print_rule_binary(FILE * file, const llama_grammar_rule & rule) { fprintf(file, "%u", elem.value); fprintf(file, "]> "); break; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: + case LLAMA_GRETYPE_TOKEN_ALT: + fprintf(file, "(%u) ", elem.value); + break; } } fprintf(file, "\n"); @@ -354,14 +394,32 @@ static void print_rule( case LLAMA_GRETYPE_TOKEN: fprintf(file, "<["); fprintf(file, "%u", elem.value); - fprintf(file, "]> "); break; case LLAMA_GRETYPE_TOKEN_NOT: fprintf(file, "!"); fprintf(file, "<["); fprintf(file, "%u", elem.value); - fprintf(file, "]> "); break; + case LLAMA_GRETYPE_TOKEN_RNG_UPPER: + if (i == 0 || !is_token_element(rule[i - 1])) { + throw std::runtime_error( + "LLAMA_GRETYPE_TOKEN_RNG_UPPER without preceding token: " + + std::to_string(rule_id) + "," + std::to_string(i)); + } + fprintf(file, "-%u", elem.value); + break; + case LLAMA_GRETYPE_TOKEN_ALT: + if (i == 0 || !is_token_element(rule[i - 1])) { + throw std::runtime_error( + "LLAMA_GRETYPE_TOKEN_ALT without preceding token: " + + std::to_string(rule_id) + "," + std::to_string(i)); + } + fprintf(file, ",%u", elem.value); + break; + } + if (is_token_element(elem) && + rule[i + 1].type != LLAMA_GRETYPE_TOKEN_ALT && rule[i + 1].type != LLAMA_GRETYPE_TOKEN_RNG_UPPER) { + fprintf(file, "]> "); } if (is_char_element(elem)) { switch (rule[i + 1].type) { @@ -587,11 +645,9 @@ const char * llama_grammar_parser::parse_sequence( type = LLAMA_GRETYPE_TOKEN_NOT; pos++; } - auto token_pair = parse_token(vocab, pos); - const char * token_end = token_pair.second; last_sym_start = rule.size(); n_prev_rules = 1; - rule.push_back({type, token_pair.first}); + const char * token_end = parse_token(vocab, pos, type, rule); pos = parse_space(token_end, is_nested); } else if (is_word_char(*pos)) { // rule reference const char * name_end = parse_name(pos); @@ -854,17 +910,58 @@ static bool llama_grammar_match_partial_char( // returns true iff token matches the rule at pos (regular or inverse) // asserts that pos is pointing to a token element -static bool llama_grammar_match_token( +static std::pair llama_grammar_match_token( const llama_grammar_element * pos, const llama_token token) { - GGML_ASSERT(pos->type == LLAMA_GRETYPE_TOKEN || pos->type == LLAMA_GRETYPE_TOKEN_NOT); - if (pos->type == LLAMA_GRETYPE_TOKEN) { - return pos->value == static_cast(token); + bool is_positive_token = pos->type == LLAMA_GRETYPE_TOKEN; + + GGML_ASSERT(is_positive_token || pos->type == LLAMA_GRETYPE_TOKEN_NOT); + + const uint32_t id = static_cast(token); + + bool found = false; + do { + if (pos[1].type == LLAMA_GRETYPE_TOKEN_RNG_UPPER) { + // inclusive range, e.g. <[1-5]> + found = found || (pos->value <= id && id <= pos[1].value); + pos += 2; + } else { + found = found || pos->value == id; + pos += 1; + } + } while (pos->type == LLAMA_GRETYPE_TOKEN_ALT); + + return std::make_pair(found == is_positive_token, pos); +} + +// every token id a token rule names, merged into sorted inclusive ranges +static std::vector> llama_grammar_opaque_tokens(const llama_grammar_rules & rules) { + std::vector> ranges; + for (const auto & rule : rules) { + for (size_t i = 0; i < rule.size(); i++) { + const auto type = rule[i].type; + if (type == LLAMA_GRETYPE_TOKEN || type == LLAMA_GRETYPE_TOKEN_NOT || type == LLAMA_GRETYPE_TOKEN_ALT) { + const bool is_range = i + 1 < rule.size() && rule[i + 1].type == LLAMA_GRETYPE_TOKEN_RNG_UPPER; + ranges.emplace_back(rule[i].value, is_range ? rule[i + 1].value : rule[i].value); + } + } } - if (pos->type == LLAMA_GRETYPE_TOKEN_NOT) { - return pos->value != static_cast(token); + std::sort(ranges.begin(), ranges.end()); + std::vector> merged; + for (const auto & r : ranges) { + if (!merged.empty() && r.first <= (uint64_t) merged.back().second + 1) { + merged.back().second = std::max(merged.back().second, r.second); + } else { + merged.push_back(r); + } } - return false; + return merged; +} + +bool llama_grammar_is_opaque(const llama_grammar & grammar, llama_token token) { + const auto id = static_cast(token); + auto it = std::upper_bound(grammar.opaque_tokens.begin(), grammar.opaque_tokens.end(), std::make_pair(id, UINT32_MAX)); + return it != grammar.opaque_tokens.begin() && std::prev(it)->second >= id; } // transforms a grammar pushdown stack into N possible stacks, all ending @@ -946,8 +1043,7 @@ static void llama_grammar_advance_stack( break; default: // end of alternate (LLAMA_GRETYPE_END, LLAMA_GRETYPE_ALT) or middle of char range - // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER); stack should never be left on - // those + // (LLAMA_GRETYPE_CHAR_ALT, LLAMA_GRETYPE_CHAR_RNG_UPPER) or token set (LLAMA_GRETYPE_TOKEN_ALT, LLAMA_GRETYPE_TOKEN_RNG_UPPER); stack should never be left on those GGML_ABORT("fatal error"); } } @@ -1238,13 +1334,13 @@ static bool llama_grammar_reject_step( if (stack_pos->type == LLAMA_GRETYPE_TOKEN || stack_pos->type == LLAMA_GRETYPE_TOKEN_NOT) { for (const uint32_t i : cur) { const auto & tok = candidates[i]; - if (tok.code_points[depth] == 0) { - // reached the end of a token consumed by char rules, reject iff it ended - // in a partial response - if (tok.partial_utf8.n_remain != 0) { + if (depth > 0) { + // char rules already consumed part of this token, so it cannot match by id. + // accept it only if they consumed all of it and did not end in a partial sequence. + if (tok.code_points[depth] != 0 || tok.partial_utf8.n_remain != 0) { rejects.push_back(i); } - } else if (!llama_grammar_match_token(stack_pos, tok.id)) { + } else if (tok.partial_utf8.n_remain < 0 || !llama_grammar_match_token(stack_pos, tok.id).first) { rejects.push_back(i); } } @@ -1255,7 +1351,10 @@ static bool llama_grammar_reject_step( for (const uint32_t i : cur) { const auto & tok = candidates[i]; - if (tok.code_points[depth] == 0) { + if (tok.opaque) { + // a token named by a token rule only matches token rules + rejects.push_back(i); + } else if (tok.code_points[depth] == 0) { // reached end of full codepoints in token, reject iff it ended in a partial sequence // that cannot satisfy this position in grammar if (tok.partial_utf8.n_remain != 0 && @@ -1425,6 +1524,8 @@ struct llama_grammar * llama_grammar_init_impl( } } while (true); + auto opaque_tokens = llama_grammar_opaque_tokens(vec_rules); + // Important: vec_rules has to be moved here, not copied, because stacks contains // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar // then the pointers would be invalidated when the local vec_rules goes out of scope. @@ -1439,6 +1540,7 @@ struct llama_grammar * llama_grammar_init_impl( /* .trigger_buffer_positions = */ {}, /* .trigger_tokens = */ {}, /* .trigger_patterns = */ {}, + /* .opaque_tokens = */ std::move(opaque_tokens), }; } @@ -1540,6 +1642,8 @@ struct llama_grammar * llama_grammar_init_impl( trigger.regex = std::regex(trigger.pattern); } + auto opaque_tokens = llama_grammar_opaque_tokens(vec_rules); + // Important: vec_rules has to be moved here, not copied, because stacks contains // pointers to elements of vec_rules. If vec_rules were copied into llama_grammar // then the pointers would be invalidated when the local vec_rules goes out of scope. @@ -1554,6 +1658,7 @@ struct llama_grammar * llama_grammar_init_impl( /* .trigger_buffer_positions = */ {}, std::move(vec_trigger_tokens), std::move(vec_trigger_patterns), + std::move(opaque_tokens), }; } @@ -1601,8 +1706,9 @@ void llama_grammar_apply_impl(const struct llama_grammar & grammar, llama_token_ } else if (piece.empty() || piece[0] == 0) { cur_p->data[i].logit = -INFINITY; } else { - candidates_decoded.push_back(decode_utf8(piece, grammar.partial_utf8)); - candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second, id }); + candidates_decoded.push_back(llama_grammar_decode_utf8(piece, grammar.partial_utf8)); + candidates_grammar.push_back({ i, candidates_decoded.back().first.data(), candidates_decoded.back().second, id, + llama_grammar_is_opaque(grammar, id) }); } } @@ -1673,7 +1779,7 @@ void llama_grammar_accept_impl(struct llama_grammar & grammar, llama_token token void llama_grammar_accept_str(struct llama_grammar & grammar, const std::string & piece) { // Note terminating 0 in decoded string - const auto decoded = decode_utf8(piece, grammar.partial_utf8); + const auto decoded = llama_grammar_decode_utf8(piece, grammar.partial_utf8); const auto & code_points = decoded.first; for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) { @@ -1688,9 +1794,16 @@ void llama_grammar_accept_str(struct llama_grammar & grammar, const std::string void llama_grammar_accept_token(struct llama_grammar & grammar, llama_token token, const std::string & piece) { // Note terminating 0 in decoded string - const auto decoded = decode_utf8(piece, grammar.partial_utf8); + const auto decoded = llama_grammar_decode_utf8(piece, grammar.partial_utf8); const auto & code_points = decoded.first; + // the mask rejects a piece that does not continue a partial character, so accepting one has to fail too + if (decoded.second.n_remain < 0) { + throw std::runtime_error("Invalid UTF-8 continuation in piece: " + piece + " (" + std::to_string(token) + ")"); + } + + const bool opaque = llama_grammar_is_opaque(grammar, token); + llama_grammar_stacks stacks_new; stacks_new.reserve(grammar.stacks.size()); @@ -1702,14 +1815,15 @@ void llama_grammar_accept_token(struct llama_grammar & grammar, llama_token toke const llama_grammar_element * pos = stack.back(); if (pos->type == LLAMA_GRETYPE_TOKEN || pos->type == LLAMA_GRETYPE_TOKEN_NOT) { - if (llama_grammar_match_token(pos, token)) { + auto match = llama_grammar_match_token(pos, token); + if (match.first) { llama_grammar_stack new_stack(stack.begin(), stack.end() - 1); - if (!llama_grammar_is_end_of_sequence(pos + 1)) { - new_stack.push_back(pos + 1); + if (!llama_grammar_is_end_of_sequence(match.second)) { + new_stack.push_back(match.second); } llama_grammar_advance_stack(*grammar.rules, new_stack, stacks_new); } - } else { + } else if (!opaque) { llama_grammar_stacks current_stacks = {stack}; for (auto it = code_points.begin(), end = code_points.end() - 1; it != end; ++it) { diff --git a/src/llama-grammar.h b/src/llama-grammar.h index 5829d8edc467..fedc709697e0 100644 --- a/src/llama-grammar.h +++ b/src/llama-grammar.h @@ -38,11 +38,17 @@ enum llama_gretype { // any character (.) LLAMA_GRETYPE_CHAR_ANY = 7, - // terminal element: token (<[token-id]>) + // terminal element: token (<[token-id]>, <[token-id,token-id-token-id]>) LLAMA_GRETYPE_TOKEN = 8, - // inverse token (!<[token-id]>) + // inverse token (!<[token-id]>, !<[token-id,token-id-token-id]>) LLAMA_GRETYPE_TOKEN_NOT = 9, + + // modifies a preceding LLAMA_GRETYPE_TOKEN, LLAMA_GRETYPE_TOKEN_NOT, or LLAMA_GRETYPE_TOKEN_ALT to be an inclusive range (<[1-5]>) + LLAMA_GRETYPE_TOKEN_RNG_UPPER = 10, + + // modifies a preceding LLAMA_GRETYPE_TOKEN, LLAMA_GRETYPE_TOKEN_NOT, or LLAMA_GRETYPE_TOKEN_RNG_UPPER to add an alternate token to match (<[1,5]>, <[1-5,9]>) + LLAMA_GRETYPE_TOKEN_ALT = 11, }; typedef struct llama_grammar_element { @@ -60,6 +66,7 @@ struct llama_grammar_candidate { const uint32_t * code_points; llama_partial_utf8 partial_utf8; llama_token id; + bool opaque; }; using llama_grammar_rule = std::vector< llama_grammar_element>; @@ -84,6 +91,10 @@ std::vector llama_grammar_reject_candidates_for_stack( const llama_grammar_stack & stack, const llama_grammar_candidates & candidates); +std::pair, llama_partial_utf8> llama_grammar_decode_utf8( + const std::string & src, + llama_partial_utf8 partial_start); + struct llama_grammar_parser { const llama_vocab * vocab; std::map symbol_ids; @@ -151,6 +162,8 @@ struct llama_grammar { trigger_patterns; // Regular expressions that trigger a lazy grammar. Must be a full match of the entire generated // string, and the grammar will be given the string from the first match group onwards. + // token ids named by token rules, as sorted inclusive ranges. char rules never match these tokens. + std::vector> opaque_tokens; }; // @@ -195,3 +208,6 @@ void llama_grammar_accept_token( struct llama_grammar & grammar, llama_token token, const std::string & piece); + +// true if a token rule names the token, char rules do not match it +bool llama_grammar_is_opaque(const llama_grammar & grammar, llama_token token); diff --git a/tests/peg-parser/test-basic.cpp b/tests/peg-parser/test-basic.cpp index b6af61491d76..df124c759c68 100644 --- a/tests/peg-parser/test-basic.cpp +++ b/tests/peg-parser/test-basic.cpp @@ -367,6 +367,49 @@ void test_basic(testing & t) { }); + t.test("through", [](testing & t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.tag("body", p.until_one_of({ "", "" })), { { p.literal(""), p.literal("x") }, { p.literal("") } }, true); + }); + + t.test("consumes the delimiter and its rest", [&](testing & t) { + auto ctx = common_peg_parse_context("hellox"); + auto result = parser.parse(ctx); + t.assert_equal("success", true, result.success()); + t.assert_equal("end", (size_t) 10, result.end); + t.assert_equal("body", std::string("hello"), std::string(ctx.ast.get(result.nodes[0]).text)); + }); + + t.test("picks the branch of the delimiter found", [&](testing & t) { + auto ctx = common_peg_parse_context("hellox"); + auto result = parser.parse(ctx); + t.assert_equal("success", true, result.success()); + t.assert_equal("end", (size_t) 9, result.end); + }); + + t.test("waits for the rest of a partial delimiter", [&](testing & t) { + auto ctx = common_peg_parse_context("hello"); + }); + auto ctx = common_peg_parse_context("hello"); + auto result = parser.parse(ctx); + t.assert_equal("fail", true, result.fail()); + }); + }); + t.test("recursive rules", [](testing &t) { // Test simple number t.test("simple_number", [](testing &t) { diff --git a/tests/peg-parser/test-gbnf-generation.cpp b/tests/peg-parser/test-gbnf-generation.cpp index 60066a817b50..38f3ec9abe23 100644 --- a/tests/peg-parser/test-gbnf-generation.cpp +++ b/tests/peg-parser/test-gbnf-generation.cpp @@ -129,14 +129,14 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - root ::= until-0 + root ::= until-1 space ::= | " " | "\n"{1,2} [ \t]{0,20} - until-0 ::= | [<] until-0-01 | [^<] until-0 - until-0-01 ::= | [<] until-0-01 | [/] until-0-02 | [^/<] until-0 - until-0-02 ::= | [<] until-0-01 | [t] until-0-03 | [^] until-0 + until-1 ::= | [<] until-1-01 | [^<] until-1 + until-1-01 ::= | [<] until-1-01 | [/] until-1-02 | [^/<] until-1 + until-1-02 ::= | [<] until-1-01 | [t] until-1-03 | [^] until-1 )""", gbnf); }); @@ -150,22 +150,22 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - root ::= until-0 + root ::= until-1 space ::= | " " | "\n"{1,2} [ \t]{0,20} - until-0 ::= | [\n] until-0-01 | [^\n] until-0 - until-0-01 ::= | [\n] until-0-01 | [<] until-0-02 | [^\n<] until-0 - until-0-02 ::= | [\n] until-0-01 | [/] until-0-03 | [^\n/] until-0 - until-0-03 ::= | [\n] until-0-01 | [p] until-0-04 | [^\np] until-0 - until-0-04 ::= | [\n] until-0-01 | [a] until-0-05 | [^\na] until-0 - until-0-05 ::= | [\n] until-0-01 | [r] until-0-06 | [^\nr] until-0 - until-0-06 ::= | [\n] until-0-01 | [a] until-0-07 | [^\na] until-0 - until-0-07 ::= | [\n] until-0-01 | [m] until-0-08 | [^\nm] until-0 - until-0-08 ::= | [\n] until-0-01 | [e] until-0-09 | [^\ne] until-0 - until-0-09 ::= | [\n] until-0-01 | [t] until-0-10 | [^\nt] until-0 - until-0-10 ::= | [\n] until-0-01 | [e] until-0-11 | [^\ne] until-0 - until-0-11 ::= | [\n] until-0-01 | [r] until-0-12 | [^\nr] until-0 - until-0-12 ::= | [\n] until-0-01 | [>] until-0-13 | [^\n>] until-0 - until-0-13 ::= | [^\n] until-0 + until-1 ::= | [\n] until-1-01 | [^\n] until-1 + until-1-01 ::= | [\n] until-1-01 | [<] until-1-02 | [^\n<] until-1 + until-1-02 ::= | [\n] until-1-01 | [/] until-1-03 | [^\n/] until-1 + until-1-03 ::= | [\n] until-1-01 | [p] until-1-04 | [^\np] until-1 + until-1-04 ::= | [\n] until-1-01 | [a] until-1-05 | [^\na] until-1 + until-1-05 ::= | [\n] until-1-01 | [r] until-1-06 | [^\nr] until-1 + until-1-06 ::= | [\n] until-1-01 | [a] until-1-07 | [^\na] until-1 + until-1-07 ::= | [\n] until-1-01 | [m] until-1-08 | [^\nm] until-1 + until-1-08 ::= | [\n] until-1-01 | [e] until-1-09 | [^\ne] until-1 + until-1-09 ::= | [\n] until-1-01 | [t] until-1-10 | [^\nt] until-1 + until-1-10 ::= | [\n] until-1-01 | [e] until-1-11 | [^\ne] until-1 + until-1-11 ::= | [\n] until-1-01 | [r] until-1-12 | [^\nr] until-1 + until-1-12 ::= | [\n] until-1-01 | [>] until-1-13 | [^\n>] until-1 + until-1-13 ::= | [^\n] until-1 )""", gbnf); }); @@ -181,15 +181,15 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - root ::= until-0 + root ::= until-1 space ::= | " " | "\n"{1,2} [ \t]{0,20} - until-0 ::= | [<] until-0-01 | [^<] until-0 - until-0-01 ::= | [<] until-0-01 | [\uFF5C] until-0-02 | [^<\uFF5C] until-0 - until-0-02 ::= | [<] until-0-01 | [D] until-0-03 | [^") + p.literal(""), ""); + return p.through(p.until(""), ""); }); auto gbnf = build_grammar([&](const common_grammar_builder & builder) { @@ -222,20 +222,20 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - ac-3 ::= [<] ac-3-01 | [^<] ac-3 - ac-3-01 ::= [<] ac-3-01 | [/] ac-3-02 | [^/<] ac-3 - ac-3-02 ::= [<] ac-3-01 | [t] ac-3-03 | [^] | [<] ac-3-01 | [^<>] ac-3 - root ::= ac-3 + root ::= until-3 space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-3 ::= [<] until-3-01 | [^<] until-3 + until-3-01 ::= [<] until-3-01 | [/] until-3-02 | [^/<] until-3 + until-3-02 ::= [<] until-3-01 | [t] until-3-03 | [^] | [<] until-3-01 | [^<>] until-3 )""", gbnf); }); - t.test("ac grammar terminates at first delimiter", [](testing &t) { + t.test("through grammar terminates at first delimiter", [](testing &t) { auto parser = build_peg_parser([](common_peg_parser_builder & p) { - return p.ac(p.until("\n\n") + p.literal("\n\n"), "\n\n"); + return p.through(p.until("\n\n"), "\n\n"); }); auto gbnf = build_grammar([&](const common_grammar_builder & builder) { @@ -243,28 +243,28 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - ac-3 ::= [\n] ac-3-01 | [^\n] ac-3 - ac-3-01 ::= [\n] ac-3-01 | [<] ac-3-02 | [^\n<] ac-3 - ac-3-02 ::= [\n] ac-3-01 | [/] ac-3-03 | [^\n/] ac-3 - ac-3-03 ::= [\n] ac-3-01 | [p] ac-3-04 | [^\np] ac-3 - ac-3-04 ::= [\n] ac-3-01 | [a] ac-3-05 | [^\na] ac-3 - ac-3-05 ::= [\n] ac-3-01 | [r] ac-3-06 | [^\nr] ac-3 - ac-3-06 ::= [\n] ac-3-01 | [a] ac-3-07 | [^\na] ac-3 - ac-3-07 ::= [\n] ac-3-01 | [m] ac-3-08 | [^\nm] ac-3 - ac-3-08 ::= [\n] ac-3-01 | [e] ac-3-09 | [^\ne] ac-3 - ac-3-09 ::= [\n] ac-3-01 | [t] ac-3-10 | [^\nt] ac-3 - ac-3-10 ::= [\n] ac-3-01 | [e] ac-3-11 | [^\ne] ac-3 - ac-3-11 ::= [\n] ac-3-01 | [r] ac-3-12 | [^\nr] ac-3 - ac-3-12 ::= [\n] ac-3-01 | [>] ac-3-13 | [^\n>] ac-3 - ac-3-13 ::= [\n] | [^\n] ac-3 - root ::= ac-3 + root ::= until-3 space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-3 ::= [\n] until-3-01 | [^\n] until-3 + until-3-01 ::= [\n] until-3-01 | [<] until-3-02 | [^\n<] until-3 + until-3-02 ::= [\n] until-3-01 | [/] until-3-03 | [^\n/] until-3 + until-3-03 ::= [\n] until-3-01 | [p] until-3-04 | [^\np] until-3 + until-3-04 ::= [\n] until-3-01 | [a] until-3-05 | [^\na] until-3 + until-3-05 ::= [\n] until-3-01 | [r] until-3-06 | [^\nr] until-3 + until-3-06 ::= [\n] until-3-01 | [a] until-3-07 | [^\na] until-3 + until-3-07 ::= [\n] until-3-01 | [m] until-3-08 | [^\nm] until-3 + until-3-08 ::= [\n] until-3-01 | [e] until-3-09 | [^\ne] until-3 + until-3-09 ::= [\n] until-3-01 | [t] until-3-10 | [^\nt] until-3 + until-3-10 ::= [\n] until-3-01 | [e] until-3-11 | [^\ne] until-3 + until-3-11 ::= [\n] until-3-01 | [r] until-3-12 | [^\nr] until-3 + until-3-12 ::= [\n] until-3-01 | [>] until-3-13 | [^\n>] until-3 + until-3-13 ::= [\n] | [^\n] until-3 )""", gbnf); }); - t.test("ac grammar multiple delimiters", [](testing &t) { + t.test("through grammar multiple delimiters", [](testing &t) { auto parser = build_peg_parser([](common_peg_parser_builder & p) { - return p.ac(p.eps(), std::vector{"ab", "cd", "ef"}); + return p.through(p.eps(), { { p.literal("ab") }, { p.literal("cd") }, { p.literal("ef") } }); }); auto gbnf = build_grammar([&](const common_grammar_builder & builder) { @@ -272,12 +272,238 @@ void test_gbnf_generation(testing &t) { }); assert_gbnf_equal(t, R"""( - ac-1 ::= [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^ace] ac-1 - ac-1-01 ::= [b] | [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^abce] ac-1 - ac-1-03 ::= [d] | [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^acde] ac-1 - ac-1-05 ::= [f] | [a] ac-1-01 | [c] ac-1-03 | [e] ac-1-05 | [^acef] ac-1 - root ::= ac-1 + root ::= until-4 space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-4 ::= [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^ace] until-4 + until-4-01 ::= [b] | [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^abce] until-4 + until-4-03 ::= [d] | [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^acde] until-4 + until-4-05 ::= [f] | [a] until-4-01 | [c] until-4-03 | [e] until-4-05 | [^acef] until-4 + )""", gbnf); + }); + + t.test("until grammar with parser delimiters", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.until((p.literal("a") + p.literal("b")) | p.literal("cd")); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= | [a] until-5-01 | [c] until-5-03 | [^ac] until-5 + until-5-01 ::= | [a] until-5-01 | [c] until-5-03 | [^abc] until-5 + until-5-03 ::= | [a] until-5-01 | [c] until-5-03 | [^acd] until-5 + )""", gbnf); + }); + + t.test("delimiters see through tags and atomics", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.until(p.tag("open", p.literal("a") + p.atomic(p.literal("b")))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= | [a] until-5-01 | [^a] until-5 + until-5-01 ::= | [a] until-5-01 | [^ab] until-5 + )""", gbnf); + }); + + t.test("delimiters expand a choice in a sequence", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.until(p.literal("a") + (p.literal("b") | p.literal("d"))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= | [a] until-5-01 | [^a] until-5 + until-5-01 ::= | [a] until-5-01 | [^abd] until-5 + )""", gbnf); + }); + + t.test("delimiters reject anything but sequences, choices, literals, and tokens", [](testing &t) { + bool threw = false; + try { + build_peg_parser([](common_peg_parser_builder & p) { + return p.until(p.literal("a") + p.space()); + }); + } catch (const std::invalid_argument &) { + threw = true; + } + t.assert_equal("space_rejected", true, threw); + }); + + t.test("through branches reject a shared delimiter", [](testing &t) { + bool threw = false; + try { + build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("ab"), p.literal("x") }, { p.literal("ab"), p.literal("y") } }); + }); + } catch (const std::invalid_argument &) { + threw = true; + } + t.assert_equal("duplicate_rejected", true, threw); + }); + + t.test("through grammar branches continue with their rest", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("ab"), p.literal("x") }, { p.literal("cd") } }); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-4 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-4 ::= [a] until-4-01 | [c] until-4-03 | [^ac] until-4 + until-4-01 ::= [b] until-4-rest-0 | [a] until-4-01 | [c] until-4-03 | [^abc] until-4 + until-4-03 ::= [d] | [a] until-4-01 | [c] until-4-03 | [^acd] until-4 + until-4-rest-0 ::= "x" + )""", gbnf); + }); + + t.test("through grammar optional may end before a delimiter", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("ab"), p.literal("x") } }, true); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-3 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-3 ::= | [a] until-3-01 | [^a] until-3 + until-3-01 ::= | [b] until-3-rest-0 | [a] until-3-01 | [^ab] until-3 + until-3-rest-0 ::= "x" + )""", gbnf); + }); + + t.test("trigger rules emit their start and rest when not lazy", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + auto ab = p.literal("ab"); + auto cd = p.literal("cd"); + auto scan = p.until(ab | cd); + return scan + (p.trigger_rule("one", ab, p.literal("x")) | p.trigger_rule("two", cd, p.literal("y"))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder, false); + }); + + assert_gbnf_equal(t, R"""( + one ::= "ab" "x" + root ::= until-3 (one | two) + space ::= | " " | "\n"{1,2} [ \t]{0,20} + two ::= "cd" "y" + until-3 ::= | [a] until-3-01 | [c] until-3-03 | [^ac] until-3 + until-3-01 ::= | [a] until-3-01 | [c] until-3-03 | [^abc] until-3 + until-3-03 ::= | [a] until-3-01 | [c] until-3-03 | [^acd] until-3 + )""", gbnf); + }); + + t.test("trigger rules make the lazy grammar scan for their starts", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + auto ab = p.literal("ab"); + auto cd = p.literal("cd"); + auto scan = p.until(ab | cd); + return scan + (p.trigger_rule("one", ab, p.literal("x")) | p.trigger_rule("two", cd, p.literal("y"))); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder, true); + }); + + assert_gbnf_equal(t, R"""( + one-rest ::= "x" + root ::= trigger + space ::= | " " | "\n"{1,2} [ \t]{0,20} + trigger ::= | [a] trigger-01 | [c] trigger-03 | [^ac] trigger + trigger-01 ::= | [b] one-rest | [a] trigger-01 | [c] trigger-03 | [^abc] trigger + trigger-03 ::= | [d] two-rest | [a] trigger-01 | [c] trigger-03 | [^acd] trigger + two-rest ::= "y" + )""", gbnf); + }); + + t.test("scanning grammar lets other named tokens through", [](testing &t) { + common_peg_tokens tokens; + tokens.ids.emplace("", 1); + tokens.ids.emplace("", 2); + tokens.tokens.emplace(1, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + tokens.tokens.emplace(2, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + + common_peg_parser_builder p(tokens); + auto start = p.token("") + p.literal("x"); + p.set_root(p.until(start) + p.trigger_rule("tool", start, p.token(""))); + auto parser = p.build(); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder, true); + }); + + assert_gbnf_equal(t, R"""( + root ::= trigger + space ::= | " " | "\n"{1,2} [ \t]{0,20} + tool-rest ::= <[2]> + trigger ::= | <[1]> trigger-01 | (. | <[2]>) trigger + trigger-01 ::= | [x] tool-rest | <[1]> trigger-01 | ([^x] | <[2]>) trigger + )""", gbnf); + }); + + t.test("token sets", [](testing &t) { + common_peg_tokens tokens; + tokens.ids.emplace("", 1); + tokens.ids.emplace("", 2); + tokens.tokens.emplace(1, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + tokens.tokens.emplace(2, common_peg_token{ "", LLAMA_TOKEN_ATTR_CONTROL }); + + common_peg_parser_builder p(tokens); + p.set_root(p.token({ "", "" }) + p.token({ "", "" }, true)); + auto parser = p.build(); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= (<[1]> | <[2]>) !<[1-2]> + space ::= | " " | "\n"{1,2} [ \t]{0,20} + )""", gbnf); + }); + + t.test("through grammar suffix delimiter offers both rests", [](testing &t) { + auto parser = build_peg_parser([](common_peg_parser_builder & p) { + return p.through(p.eps(), { { p.literal("xab"), p.literal("1") }, { p.literal("ab"), p.literal("2") } }); + }); + + auto gbnf = build_grammar([&](const common_grammar_builder & builder) { + parser.build_grammar(builder); + }); + + assert_gbnf_equal(t, R"""( + root ::= until-5 + space ::= | " " | "\n"{1,2} [ \t]{0,20} + until-5 ::= [x] until-5-01 | [a] until-5-04 | [^ax] until-5 + until-5-01 ::= [x] until-5-01 | [a] until-5-02 | [^ax] until-5 + until-5-02 ::= [b] (until-5-rest-0 | until-5-rest-1) | [x] until-5-01 | [a] until-5-04 | [^abx] until-5 + until-5-04 ::= [b] until-5-rest-1 | [x] until-5-01 | [a] until-5-04 | [^abx] until-5 + until-5-rest-0 ::= "1" + until-5-rest-1 ::= "2" )""", gbnf); }); diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 7b70e7bcc853..11fa68f6a736 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -305,6 +305,66 @@ static std::string get_expected_description(const llama_grammar_rules & rules, c return result; } +// Every text token shares one ID, the parsers and grammars only tell special tokens apart +static constexpr llama_token FAKE_TEXT_TOKEN = 0; + +struct fake_token { + llama_token id; + std::string piece; +}; + +// Splits text into the special tokens it spells, longest first, and one text token per UTF-8 character. +static std::vector fake_tokenize(const common_peg_tokens & specials, const std::string & text) { + std::vector result; + size_t pos = 0; + while (pos < text.size()) { + llama_token best = LLAMA_TOKEN_NULL; + size_t best_len = 0; + for (const auto & [piece, id] : specials.ids) { + if (piece.size() > best_len && text.compare(pos, piece.size(), piece) == 0) { + best = id; + best_len = piece.size(); + } + } + if (best != LLAMA_TOKEN_NULL) { + result.push_back({ best, text.substr(pos, best_len) }); + pos += best_len; + continue; + } + size_t len = 1; + while (pos + len < text.size() && (static_cast(text[pos + len]) & 0xC0) == 0x80) { + len++; + } + result.push_back({ FAKE_TEXT_TOKEN, text.substr(pos, len) }); + pos += len; + } + return result; +} + +// Returns the tokens from byte offset pos. A token split by pos keeps the rest of its piece as text. +static std::vector fake_tokens_from(const std::vector & tokens, size_t pos) { + std::vector result; + size_t start = 0; + for (const auto & token : tokens) { + const size_t end = start + token.piece.size(); + if (start >= pos) { + result.push_back(token); + } else if (end > pos) { + result.push_back({ FAKE_TEXT_TOKEN, token.piece.substr(pos - start) }); + } + start = end; + } + return result; +} + +static common_chat_input fake_input(const std::vector & tokens) { + common_chat_input input; + for (const auto & token : tokens) { + input.append(token.piece, token.id); + } + return input; +} + // Result of a detailed grammar match attempt struct grammar_match_result { bool success = false; // Did the string fully match the grammar? @@ -318,56 +378,49 @@ struct grammar_match_result { bool incomplete = false; // True if matched all input but grammar expects more }; -// Detailed version of match_string that returns failure information -static grammar_match_result match_string_detailed(const std::string & input, llama_grammar * grammar) { - grammar_match_result result; - result.total_bytes = input.size(); +// Detailed version of match_string that returns failure information, accepting the input token by token +static grammar_match_result match_string_detailed(const std::vector & tokens, llama_grammar * grammar) { + std::string input; + for (const auto & token : tokens) { + input += token.piece; + } - const auto cpts = unicode_cpts_from_utf8(input); - result.total_codepoints = cpts.size(); + grammar_match_result result; + result.total_bytes = input.size(); + result.total_codepoints = unicode_cpts_from_utf8(input).size(); auto & stacks_cur = llama_grammar_get_stacks(grammar); const auto & rules = llama_grammar_get_rules(grammar); size_t byte_pos = 0; + size_t cpt_pos = 0; - for (size_t i = 0; i < cpts.size(); i++) { - const auto & cpt = cpts[i]; - + for (const auto & token : tokens) { // Get expected before accepting (for error reporting) std::string expected_before = get_expected_description(rules, stacks_cur); - llama_grammar_accept(grammar, cpt); - - // Calculate byte position for this codepoint - size_t cpt_bytes = 0; - if (cpt < 0x80) { - cpt_bytes = 1; - } else if (cpt < 0x800) { - cpt_bytes = 2; - } else if (cpt < 0x10000) { - cpt_bytes = 3; - } else { - cpt_bytes = 4; - } - - if (stacks_cur.empty()) { + try { + llama_grammar_accept_token(*grammar, token.id, token.piece); + } catch (const std::runtime_error & /*e*/) { // Grammar failed to match at this point result.matched_bytes = byte_pos; - result.matched_codepoints = i; + result.matched_codepoints = cpt_pos; result.matched_prefix = input.substr(0, byte_pos); - result.failing_char = format_codepoint(cpt); + result.failing_char = token.id == FAKE_TEXT_TOKEN + ? format_codepoint(unicode_cpts_from_utf8(token.piece).at(0)) + : token.piece + " (token " + std::to_string(token.id) + ")"; result.expected_description = expected_before; result.incomplete = false; return result; } - byte_pos += cpt_bytes; + byte_pos += token.piece.size(); + cpt_pos += unicode_cpts_from_utf8(token.piece).size(); } // All input matched - check if grammar is complete result.matched_bytes = input.size(); - result.matched_codepoints = cpts.size(); + result.matched_codepoints = result.total_codepoints; result.matched_prefix = input; if (std::any_of(stacks_cur.begin(), stacks_cur.end(), [](const auto & stack) { return stack.empty(); })) { @@ -1129,6 +1182,7 @@ static std::string g_template_filter; static bool g_force_reconstruction_test = false; static void test_peg_parser(common_chat_templates * tmpls, + const common_peg_tokens & specials, const std::function & init, bool detailed_debug) { // UTF-8-safe truncation helper (same as in test_parser_with_streaming) @@ -1173,8 +1227,15 @@ static void test_peg_parser(common_chat_templates * tmpls, tc.expect.role = "assistant"; } + const bool tokenized = !specials.ids.empty(); + common_chat_session_params session_params; session_params.debug = detailed_debug; + if (tokenized) { + session_params.tokenize = [&](const std::string & text) { + return fake_input(fake_tokenize(specials, text)); + }; + } common_chat_session session(tmpls, nullptr, tc.params, session_params); const auto & parser = session.parser(); common_params_sampling sampling; @@ -1200,14 +1261,27 @@ static void test_peg_parser(common_chat_templates * tmpls, common_chat_msg msg_prev; msg_accum.role = msg_prev.role = "assistant"; - size_t fed = 0; - for (size_t i = 1; i <= tc.input.size(); ++i) { - auto is_partial = i < tc.input.size() || tc.is_partial; - // Use UTF-8 safe truncation to avoid corrupting multi-byte characters - size_t safe_len = utf8_truncate_safe_len(std::string_view(tc.input).substr(0, i)); - common_chat_input chunk(tc.input.substr(fed, safe_len - fed)); - fed = safe_len; - const common_chat_msg & msg_current = is_partial ? session.feed(chunk) : session.finish(chunk); + const auto input_tokens = fake_tokenize(specials, tc.input); + + // A token arrives whole, so a special token is never split across chunks + std::vector chunks; + if (tokenized) { + for (const auto & token : input_tokens) { + chunks.push_back(fake_input({ token })); + } + } else { + size_t fed = 0; + for (size_t i = 1; i <= tc.input.size(); ++i) { + // Use UTF-8 safe truncation to avoid corrupting multi-byte characters + size_t safe_len = utf8_truncate_safe_len(std::string_view(tc.input).substr(0, i)); + chunks.emplace_back(tc.input.substr(fed, safe_len - fed)); + fed = safe_len; + } + } + + for (size_t i = 0; i < chunks.size(); ++i) { + auto is_partial = i + 1 < chunks.size() || tc.is_partial; + const common_chat_msg & msg_current = is_partial ? session.feed(chunks[i]) : session.finish(chunks[i]); for (const auto & diff : common_chat_msg_diff::compute_diffs(msg_prev, msg_current)) { if (!diff.reasoning_content_delta.empty()) { @@ -1222,10 +1296,15 @@ static void test_peg_parser(common_chat_templates * tmpls, while (msg_accum.tool_calls.size() <= diff.tool_call_index) { msg_accum.tool_calls.push_back({ "", "", "" }); } - // Always update name and id from diff (may change during incremental parsing), but only if the delta - // actually contains them + // The name and id are set once the delta carries them. + // A name that is already set must not change, clients concatenate name deltas. if (!diff.tool_call_delta.name.empty()) { - msg_accum.tool_calls[diff.tool_call_index].name = diff.tool_call_delta.name; + auto & name = msg_accum.tool_calls[diff.tool_call_index].name; + if (!name.empty() && name != diff.tool_call_delta.name) { + throw std::runtime_error("Tool call " + std::to_string(diff.tool_call_index) + " name changed from " + + name + " to " + diff.tool_call_delta.name + " during incremental parsing"); + } + name = diff.tool_call_delta.name; } if (!diff.tool_call_delta.id.empty()) { msg_accum.tool_calls[diff.tool_call_index].id = diff.tool_call_delta.id; @@ -1413,9 +1492,10 @@ static void test_peg_parser(common_chat_templates * tmpls, // sampler was already active before model output began — constrain from the // start of the model output (i.e. tc.input). std::string constrained = full_input; + size_t constrain_from = 0; bool grammar_triggered = false; if (earliest_trigger_pos != std::string::npos) { - auto constrain_from = std::max(earliest_trigger_pos, gen_prompt.size()); + constrain_from = std::max(earliest_trigger_pos, gen_prompt.size()); constrained = full_input.substr(constrain_from); grammar_triggered = true; } else if (!sampling.grammar_lazy) { @@ -1425,7 +1505,9 @@ static void test_peg_parser(common_chat_templates * tmpls, // Test the constrained portion against the grammar if (grammar_triggered && !tc.is_partial) { - auto result = match_string_detailed(constrained, grammar.get()); + auto full_tokens = fake_tokenize(specials, gen_prompt); + full_tokens.insert(full_tokens.end(), input_tokens.begin(), input_tokens.end()); + auto result = match_string_detailed(fake_tokens_from(full_tokens, constrain_from), grammar.get()); if (!result.success) { std::string error_msg; if (result.incomplete) { @@ -1514,6 +1596,7 @@ class peg_tester { common_chat_templates_ptr tmpls_; std::string template_path_; bool detailed_debug_; + common_peg_tokens specials_; friend class peg_test_builder; public: @@ -1529,6 +1612,18 @@ class peg_tester { const std::string & template_path() const { return template_path_; } + // Run the tests tokenized with these pieces as special tokens, as if the vocab defined them + peg_tester & specials(const std::vector & pieces) { + llama_token id = FAKE_TEXT_TOKEN + 1; + for (const auto & piece : pieces) { + specials_.ids.emplace(piece, id); + specials_.tokens.emplace(id, common_peg_token{ piece, LLAMA_TOKEN_ATTR_CONTROL }); + id++; + } + common_chat_templates_set_specials(tmpls_.get(), specials_); + return *this; + } + peg_test_builder test(const std::string & input); }; @@ -1649,8 +1744,10 @@ class peg_test_builder { return; } } - LOG_INF("\n\x1b[38;5;126m[%s]\x1b[0m\n%s\n\n", tester_.template_path().c_str(), tc_.input.c_str()); - test_peg_parser(tester_.tmpls_.get(), [this](peg_test_case & t) { t = tc_; }, tester_.detailed_debug_); + LOG_INF("\n\x1b[38;5;126m[%s%s]\x1b[0m\n%s\n\n", tester_.template_path().c_str(), + tester_.specials_.ids.empty() ? "" : ", tokenized", tc_.input.c_str()); + test_peg_parser(tester_.tmpls_.get(), tester_.specials_, [this](peg_test_case & t) { t = tc_; }, + tester_.detailed_debug_); } }; @@ -2269,9 +2366,17 @@ static void test_template_output_peg_parsers(bool detailed_debug) { "const": "42" })"; + // Special tokens of the templates that use the Qwen3-Coder format. + // Check that the vocab of a model defines them before reuse. A model can share the syntax without the tokens. + const std::vector qwen3_coder_specials = { + "<|im_start|>", "<|im_end|>", "", "", + "", "", "", "", + }; + { // Qwen3.5 (basically same as Nemotron, but keeping separate tests just in case) auto tst = peg_tester("models/templates/Qwen3.5-4B.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("I'm\nthinking\n\n\nHello, world!\nWhat's up?") .reasoning_format(COMMON_REASONING_FORMAT_AUTO) @@ -2843,6 +2948,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { // NVIDIA Nemotron-3 Nano auto tst = peg_tester("models/templates/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("Hello, world!\nWhat's up?"). enable_thinking(false). @@ -3138,6 +3244,8 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { // Google Gemma 4 (tool calling with Gemma4 dict format) auto tst = peg_tester("models/templates/google-gemma-4-31B-it.jinja"); + tst.specials({ "<|turn>", "", "<|channel>", "", "<|tool_call>", "", + "<|tool_response>", "", "<|tool>", "", "<|\"|>", "<|think|>" }); tst.test("Hello, world!").expect(simple_assist_msg("Hello, world!")).run(); @@ -3766,6 +3874,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { // Qwen3-Coder (tool calling with XML-style format) auto tst = peg_tester("models/templates/Qwen3-Coder.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("Hello, world!\nWhat's up?").expect(message_assist).expect_reconstruction().run(); @@ -3794,6 +3903,20 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect(message_assist_call) .run(); + // Required tool choice constrains from the first token instead of gating on a trigger + tst.test( + "\n" + "\n" + "\n" + "1\n" + "\n" + "\n" + "") + .tools({ special_function_tool }) + .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) + .expect(message_assist_call) + .run(); + tst.test( "Let me call it.\n" "\n" @@ -5895,6 +6018,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { auto tst = peg_tester("models/templates/LFM3.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("Hello, world!\nWhat's up?") .enable_thinking(false) @@ -7157,6 +7281,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // Muse Glimmer format tests { auto tst = peg_tester("models/templates/muse-glimmer.jinja", detailed_debug); + tst.specials({ "<|start|>", "<|message|>", "<|eom|>" }); const std::string call_markup = "\n" @@ -7166,7 +7291,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { ""; // A plain answer is unaffected - tst.test(" to=user<|message|>Hello, world!\nWhat's up?<|eot|>") + tst.test(" to=user<|message|>Hello, world!\nWhat's up?") .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect(message_assist) .run(); @@ -7177,7 +7302,34 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .tools({ special_function_tool }) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect(message_assist_call) - .expect_rules({ "tool-0" }) + .expect_rules({ "tool-0", "tool-calls" }) + .run(); + + // Parallel calls, one message per call + tst.test(" to=special_function<|message|>" + call_markup + "<|eom|>" + "<|start|>assistant to=special_function_with_opt<|message|>" + "\n" + "\n" + "1\n" + "2\n" + "\n" + "") + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .parallel_tool_calls(true) + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect_tool_calls({ + { "special_function", R"({"arg1": 1})", {} }, + { "special_function_with_opt", R"({"arg1": 1, "arg2": 2})", {} }, + }) + .run(); + + // Required tool choice after a reasoning message + tst.test(" to=self<|message|>I'm\nthinking<|eom|>" + "<|start|>assistant to=special_function<|message|>" + call_markup) + .tools({ special_function_tool }) + .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .expect(message_assist_call_thoughts) .run(); // "Inform then act": the model answers the user and calls a tool in ONE generation, @@ -7193,7 +7345,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // Markup quoted in an answer has no preceding <|eom|>, so it stays content instead of // becoming an invocation the user never asked for - tst.test(" to=user<|message|>You invoke it like this:\n" + call_markup + "<|eot|>") + tst.test(" to=user<|message|>You invoke it like this:\n" + call_markup) .tools({ special_function_tool }) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect_content("You invoke it like this:\n" + call_markup) @@ -7217,7 +7369,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // Tool markup inside the analysis channel is reasoning, not a call tst.test(" to=self<|message|>I could use " + call_markup + " here<|eom|>" - "<|start|>assistant to=user<|message|>Hello!<|eot|>") + "<|start|>assistant to=user<|message|>Hello!") .tools({ special_function_tool }) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .expect_reasoning("I could use " + call_markup + " here") @@ -7288,6 +7440,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { // GPT-OSS format tests { auto tst = peg_tester("models/templates/openai-gpt-oss-120b.jinja", detailed_debug); + tst.specials({ "<|start|>", "<|end|>", "<|message|>", "<|channel|>", "<|constrain|>", "<|return|>", "<|call|>" }); // Basic content only - final channel tst.test("<|channel|>final<|message|>Hello, world!\nWhat's up?").expect(message_assist).run(); @@ -7327,7 +7480,30 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .tools({ special_function_tool }) .expect(message_assist_call) - .expect_rules({ "tool-0" }) + .expect_rules({ "tool-0-in-role", "tool-0-in-channel" }) + .run(); + + // A tool whose name prefixes another's must not be reported while the header is still open + tst.test(" to=functions.special_function_with_opt<|channel|>analysis<|message|>{\"arg1\": 1}") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .expect(simple_assist_msg("", "", "special_function_with_opt", "{\"arg1\": 1}")) + .run(); + + tst.test("<|channel|>commentary to=functions.special_function_with_opt<|message|>{\"arg1\": 1}") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .tools({ special_function_tool, special_function_tool_with_optional_param }) + .expect(simple_assist_msg("", "", "special_function_with_opt", "{\"arg1\": 1}")) + .run(); + + // Required tool choice constrains from the first token instead of gating on a trigger + tst.test( + "<|channel|>analysis<|message|>I'm\nthinking<|end|>" + "<|start|>assistant to=functions.special_function<|channel|>analysis<|message|>{\"arg1\": 1}") + .reasoning_format(COMMON_REASONING_FORMAT_AUTO) + .tools({ special_function_tool }) + .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) + .expect(message_assist_call_thoughts) .run(); // Tool call with recipient in channel header: "<|channel|>analysis to=functions.NAME<|message|>JSON" @@ -7544,6 +7720,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { { auto tst = peg_tester("models/templates/StepFun3.5-Flash.jinja", detailed_debug); + tst.specials(qwen3_coder_specials); tst.test("I was thinking\n\nNow I'm not."). enable_thinking(true). diff --git a/tests/test-grammar-integration.cpp b/tests/test-grammar-integration.cpp index a7a7e968ef42..ec2b1b784c1f 100644 --- a/tests/test-grammar-integration.cpp +++ b/tests/test-grammar-integration.cpp @@ -41,15 +41,21 @@ struct token_and_piece { std::string piece; }; -// token() encodes a 32-bit ID as 5 bytes: a 0xff marker followed by the ID in big-endian order. -static std::string token(llama_token id) { +// token() encodes a token and its piece as a 0xff marker, the ID in big-endian order, the piece length, and the piece. +static std::string token(llama_token id, const std::string & piece) { return std::string{ static_cast(0xff), static_cast((id >> 24) & 0xff), static_cast((id >> 16) & 0xff), static_cast((id >> 8) & 0xff), - static_cast(id & 0xff) - }; + static_cast(id & 0xff), + static_cast(piece.size()) + } + piece; +} + +// token() without a piece encodes a token whose piece is its <[id]> spelling. +static std::string token(llama_token id) { + return token(id, "<[" + std::to_string(id) + "]>"); } // parse_tokens() parses the token encodes above and UTF-8 text. @@ -60,7 +66,7 @@ static std::vector parse_tokens(const std::string & input) { while (offset < input.size()) { try { if (static_cast(input[offset]) == 0xff) { - if (offset + 5 > input.size()) { + if (offset + 6 > input.size()) { throw std::runtime_error("not enough bytes for token id"); } uint32_t val = @@ -68,9 +74,12 @@ static std::vector parse_tokens(const std::string & input) { (static_cast(input[offset + 2]) << 16) | (static_cast(input[offset + 3]) << 8) | (static_cast(input[offset + 4])); - auto piece = "<[" + std::to_string(val) + "]>"; - result.push_back({static_cast(val), piece}); - offset += 5; + size_t len = static_cast(input[offset + 5]); + if (offset + 6 + len > input.size()) { + throw std::runtime_error("not enough bytes for token piece"); + } + result.push_back({static_cast(val), input.substr(offset + 6, len)}); + offset += 6 + len; } else { uint32_t cpt = unicode_cpt_from_utf8(input, offset); result.push_back({0, unicode_cpt_to_utf8(cpt)}); @@ -84,23 +93,42 @@ static std::vector parse_tokens(const std::string & input) { return result; } +// Returns true if the sampler mask allows the token. The mask rejects a token only when every stack rejects it. +static bool mask_allows(llama_grammar * grammar, const token_and_piece & in) { + const auto decoded = llama_grammar_decode_utf8(in.piece, grammar->partial_utf8); + + llama_grammar_candidates rejects = { { 0, decoded.first.data(), decoded.second, in.token, llama_grammar_is_opaque(*grammar, in.token) } }; + for (const auto & stack : llama_grammar_get_stacks(grammar)) { + rejects = llama_grammar_reject_candidates_for_stack(llama_grammar_get_rules(grammar), stack, rejects); + } + return rejects.empty(); +} + static bool match_string(const std::string & input, llama_grammar * grammar) { const auto parsed = parse_tokens(input); auto & stacks_cur = llama_grammar_get_stacks(grammar); for (const auto & in : parsed) { + const bool allowed = mask_allows(grammar, in); + + // the mask decides what can be sampled, so it has to agree with what accepting the token does try { llama_grammar_accept_token(*grammar, in.token, in.piece); } catch (const std::runtime_error & /*e*/) { - // normally this shouldn't get hit because of llama_grammar_apply - return false; - } + if (allowed) { + fprintf(stderr, "❌ (token %d \"%s\" is allowed by the mask but not accepted)\n", in.token, in.piece.c_str()); + } + assert(!allowed); - if (stacks_cur.empty()) { // no stacks means that the grammar failed to match at this point return false; } + + if (!allowed) { + fprintf(stderr, "❌ (token %d \"%s\" is masked but accepted)\n", in.token, in.piece.c_str()); + } + assert(allowed); } for (const auto & stack : stacks_cur) { @@ -121,6 +149,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str, // Save the original grammar stacks so that we can reset after every new string we want to test const llama_grammar_stacks stacks_org = llama_grammar_get_stacks(grammar); // copy + const llama_partial_utf8 partial_org = grammar->partial_utf8; llama_grammar_stacks & stacks_cur = llama_grammar_get_stacks(grammar); @@ -160,6 +189,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str, // Reset the grammar stacks stacks_cur = stacks_org; + grammar->partial_utf8 = partial_org; } fprintf(stderr, " 🟠 Invalid strings:\n"); @@ -180,6 +210,7 @@ static void test(const std::string & test_desc, const std::string & grammar_str, // Reset the grammar stacks stacks_cur = stacks_org; + grammar->partial_utf8 = partial_org; } // Clean up allocated memory @@ -522,6 +553,137 @@ static void test_simple_grammar() { ); } +static void test_token_rule_utf8() { + // A byte-level token can hold part of a multibyte character, a token rule still takes it as a whole token + test_grammar( + "byte-split characters under token rules", + R"""( + root ::= <[10]> content <[11]> + content ::= (!<[11]>)*)""", + // Passing strings + { + token(10) + token(20, "\xF0") + token(21, "\x9F\xA6\x99") + token(11), + token(10) + token(22, "\xE2") + token(23, "\x98\x80") + token(11), + token(10) + token(24, "a\xF0") + token(21, "\x9F\xA6\x99") + token(11), + }, + // Failing strings + { + token(10) + token(20, "\xF0"), + token(10) + token(20, "\xF0") + token(11), + } + ); + + // A token rule can only start where a token starts, not after char rules consumed part of it + test_grammar( + "token rule after a char rule", + R"""( + root ::= "a" <[11]>)""", + // Passing strings + { + "a" + token(11), + token(12, "a") + token(11), + }, + // Failing strings + { + token(11, "ab"), + token(12, "ab") + token(11), + } + ); + + // A token partly matched by a char rule stays partly matched for every alternative, whichever is checked first + test_grammar( + "token rule alternative after a char rule", + R"""( + root ::= "a" (!<[7]> | "bx"))""", + // Passing strings + { + "abx", + token(12, "abx"), + "a" + token(5), + }, + // Failing strings + { + token(5, "aby"), + token(5, "ab"), + } + ); +} + +static void test_token_sets() { + test_grammar( + "token set with alternatives and ranges", + R"""( + root ::= <[1,5-9,12]>+)""", + // Passing strings + { + token(1), + token(5) + token(9), + token(7) + token(12) + token(1), + }, + // Failing strings + { + token(2), + token(4), + token(10), + token(13), + token(5) + token(11), + } + ); + + test_grammar( + "negated token set", + R"""( + root ::= <[10]> (!<[11,20-29]>)* <[11]>)""", + // Passing strings + { + token(10) + token(11), + token(10) + "text" + token(12) + token(19) + token(30) + token(11), + }, + // Failing strings + { + token(10) + token(20) + token(11), + token(10) + token(29) + token(11), + token(10) + token(11) + token(11), + } + ); +} + +static void test_opaque_tokens() { + // Char rules do not match a token that a token rule names, other tokens still match as text + test_grammar( + "tokens named by token rules are opaque to char rules", + R"""( + root ::= [^x]* <[11]> "done")""", + // Passing strings + { + "abc" + token(11) + "done", + token(11) + "done", + token(12) + token(11) + "done", + }, + // Failing strings + { + "abc" + token(11) + "more" + token(11) + "done", + token(11) + token(11) + "done", + } + ); + + test_grammar( + "tokens named by a negated set are opaque to char rules", + R"""( + root ::= [^x]* !<[11,20-29]>)""", + // Passing strings + { + "abc" + token(30), + token(12) + token(30), + }, + // Failing strings + { + token(25) + token(30), + token(11) + token(30), + } + ); +} + static void test_complex_grammar() { // Test case for a more complex grammar, with both failure strings and success strings test_grammar( @@ -1539,6 +1701,9 @@ int main() { fprintf(stdout, "Running grammar integration tests...\n"); test_simple_grammar(); test_complex_grammar(); + test_token_rule_utf8(); + test_token_sets(); + test_opaque_tokens(); test_special_chars(); test_quantifiers(); test_failure_missing_root(); diff --git a/tests/test-grammar-parser.cpp b/tests/test-grammar-parser.cpp index a6a99520c013..6a35fd66cd58 100644 --- a/tests/test-grammar-parser.cpp +++ b/tests/test-grammar-parser.cpp @@ -179,6 +179,14 @@ int main() verify_failure(deep_grammar.c_str()); } + verify_failure(R"""( + root ::= <[9-5]> + )"""); + + verify_failure(R"""( + root ::= <[4294967296]> + )"""); + verify_parsing(R"""( root ::= "a"{0,5000} )""", { @@ -594,5 +602,21 @@ int main() {LLAMA_GRETYPE_END, 0}, }); + verify_parsing(R"""( + root ::= <[1,5-9,12]> !<[11,20-29]> + )""", { + {"root", 0} + }, { + // root (index 0) + {LLAMA_GRETYPE_TOKEN, 1}, + {LLAMA_GRETYPE_TOKEN_ALT, 5}, + {LLAMA_GRETYPE_TOKEN_RNG_UPPER, 9}, + {LLAMA_GRETYPE_TOKEN_ALT, 12}, + {LLAMA_GRETYPE_TOKEN_NOT, 11}, + {LLAMA_GRETYPE_TOKEN_ALT, 20}, + {LLAMA_GRETYPE_TOKEN_RNG_UPPER, 29}, + {LLAMA_GRETYPE_END, 0}, + }); + return 0; } diff --git a/tests/test-llama-grammar.cpp b/tests/test-llama-grammar.cpp index 25f432a2f506..3b3beb4384a3 100644 --- a/tests/test-llama-grammar.cpp +++ b/tests/test-llama-grammar.cpp @@ -202,7 +202,7 @@ int main() uint32_t *cp = new uint32_t[2]; // dynamically allocate memory for code_point cp[0] = 37 + i; cp[1] = 0; - next_candidates[i] = {i, cp, {}, 0}; + next_candidates[i] = {i, cp, {}, 0, false}; } std::vector>> expected_reject = { From e14a2d3a63253cb3bdd6a8916d8eda83ed386d37 Mon Sep 17 00:00:00 2001 From: Pedro Cuenca Date: Sun, 22 Nov 2026 18:59:17 +0100 Subject: [PATCH 044/401] skill: Pay attention to tokenizer flags (#32819) --- skills/add-new-model/SKILL.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/skills/add-new-model/SKILL.md b/skills/add-new-model/SKILL.md index 3e4d178ebeb7..3b26828686e7 100644 --- a/skills/add-new-model/SKILL.md +++ b/skills/add-new-model/SKILL.md @@ -69,6 +69,7 @@ These recur often enough in review comments on past add-model PRs that they're w - Before writing a dedicated tool-call/output parser, check whether the existing autoparser already handles the template (`test-chat-auto-parser ` shows what it detects). - Marking a custom EOS/closing-tag token as `eot` at conversion time isn't always sufficient - in long/agentic generations a model can emit the closing sequence as literal text instead of the token, so generation never stops on EOG and raw text leaks past the parser. Verify this case, not just the token path. - If reusing or aliasing an existing pre-tokenizer for convenience, justify and test that choice explicitly - silent reuse is an easy source of subtle tokenizer bugs. +- The GGUF only stores the pre-tokenizer name (`tokenizer.pre`), the behavior flags are hard-coded per name in `src/llama-vocab.cpp`. When adding a new name, set each flag from the HF `tokenizer.json`, not from the case you copied. Examples: `model.ignore_merges` -> `ignore_merges`, the BOS/EOS of the post-processor -> `special_bos_id` / `add_bos`, prefix space and space cleanup -> `add_space_prefix` / `clean_spaces`. The `chkhsh` check in the converter only identifies the pre-tokenizer on a short text, it may not catch a wrong flag. - Watch for excessive graph splits caused by building per-layer view/index tensors inside the layer loop - hoist tensors that don't vary per layer out of the loop (relevant if you hit `GGML_SCHED_MAX_SPLIT_INPUTS`). - A custom KQ mask fed into flash attention must match FA's expected dtype - cast it to F16 before passing it to `build_attn_mha` when FA is enabled. - When padding a custom KV-cache size to an alignment (e.g. `GGML_PAD(..., 256)`), apply the padding after all other size adjustments, not before - otherwise later logic can un-align it again. @@ -83,12 +84,13 @@ These recur often enough in review comments on past add-model PRs that they're w Reference: `examples/model-conversion/README.md`. 1. Convert to GGUF, then inspect/run both the original and converted tensors. -2. Run logits verification (original vs converted). If this model is a new version of an already-supported family, verify the *previous* version still passes logits verification first - numerical differences may be pre-existing, not caused by the new work. The tools to perform full logits validation are available in `examples/model-conversion`. -3. Quantize (including QAT variants if relevant) and re-verify. -4. Run perplexity evaluation (simple and full). -5. Sanity-check across `tools/cli`, `tools/completion`, `tools/imatrix`, `tools/quantize`, and `tools/server`. -6. CPU backend first; other backends (CUDA, Metal, ...) can be separate follow-up PRs per `CONTRIBUTING.md`. -7. Re-review every changed file against the coding/naming guidelines in `AGENTS.md` (and `CONTRIBUTING.md`'s "Coding guidelines"/"Naming guidelines" sections) - this is a separate pass from functional testing and is just as important: no forced line-wrapping, no unicode punctuation, minimal/non-redundant comments, `snake_case` naming (`kebab-case` for file names), matching indentation/brace style, etc. +2. If the model adds a new pre-tokenizer, compare the token ids of `llama-tokenize -f --ids --no-escape` with the HF tokenizer on whole files of prose, code and multilingual text (e.g. wikitext-2 and a few source files). +3. Run logits verification (original vs converted). If this model is a new version of an already-supported family, verify the *previous* version still passes logits verification first - numerical differences may be pre-existing, not caused by the new work. The tools to perform full logits validation are available in `examples/model-conversion`. +4. Quantize (including QAT variants if relevant) and re-verify. +5. Run perplexity evaluation (simple and full). +6. Sanity-check across `tools/cli`, `tools/completion`, `tools/imatrix`, `tools/quantize`, and `tools/server`. +7. CPU backend first; other backends (CUDA, Metal, ...) can be separate follow-up PRs per `CONTRIBUTING.md`. +8. Re-review every changed file against the coding/naming guidelines in `AGENTS.md` (and `CONTRIBUTING.md`'s "Coding guidelines"/"Naming guidelines" sections) - this is a separate pass from functional testing and is just as important: no forced line-wrapping, no unicode punctuation, minimal/non-redundant comments, `snake_case` naming (`kebab-case` for file names), matching indentation/brace style, etc. ## Before opening a PR From 56eea9e4b0f5d125da16b75b551440b170aa8b1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Gallou=C3=ABt?= Date: Sun, 22 Nov 2026 19:00:05 +0100 Subject: [PATCH 045/401] server : add offset pagination to grep_search tool (#32792) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Adrien Gallouët --- tools/server/server-tools.cpp | 29 +++++-- tools/server/tests/unit/test_tools_builtin.py | 80 +++++++++++++++++++ 2 files changed, 101 insertions(+), 8 deletions(-) diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 63626ddcc3df..060361968c59 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -1121,6 +1121,7 @@ struct server_tool_grep_search : server_tool { {"literal", {{"type", "boolean"}, {"description", "Treat pattern as a literal string instead of a regular expression (default: false)"}}}, {"ignore_case", {{"type", "boolean"}, {"description", "Case-insensitive search (default: false)"}}}, {"context_lines", {{"type", "integer"}, {"description", "Number of lines of context to show before and after each match (default: 0)"}}}, + {"offset", {{"type", "integer"}, {"description", "Number of matching lines to skip (default: 0)"}}}, }}, {"required", json::array({"path", "pattern"})}, }}, @@ -1137,6 +1138,7 @@ struct server_tool_grep_search : server_tool { bool literal = json_value(params, "literal", false); bool ignore_case = json_value(params, "ignore_case", false); int ctx_lines = std::max(0, json_value(params, "context_lines", 0)); + uint64_t offset = std::max(0, json_value(params, "offset", int64_t{0})); std::string pattern_src = pat_str; if (literal) { @@ -1164,6 +1166,7 @@ struct server_tool_grep_search : server_tool { // collect (absolute_path, display_path) pairs to search std::vector> files; + bool listing_truncated = false; const std::string abs_path = io->resolve(path); if (io->is_regular_file(abs_path)) { files.emplace_back(abs_path, path); @@ -1172,6 +1175,7 @@ struct server_tool_grep_search : server_tool { if (!listing.err.empty()) { return {{"error", listing.err + ": " + path}}; } + listing_truncated = listing.truncated; for (const auto & entry : listing.entries) { if (!path_glob_match(include, entry.rel)) continue; if (!exclude.empty() && path_glob_match(exclude, entry.rel)) continue; @@ -1180,14 +1184,18 @@ struct server_tool_grep_search : server_tool { } else { return {{"error", "path does not exist: " + path}}; } + std::sort(files.begin(), files.end(), [](const auto & a, const auto & b) { + return a.second < b.second; + }); std::ostringstream output_text; + uint64_t skipped = 0; size_t total = 0; - bool limit_reached = false; + bool has_more = false; bool show_num = show_lineno || ctx_lines > 0; for (const auto & file_entry : files) { - if (limit_reached) break; + if (has_more) break; const std::string & fpath = file_entry.first; const std::string & display_path = file_entry.second; @@ -1201,11 +1209,15 @@ struct server_tool_grep_search : server_tool { } for (size_t i = 0; i < lines.size(); i++) { + if (!std::regex_search(lines[i], pattern)) continue; + if (skipped < offset) { + skipped++; + continue; + } if (total >= SERVER_TOOL_GREP_SEARCH_MAX_RESULTS) { - limit_reached = true; + has_more = true; break; } - if (!std::regex_search(lines[i], pattern)) continue; long ctx_start = ctx_lines > 0 ? std::max(0, (long) i - ctx_lines) : (long) i; long ctx_end = ctx_lines > 0 ? std::min((long) lines.size() - 1, (long) i + ctx_lines) : (long) i; @@ -1226,10 +1238,11 @@ struct server_tool_grep_search : server_tool { } output_text << "\n---\nTotal matches: " << total << "\n"; - if (limit_reached) { - output_text << string_format( - "[%zu matches limit reached. Narrow the path/pattern/include to see more.]\n", - SERVER_TOOL_GREP_SEARCH_MAX_RESULTS); + if (has_more) { + output_text << "Continue with offset=" << offset + total << " and the same search arguments.\n"; + } + if (listing_truncated) { + output_text << "[results truncated: time budget or unreadable directory]\n"; } return {{"plain_text_response", output_text.str()}}; diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py index b6673a089b09..c830b0642f63 100755 --- a/tools/server/tests/unit/test_tools_builtin.py +++ b/tools/server/tests/unit/test_tools_builtin.py @@ -1,4 +1,5 @@ import os +import re import shutil import subprocess @@ -53,6 +54,85 @@ def test_tools_builtin_grep_search(): assert "Total matches: 1" in text +def _grep_matches(text: str) -> list[tuple[str, int, str]]: + matches = [] + for line in text.splitlines(): + match = re.match(r"^(.*):(\d+):(match-\d+)$", line) + if match: + path, line_number, identity = match.groups() + matches.append((path, int(line_number), identity)) + return matches + + +def test_tools_builtin_grep_search_pagination(tmp_path): + global server + server.start() + + path = tmp_path / "matches.txt" + expected = [f"match-{i:03d}" for i in range(231)] + path.write_text("\n".join(expected) + "\n") + params = {"path": str(path), "pattern": "match-", "return_line_numbers": True} + + pages = [] + next_offset = 0 + for page_index, expected_size in enumerate([100, 100, 31]): + page_params = params if not pages else {**params, "offset": next_offset} + text = call_tool("grep_search", page_params)["plain_text_response"] + matches = _grep_matches(text) + pages.append(matches) + assert len(matches) == expected_size + assert f"\n---\nTotal matches: {expected_size}\n" in text + + continuation = re.search(r"Continue with offset=(\d+) and the same search arguments\.", text) + if page_index < 2: + assert continuation is not None + next_offset = int(continuation.group(1)) + assert next_offset == (page_index + 1) * 100 + else: + assert continuation is None + + assert [identity for page in pages for _, _, identity in page] == expected + + +def test_tools_builtin_grep_search_exact_page_has_no_continuation(tmp_path): + global server + server.start() + + path = tmp_path / "matches.txt" + path.write_text("".join(f"match-{i:03d}\n" for i in range(100)) + "unrelated\n") + res = call_tool("grep_search", {"path": str(path), "pattern": "match-", "return_line_numbers": True}) + text = res["plain_text_response"] + + assert len(_grep_matches(text)) == 100 + assert "Total matches: 100" in text + assert "Continue with offset=" not in text + assert "matches limit reached" not in text + + +def test_tools_builtin_grep_search_page_order_with_context(tmp_path): + global server + server.start() + + (tmp_path / "z.txt").write_text("".join(f"match-{i:03d}\n" for i in range(50))) + (tmp_path / "a.txt").write_text("".join(f"match-{i:03d}\n" for i in range(50, 120))) + params = {"path": str(tmp_path), "pattern": "match-", "context_lines": 1} + + first = call_tool("grep_search", {**params, "offset": 0})["plain_text_response"] + second = call_tool("grep_search", {**params, "offset": 100})["plain_text_response"] + past_end = [call_tool("grep_search", {**params, "offset": offset})["plain_text_response"] for offset in (121, 1 << 32)] + + expected = [("a.txt", line, f"match-{line + 49:03d}") for line in range(1, 71)] + expected += [("z.txt", line, f"match-{line - 1:03d}") for line in range(1, 51)] + assert _grep_matches(first) == expected[:100] + assert _grep_matches(second) == expected[100:] + assert "Continue with offset=100 and the same search arguments." in first + assert "Continue with offset=" not in second + for text in past_end: + assert _grep_matches(text) == [] + assert "Total matches: 0" in text + assert "Continue with offset=" not in text + + def test_tools_builtin_read_file(tmp_path): global server server.start() From d2bceda3de6d61429b885f4f012bc983c6dcfd50 Mon Sep 17 00:00:00 2001 From: "Max S." Date: Mon, 23 Nov 2026 01:52:33 +0700 Subject: [PATCH 046/401] vocab: enable ignore_merges for inkling2 (#32799) --- src/llama-vocab.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index f3e1d0192414..20357e8ef192 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -2673,6 +2673,7 @@ void llama_vocab::impl::load(llama_model_loader & ml, const LLM_KV & kv) { pre_type = LLAMA_VOCAB_PRE_TYPE_GPT4O; special_bos_id = LLAMA_TOKEN_NULL; clean_spaces = false; + ignore_merges = true; } else if ( tokenizer_pre == "granite-embed-multi-97m") { pre_type = LLAMA_VOCAB_PRE_TYPE_GRANITE_EMB_MULTI; From 5bacb7c868a2bc98682de15f447fc1ce17c9c49c Mon Sep 17 00:00:00 2001 From: "Piotr Wilkin (ilintar)" Date: Sun, 22 Nov 2026 20:04:21 +0100 Subject: [PATCH 047/401] llama : copy all experts of a host weight shared by several nodes (#32807) * llama : copy all experts of a host weight shared by several nodes The scheduler copies a host weight to the device once per graph, so a partial expert copy made for the first MUL_MAT_ID is stale for the others (e.g. the shared layers of inkling2_loop with --n-cpu-moe). Assisted-by: Claude Opus 5.5 * llama : copy all experts of a host weight shared by several nodes Assisted-by: Codex --- src/llama-context.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 7490cf3794d7..07a0dbafc17e 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -3143,6 +3143,12 @@ bool llama_context::sched_copy_experts(ggml_backend_t backend, const ggml_tensor return false; } + // Later loop passes can select different experts from the same device copy. + // TODO: copy only the experts needed by each pass (see #32807 and #32809). + if (lctx->model.arch == LLM_ARCH_INKLING2_LOOP) { + return false; + } + const ggml_tensor * ids = node->src[2]; if (ggml_nelements(ids) == 0) { return true; From f505c30b92b5579e00532c9e75baa3aa74b70432 Mon Sep 17 00:00:00 2001 From: George Burton <8233643+gecBurton@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:22:46 +0000 Subject: [PATCH 048/401] mtmd: fix qwen3a audio tail (#32697) * add: test to reporduce error reported in https://github.com/ggml-org/llama.cpp/issues/32689 * fix: remove extra tokens from zero-padding of Qwen3-Omni / Qwen3-ASR audio * add: qwen3a_tokens_for_frames instead of magic numbers * refactor: only ggml_pad when required * refactor: move qwen3a_tokens_for_frames as static member of mtmd_graph_qwen3a and add test * remove: trailing empty line --------- Co-authored-by: george burton --- tests/test-mtmd-impl.cpp | 65 ++++++++++++++++++++++++++++++++++++ tools/mtmd/models/models.h | 4 +++ tools/mtmd/models/qwen3a.cpp | 17 +++++++--- tools/mtmd/mtmd-audio.cpp | 32 +++++++++--------- tools/mtmd/mtmd-audio.h | 1 + tools/mtmd/mtmd-model.cpp | 15 ++++++--- 6 files changed, 109 insertions(+), 25 deletions(-) diff --git a/tests/test-mtmd-impl.cpp b/tests/test-mtmd-impl.cpp index e24365e5969b..0c34f9c2bcce 100644 --- a/tests/test-mtmd-impl.cpp +++ b/tests/test-mtmd-impl.cpp @@ -609,6 +609,50 @@ MAKE_TEST(test_audio_preprocessor_whisper_chunks) { } } +MAKE_TEST(test_audio_preprocessor_qwen3a_tail) { + mtmd_hparams hparams; + hparams.n_mel_bins = 128; + hparams.audio_sample_rate = 16000; + hparams.audio_n_fft = 400; + hparams.audio_window_len = 400; + hparams.audio_hop_len = 160; + + ggml_backend_ptr backend(ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr)); + ggml_backend_t backends[] = { backend.get() }; + ggml_backend_sched_ptr sched(ggml_backend_sched_new(backends, nullptr, 1, 256, false, true)); + + mtmd_audio_preprocessor_qwen3a preproc(hparams, sched.get()); + preproc.initialize(); + + // one 800-frame window covers 128000 samples (hop 160), so longer audio is split; + // the last window is emitted with its exact frame count, the graph pads the final 100-frame chunk + // { sample count, expected n_len of each output window } + const std::vector>> cases = { + { 0, {} }, + { 1, {1} }, + { 32000, {200} }, + { 128000, {800} }, + { 128160, {800, 1} }, + { 168000, {800, 250} }, + { 170080, {800, 263} }, + { 176000, {800, 300} }, + }; + + for (const auto & [n_samples, expected] : cases) { + const std::string name = std::to_string(n_samples) + " samples"; + std::vector samples(n_samples, 0.0f); + if (n_samples > 0) { + samples.back() = 0.5f; + } + mtmd_audio_preproc_out out = preproc.preprocess(samples.data(), samples.size()); + t.assert_equal("windows for " + name, expected.size(), out.entries.size()); + for (size_t i = 0; i < out.entries.size(); i++) { + t.assert_equal("frames for " + name, expected[i], out.entries[i].nx()); + t.assert_equal("mel bins for " + name, 128, out.entries[i].ny()); + } + } +} + MAKE_TEST(test_audio_preprocessor_conformer) { mtmd_hparams hparams; hparams.n_mel_bins = 128; @@ -1062,6 +1106,27 @@ MAKE_TEST(test_kokoro_istft) { t.assert_true("constant signal, max error " + std::to_string(max_err), max_err < 1e-4f); } +// 13 tokens per 100-frame chunk; the tail is ceil^3 (one halving per stride-2 conv layer) +MAKE_TEST(test_qwen3a_tokens_for_frames) { + const std::vector> cases = { + { 0, 0 }, + { 1, 1 }, + { 99, 13 }, + { 100, 13 }, + { 101, 14 }, + { 110, 15 }, + { 200, 26 }, + { 210, 28 }, + { 1000, 130 }, + { 1024, 133 }, + }; + + for (const auto & [frames, expected] : cases) { + const std::string name = std::to_string(frames) + " frames"; + t.assert_equal(name, expected, mtmd_graph_qwen3a::qwen3a_tokens_for_frames(frames)); + } +} + // // main // diff --git a/tools/mtmd/models/models.h b/tools/mtmd/models/models.h index 278fcdb27eb3..c1feef493aab 100644 --- a/tools/mtmd/models/models.h +++ b/tools/mtmd/models/models.h @@ -387,6 +387,10 @@ struct mtmd_graph_mobilenetv5 : mtmd_graph { struct mtmd_graph_qwen3a : mtmd_graph { mtmd_graph_qwen3a(mtmd_subcontext * ctx, const mtmd_image_f32 & img) : mtmd_graph(ctx, img) {} ggml_cgraph * build() override; + + // audio tokens from n_frames mel frames: 13 per 100-frame chunk, ceil^3(tail) otherwise. + // shared with mtmd_model::n_output_tokens so they cannot drift + static int64_t qwen3a_tokens_for_frames(int64_t n_frames); }; struct mtmd_graph_mimo_audio : mtmd_graph { diff --git a/tools/mtmd/models/qwen3a.cpp b/tools/mtmd/models/qwen3a.cpp index 0ed6b9a8f537..24588f0c4579 100644 --- a/tools/mtmd/models/qwen3a.cpp +++ b/tools/mtmd/models/qwen3a.cpp @@ -6,14 +6,19 @@ ggml_cgraph * mtmd_graph_qwen3a::build() { // inp_raw: [n_frames, n_mel, 1] (nx=n_frames, ny=n_mel) ggml_tensor * inp = build_inp_raw(1); - const int64_t n_frames = inp->ne[0]; // total frames, padded to multiple of chunk_size const int64_t n_mel = inp->ne[1]; // 128 const int64_t chunk_size = 100; // n_window * 2 (n_window=50 from model config) - const int64_t n_chunks = n_frames / chunk_size; + const int64_t n_chunks = (inp->ne[0] + chunk_size - 1) / chunk_size; + const int64_t n_pre_pad = inp->ne[0]; - GGML_ASSERT(n_frames % chunk_size == 0); // preprocessor should already pad the input GGML_ASSERT(inp->type == GGML_TYPE_F32); + // zero-pad the last chunk to chunk_size, as the reference pads all chunks to the longest one + if (n_pre_pad % chunk_size > 0) { + inp = ggml_pad(ctx0, inp, n_chunks * chunk_size - n_pre_pad, 0, 0, 0); + } + const int64_t n_frames = inp->ne[0]; + // View mel spectrogram as batched 100-frame chunks: [chunk_size, n_mel, 1, n_chunks] inp = ggml_view_4d(ctx0, inp, chunk_size, n_mel, 1, n_chunks, @@ -69,7 +74,11 @@ ggml_cgraph * mtmd_graph_qwen3a::build() { inp = ggml_add(ctx0, inp, ggml_repeat(ctx0, pos_tmp, tgt)); } - ggml_tensor * cur = build_vit(inp, n_pos, + // drop the outputs of the padding in the last chunk + const int64_t n_out = qwen3a_tokens_for_frames(n_pre_pad); + inp = ggml_view_2d(ctx0, inp, inp->ne[0], n_out, inp->nb[1], 0); + + ggml_tensor * cur = build_vit(inp, n_out, NORM_TYPE_NORMAL, hparams.ffn_op, nullptr, // pos embd already added above nullptr); diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp index 53c2cbb27676..e0b27b9a5443 100644 --- a/tools/mtmd/mtmd-audio.cpp +++ b/tools/mtmd/mtmd-audio.cpp @@ -594,9 +594,10 @@ bool mtmd_audio_preprocessor_whisper::process(const float * samp // // Matches the Python WhisperFeatureExtractor called with truncation=False: // - reflection padding of n_fft/2 samples at each end (center=True) -// - Whisper-style log10 + (max-8)/4 normalization applied to full audio -// - output split into ≤30s (3000 mel frames) windows, each padded to a -// multiple of 200 frames (n_window * 2) for the cgraph batch view +// - the last STFT frame is dropped, giving n_samples / hop_length frames +// - Whisper-style log10 + (max-8)/4 normalization over the kept frames +// - output split into 800-frame (n_window_infer) windows; the graph +// zero-pads the last 100-frame chunk // void mtmd_audio_preprocessor_qwen3a::initialize() { @@ -648,11 +649,17 @@ bool mtmd_audio_preprocessor_qwen3a::process(const float * sampl return false; } - // Whisper-style normalization: clamp to (max - 8), scale to [-1, 1] - { + // WhisperFeatureExtractor drops the last STFT frame, keeping n_samples / hop_length frames; + // sub-hop clips would give 0 frames, clamp to 1 so the cgraph stays non-empty + const int64_t n_eff = std::max(1, std::min(mel_full.n_len - 1, (int64_t)(n_samples / hparams.audio_hop_len))); + + // Whisper-style normalization over the kept frames: clamp to (max - 8), scale to [-1, 1] + if (!shape_only) { double mmax = -1e20; - for (float v : mel_full.data) { - if (v > mmax) mmax = v; + for (int64_t m = 0; m < mel_full.n_mel; m++) { + for (int64_t t = 0; t < n_eff; t++) { + mmax = std::max(mmax, (double)mel_full.data[m * mel_full.n_len + t]); + } } mmax -= 8.0; for (float & v : mel_full.data) { @@ -660,25 +667,16 @@ bool mtmd_audio_preprocessor_qwen3a::process(const float * sampl } } - // The effective frame count: center-padded STFT gives ~n_samples/hop_length frames. - // We take min(mel_full.n_len, n_samples/hop + 1) to avoid including excess frames. - const int64_t n_eff = std::min(mel_full.n_len, - (int64_t)(n_samples / hparams.audio_hop_len) + 1); - // Split into inference windows matching n_window_infer=800 from model config. - // Each window is padded to the next multiple of chunk_size for the cgraph. // The mtmd caller loops over output entries, so long audio is handled automatically. - const int chunk_size = 100; // conv sub-chunk size (n_window * 2, n_window=50) const int window_size = 800; // mel frames per forward pass (n_window_infer=800) for (int64_t off = 0; off < n_eff; off += window_size) { const int64_t win_eff = std::min((int64_t)window_size, n_eff - off); - const int64_t n_chunks = (win_eff + chunk_size - 1) / chunk_size; - const int64_t n_padded = n_chunks * chunk_size; mtmd_audio_mel out; out.n_mel = mel_full.n_mel; - out.n_len = n_padded; + out.n_len = win_eff; out.n_len_org = win_eff; out.data.assign((size_t)out.n_mel * (size_t)out.n_len, 0.0f); for (int64_t m = 0; m < out.n_mel; m++) { diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h index 6d282721dd71..4ee78827617d 100644 --- a/tools/mtmd/mtmd-audio.h +++ b/tools/mtmd/mtmd-audio.h @@ -208,6 +208,7 @@ struct mtmd_audio_preprocessor_gemma4ua : mtmd_audio_preprocessor { struct mtmd_audio_preprocessor_qwen3a : mtmd_audio_preprocessor { mtmd_audio_preprocessor_qwen3a(const mtmd_model * model) : mtmd_audio_preprocessor(model) {} + mtmd_audio_preprocessor_qwen3a(const mtmd_hparams & hparams, ggml_backend_sched_t sched) : mtmd_audio_preprocessor(hparams, sched) {} void initialize() override; bool process(const float * samples, size_t n_samples, std::vector & output, bool shape_only) const override; diff --git a/tools/mtmd/mtmd-model.cpp b/tools/mtmd/mtmd-model.cpp index 570750b9b988..97dc47598ccc 100644 --- a/tools/mtmd/mtmd-model.cpp +++ b/tools/mtmd/mtmd-model.cpp @@ -4737,6 +4737,16 @@ int mtmd_model::n_output_tokens_y(const mtmd_image_f32 * img) const { return 1; } +int64_t mtmd_graph_qwen3a::qwen3a_tokens_for_frames(int64_t n_frames) { + const int64_t chunk_size = 100; // n_window * 2 + const int64_t tokens_per_chunk = 13; // 100 -> 50 -> 25 -> 13 after 3x stride-2 conv2d + const int64_t n_full = n_frames / chunk_size; + const int64_t n_tail = n_frames % chunk_size; + // ceil(ceil(ceil(n_tail / 2) / 2) / 2), one halving per conv layer + const int64_t n_tail_tokens = n_tail == 0 ? 0 : (((n_tail + 1) / 2 + 1) / 2 + 1) / 2; + return n_full * tokens_per_chunk + n_tail_tokens; +} + int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { const auto & params = hparams; @@ -4946,10 +4956,7 @@ int mtmd_model::n_output_tokens(const mtmd_image_f32 * img) const { } break; case PROJECTOR_TYPE_QWEN3A: { - // chunk_size=100 frames --> 3x stride-2 conv2d --> 13 tokens per chunk - const int chunk_size = 100; - const int tokens_per_chunk = 13; - n_patches = (img->nx() / chunk_size) * tokens_per_chunk; + n_patches = (int) mtmd_graph_qwen3a::qwen3a_tokens_for_frames(img->nx()); } break; case PROJECTOR_TYPE_GLMA: { From 94f3af3d09e74a0fb35f703194318d3b4037714a Mon Sep 17 00:00:00 2001 From: yoch Date: Sun, 22 Nov 2026 23:04:24 +0200 Subject: [PATCH 049/401] mtmd: speed up shared audio FFT (#32815) * mtmd: speed up shared audio FFT Replace recursive radix-2 splitting with iterative stages and batch the existing odd-size DFT across subsequences, preserving the previous operation order. Input buffers now hold only N real values for FFT or 2N interleaved floats for inverse FFT. Add test_audio_fft for forward and inverse transforms. Assisted-by: Claude * nits --------- Co-authored-by: Xuan Son Nguyen --- tests/test-mtmd-impl.cpp | 58 ++++++++++ tools/mtmd/mtmd-audio.cpp | 224 ++++++++++++++++++-------------------- tools/mtmd/mtmd-audio.h | 8 +- 3 files changed, 168 insertions(+), 122 deletions(-) diff --git a/tests/test-mtmd-impl.cpp b/tests/test-mtmd-impl.cpp index 0c34f9c2bcce..319811b77315 100644 --- a/tests/test-mtmd-impl.cpp +++ b/tests/test-mtmd-impl.cpp @@ -881,6 +881,64 @@ static double tone_amplitude(const std::vector & x, double freq, int rate return 2.0 * std::sqrt(re * re + im * im) / (x.size() - 2 * skip); } +MAKE_TEST(test_audio_fft) { + // the sizes in use: powers of two, and an odd part (400 = 16 * 25, 736 = 32 * 23, 1920 = 128 * 15) + // plus small edge cases: 4 = gather + one stage, 6 = n_odd 3 with n_sub 2, 15 = odd composite with n_sub 1 + const int sizes[] = { 1, 2, 3, 4, 6, 12, 15, 256, 400, 512, 736, 1920 }; + const double pi = 3.14159265358979323846; + for (int n : sizes) { + mtmd_audio_cache cache; + cache.fill_sin_cos_table(n); + // phase offset so that x[0] != 0 (n = 1 would otherwise compare all zeros) + std::vector x(2 * n); + for (int i = 0; i < 2 * n; i++) { + x[i] = (float) std::sin(0.37 * i + 0.001 * i * i + 0.5); + } + std::vector out(8 * n); + for (bool inv : { false, true }) { + // input sized exactly as documented so that sanitizers catch any overread + const std::vector in(x.begin(), x.begin() + (inv ? 2 * n : n)); + if (inv) { + mtmd_audio_ifft(cache, in.data(), n, out.data()); + } else { + mtmd_audio_fft(cache, in.data(), n, out.data()); + } + double max_err = 0.0, max_ref = 0.0; + for (int k = 0; k < n; k++) { + double re = 0.0, im = 0.0; + for (int j = 0; j < n; j++) { + const double theta = (inv ? 2 : -2) * pi * (double) ((int64_t) j * k % n) / n; + const double a = inv ? x[2 * j] : x[j]; + const double b = inv ? x[2 * j + 1] : 0.0; + re += a * std::cos(theta) - b * std::sin(theta); + im += a * std::sin(theta) + b * std::cos(theta); + } + if (inv) { + re /= n; + im /= n; + } + max_err = std::max({ max_err, std::fabs(re - out[2 * k]), std::fabs(im - out[2 * k + 1]) }); + max_ref = std::max({ max_ref, std::fabs(re), std::fabs(im) }); + } + t.assert_true(std::string(inv ? "ifft" : "fft") + " n = " + std::to_string(n) + ", relative error " + std::to_string(max_err / max_ref), + max_ref > 0.0 && max_err <= 1e-5 * max_ref); + } + + // round trip: ifft(fft(x)) == x for real x + std::vector spec(8 * n); + mtmd_audio_fft(cache, x.data(), n, spec.data()); + const std::vector spec_in(spec.begin(), spec.begin() + 2 * n); + mtmd_audio_ifft(cache, spec_in.data(), n, out.data()); + double max_err = 0.0, max_ref = 0.0; + for (int k = 0; k < n; k++) { + max_err = std::max({ max_err, (double) std::fabs(out[2 * k] - x[k]), (double) std::fabs(out[2 * k + 1]) }); + max_ref = std::max(max_ref, (double) std::fabs(x[k])); + } + t.assert_true("fft round trip n = " + std::to_string(n) + ", relative error " + std::to_string(max_err / max_ref), + max_ref > 0.0 && max_err <= 1e-5 * max_ref); + } +} + static std::vector resample_chunked(mtmd_helper_resampler * rs, const std::vector & in, size_t chunk) { std::vector res; for (size_t off = 0; off < in.size(); off += chunk) { diff --git a/tools/mtmd/mtmd-audio.cpp b/tools/mtmd/mtmd-audio.cpp index e0b27b9a5443..bfea3a364a48 100644 --- a/tools/mtmd/mtmd-audio.cpp +++ b/tools/mtmd/mtmd-audio.cpp @@ -129,152 +129,140 @@ void mtmd_audio_cache::fill_mel_filterbank_matrix(int64_t n_mel, } } -// Unified DFT implementation for both forward and inverse transforms +// FFT/IFFT of N = n_sub * n_odd points (n_sub a power of two, n_odd odd): batched odd-size DFT of the n_sub subsequences into bit-reversed blocks, then iterative radix-2 stages +// matches the previous recursive implementation for finite inputs (the twiddle-1 multiply of the first stage is skipped when n_odd == 1) // Template parameters: -// Inverse: false = DFT with exp(-2πi·k·n/N), no scaling -// true = IDFT with exp(+2πi·k·n/N), scales by 1/N -// RealInput: true = input is real-valued (stride 1), avoids imaginary computations -// false = input is complex-valued (interleaved real/imag, stride 2) -template -static void dft_impl(const mtmd_audio_cache & cache, const float * in, int N, float * out) { - const int n_sin_cos_vals = cache.sin_vals.size(); - const int sin_cos_step = n_sin_cos_vals / N; - - constexpr float sign = Inverse ? 1.0f : -1.0f; - const float scale = Inverse ? (1.0f / N) : 1.0f; - - for (int k = 0; k < N; k++) { - float re = 0; - float im = 0; - - for (int n = 0; n < N; n++) { - int idx = (k * n * sin_cos_step) % n_sin_cos_vals; - float cos_val = cache.cos_vals[idx]; - float sin_val = cache.sin_vals[idx]; - - if constexpr (RealInput) { - // Real input: in_im = 0, simplifies to: - // re += in_re * cos_val - // im += sign * in_re * sin_val - float in_re = in[n]; - re += in_re * cos_val; - im += sign * in_re * sin_val; - } else { - float in_re = in[n * 2 + 0]; - float in_im = in[n * 2 + 1]; - // (a + bi) * (cos + sign*i*sin) = (a*cos - sign*b*sin) + (sign*a*sin + b*cos)i - re += in_re * cos_val - sign * in_im * sin_val; - im += sign * in_re * sin_val + in_im * cos_val; - } - } - - out[k * 2 + 0] = re * scale; - out[k * 2 + 1] = im * scale; - } -} - -// Cooley-Tukey FFT/IFFT unified implementation -// Template parameters: -// Inverse: false = FFT with exp(-2πi·k/N), no scaling -// true = IFFT with exp(+2πi·k/N), scales by 0.5 at each level +// Inverse: false = FFT with exp(-2 pi i k / N), no scaling +// true = IFFT with exp(+2 pi i k / N), scales by 1/N (1/n_odd in the DFT, 0.5 per stage) // RealInput: true = input is real-valued (stride 1) // false = input is complex-valued (interleaved real/imag, stride 2) +// in is not modified, out needs 2 * N floats + 2 * max(N / 2, n_sub) floats of scratch template -static void fft_impl(const mtmd_audio_cache & cache, float * in, int N, float * out) { +static void fft_impl(const mtmd_audio_cache & cache, const float * in, int N, float * out) { GGML_ASSERT(N > 0); const int n_sin_cos_vals = cache.sin_vals.size(); - if (N == 1) { - out[0] = in[0]; - if constexpr (RealInput) { - out[1] = 0.0f; - } else { - out[1] = in[1]; - } - return; - } + constexpr float sign = Inverse ? 1.0f : -1.0f; + constexpr float scale = Inverse ? 0.5f : 1.0f; + constexpr int n_in = RealInput ? 1 : 2; // floats per input value - const int half_N = N / 2; - if (N - half_N * 2 == 1) { - // Odd N: fall back to DFT - dft_impl(cache, in, N, out); - return; + int n_odd = N; + while (n_odd % 2 == 0) { + n_odd /= 2; } + const int n_sub = N / n_odd; - // Split into even and odd - if constexpr (RealInput) { - // Real input: stride is 1, copy only real values - float * even = in + N; - for (int i = 0; i < half_N; ++i) { - even[i] = in[2 * i]; + // j = bitrev(r) for r = 0, 1, ...: add 1 to j starting from its highest bit h + auto bitrev_next = [](int & j, int h) { + for (; j & h; h >>= 1) { + j ^= h; } - float * even_fft = out + 2 * N; - fft_impl(cache, even, half_N, even_fft); + j |= h; + }; - float * odd = even; - for (int i = 0; i < half_N; ++i) { - odd[i] = in[2 * i + 1]; + float * scratch = out + 2 * N; + int len = 2 * n_odd; // size of the blocks after the next stage + if (n_odd > 1) { + const int sin_cos_step = n_sin_cos_vals / n_odd; + const float dft_scale = Inverse ? (1.0f / n_odd) : 1.0f; + float * acc = scratch; + for (int k = 0; k < n_odd; k++) { + std::fill(acc, acc + 2 * n_sub, 0.0f); + int idx = 0; // (k * n * sin_cos_step) % n_sin_cos_vals + for (int n = 0; n < n_odd; n++) { + const float cos_val = cache.cos_vals[idx]; + const float sin_val = cache.sin_vals[idx]; + const float * x = in + n * n_sub * n_in; + for (int r = 0; r < n_sub; r++) { + if constexpr (RealInput) { + acc[2 * r + 0] += x[r] * cos_val; + acc[2 * r + 1] += sign * x[r] * sin_val; + } else { + // (a + bi) * (cos + sign*i*sin) = (a*cos - sign*b*sin) + (sign*a*sin + b*cos)i + acc[2 * r + 0] += x[2 * r + 0] * cos_val - sign * x[2 * r + 1] * sin_val; + acc[2 * r + 1] += sign * x[2 * r + 0] * sin_val + x[2 * r + 1] * cos_val; + } + } + idx += k * sin_cos_step; + if (idx >= n_sin_cos_vals) { + idx -= n_sin_cos_vals; + } + } + for (int r = 0, j = 0; r < n_sub; r++, bitrev_next(j, n_sub / 2)) { + out[2 * (j * n_odd + k) + 0] = acc[2 * r + 0] * dft_scale; + out[2 * (j * n_odd + k) + 1] = acc[2 * r + 1] * dft_scale; + } } - float * odd_fft = even_fft + N; - fft_impl(cache, odd, half_N, odd_fft); + } else if (N == 1) { + out[0] = in[0]; + out[1] = RealInput ? 0.0f : in[1]; + return; } else { - // Complex input: stride is 2, copy complex pairs - float * even = in + N * 2; - for (int i = 0; i < half_N; ++i) { - even[i * 2 + 0] = in[2 * i * 2 + 0]; - even[i * 2 + 1] = in[2 * i * 2 + 1]; + // size 1 subsequences: the values r and r + N / 2 form block bitrev(r) of the first stage + const int half_N = N / 2; + for (int j = 0, r = 0; j < half_N; j++, bitrev_next(r, half_N / 2)) { + const float * a = in + r * n_in; + const float * b = in + (r + half_N) * n_in; + if constexpr (RealInput) { + out[4 * j + 0] = scale * (a[0] + b[0]); + out[4 * j + 1] = 0.0f; + out[4 * j + 2] = scale * (a[0] - b[0]); + out[4 * j + 3] = 0.0f; + } else { + out[4 * j + 0] = scale * (a[0] + b[0]); + out[4 * j + 1] = scale * (a[1] + b[1]); + out[4 * j + 2] = scale * (a[0] - b[0]); + out[4 * j + 3] = scale * (a[1] - b[1]); + } } - float * even_fft = out + 2 * N; - fft_impl(cache, even, half_N, even_fft); - - float * odd = even; - for (int i = 0; i < half_N; ++i) { - odd[i * 2 + 0] = in[(2 * i + 1) * 2 + 0]; - odd[i * 2 + 1] = in[(2 * i + 1) * 2 + 1]; + len = 4; + } + + for (; len <= N; len *= 2) { + const int half_N = len / 2; + const int sin_cos_step = n_sin_cos_vals / len; + // twiddles of this stage, contiguous + float * twiddle = scratch; + for (int k = 0; k < half_N; k++) { + twiddle[2 * k + 0] = cache.cos_vals[k * sin_cos_step]; // t = 2*M_PI*k/len + twiddle[2 * k + 1] = sign * cache.sin_vals[k * sin_cos_step]; + } + for (int i = 0; i < N; i += len) { + float * even_fft = out + 2 * i; + float * odd_fft = even_fft + 2 * half_N; + for (int k = 0; k < half_N; k++) { + const float re = twiddle[2 * k + 0]; + const float im = twiddle[2 * k + 1]; + const float re_even = even_fft[2 * k + 0]; + const float im_even = even_fft[2 * k + 1]; + const float re_odd = odd_fft[2 * k + 0]; + const float im_odd = odd_fft[2 * k + 1]; + + even_fft[2 * k + 0] = scale * (re_even + re * re_odd - im * im_odd); + even_fft[2 * k + 1] = scale * (im_even + re * im_odd + im * re_odd); + + odd_fft[2 * k + 0] = scale * (re_even - re * re_odd + im * im_odd); + odd_fft[2 * k + 1] = scale * (im_even - re * im_odd - im * re_odd); + } } - float * odd_fft = even_fft + N; - fft_impl(cache, odd, half_N, odd_fft); - } - - float * even_fft = out + 2 * N; - float * odd_fft = even_fft + N; - - const int sin_cos_step = n_sin_cos_vals / N; - - constexpr float sign = Inverse ? 1.0f : -1.0f; - constexpr float scale = Inverse ? 0.5f : 1.0f; - - for (int k = 0; k < half_N; k++) { - int idx = k * sin_cos_step; // t = 2*M_PI*k/N - float re = cache.cos_vals[idx]; - float im = sign * cache.sin_vals[idx]; - - float re_odd = odd_fft[2 * k + 0]; - float im_odd = odd_fft[2 * k + 1]; - - out[2 * k + 0] = scale * (even_fft[2 * k + 0] + re * re_odd - im * im_odd); - out[2 * k + 1] = scale * (even_fft[2 * k + 1] + re * im_odd + im * re_odd); - - out[2 * (k + half_N) + 0] = scale * (even_fft[2 * k + 0] - re * re_odd + im * im_odd); - out[2 * (k + half_N) + 1] = scale * (even_fft[2 * k + 1] - re * im_odd - im * re_odd); } } // Forward FFT for real input (used by mel spectrogram) -static void fft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +static void fft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { fft_impl(cache, in, N, out); } // Inverse FFT for complex input -static void ifft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +static void ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { fft_impl(cache, in, N, out); } -void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +void mtmd_audio_fft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { fft(cache, in, N, out); } -void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out) { +void mtmd_audio_ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out) { ifft(cache, in, N, out); } @@ -1955,7 +1943,7 @@ mtmd_audio_zonos3_synth::mtmd_audio_zonos3_synth(const std::vector & mixe b.n_fft = n_fft[i]; b.cache.fill_sin_cos_table(b.n_fft); b.cache.fill_hann_window(b.n_fft, true); - b.ifft_in.assign((size_t) b.n_fft * 2 * 4, 0.0f); + b.ifft_in.assign((size_t) b.n_fft * 2, 0.0f); b.ifft_out.assign((size_t) b.n_fft * 2 * 4, 0.0f); b.mix_in.assign((size_t) h, 0.0f); b.mix_avail = h; @@ -2116,7 +2104,7 @@ mtmd_audio_streaming_istft::mtmd_audio_streaming_istft(int n_fft, int hop_length overlap_buffer(n_fft, 0.0f), window_sum_buffer(n_fft, 0.0f), padding_to_remove((n_fft - hop_length) / 2), - ifft_in(n_fft * 2 * 4, 0.0f), // extra space for recursive IFFT + ifft_in(n_fft * 2, 0.0f), ifft_out(n_fft * 2 * 4, 0.0f) { GGML_ASSERT(n_fft > 0 && hop_length > 0 && hop_length <= n_fft); cache.fill_sin_cos_table(n_fft); diff --git a/tools/mtmd/mtmd-audio.h b/tools/mtmd/mtmd-audio.h index 4ee78827617d..269e78cc40f5 100644 --- a/tools/mtmd/mtmd-audio.h +++ b/tools/mtmd/mtmd-audio.h @@ -52,10 +52,10 @@ struct mtmd_audio_cache { ); }; -// FFT of N real samples -> N complex values (interleaved), in needs 2 * N floats and out 8 * N floats (scratch) -void mtmd_audio_fft(const mtmd_audio_cache & cache, float * in, int N, float * out); -// inverse FFT of N complex values (interleaved), scaled by 1 / N; in and out need 8 * N floats (scratch) -void mtmd_audio_ifft(const mtmd_audio_cache & cache, float * in, int N, float * out); +// FFT of N real samples -> N complex values (interleaved), in holds N floats, out needs 8 * N floats (scratch) +void mtmd_audio_fft(const mtmd_audio_cache & cache, const float * in, int N, float * out); +// inverse FFT of N complex values (interleaved), scaled by 1 / N; in holds 2 * N floats, out needs 8 * N floats (scratch) +void mtmd_audio_ifft(const mtmd_audio_cache & cache, const float * in, int N, float * out); // compute one log10-mel frame from n_fft windowed samples, cache must be initialized for n_fft void mtmd_audio_log_mel_frame(const mtmd_audio_cache & cache, const float * samples, int n_fft, int n_mel, float * out); From 253671d8825729b607aeb7ad1ffc38547480c392 Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Mon, 23 Nov 2026 01:20:22 +0100 Subject: [PATCH 050/401] chat: fix LFM2.5-VL template detection (#32843) --- common/chat.cpp | 2 +- models/templates/LFM2.5-VL.jinja | 92 ++++++++++++++++++++++++++++++++ tests/test-chat.cpp | 2 + 3 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 models/templates/LFM2.5-VL.jinja diff --git a/common/chat.cpp b/common/chat.cpp index 3cff920cf16b..b6eac61f87ed 100644 --- a/common/chat.cpp +++ b/common/chat.cpp @@ -1406,7 +1406,7 @@ static common_chat_params_init_fn common_chat_template_detect_params_init(const } // LFM2.5 format detection: template uses plain "List of tools: [...]" with no special tokens - if (src.find("List of tools: [") != std::string::npos && + if (src.find("List of tools: ") != std::string::npos && src.find("<|tool_list_start|>") == std::string::npos) { LOG_DBG("Using specialized template: LFM2.5\n"); return common_chat_params_init_lfm2_5; diff --git a/models/templates/LFM2.5-VL.jinja b/models/templates/LFM2.5-VL.jinja new file mode 100644 index 000000000000..d409984f9902 --- /dev/null +++ b/models/templates/LFM2.5-VL.jinja @@ -0,0 +1,92 @@ +{{- bos_token -}} +{%- set keep_past_thinking = keep_past_thinking | default(false) -%} + +{%- macro format_arg_value(arg_value) -%} + {%- if arg_value is string -%} + {{- '"' + arg_value + '"' -}} + {%- elif arg_value is mapping -%} + {{- arg_value | tojson -}} + {%- else -%} + {{- arg_value | string -}} + {%- endif -%} +{%- endmacro -%} + +{%- macro parse_content(content) -%} + {%- if content is string -%} + {{- content -}} + {%- else -%} + {%- set _ns = namespace(result="") -%} + {%- for item in content -%} + {%- if item.type == "image" -%} + {%- set _ns.result = _ns.result + "" -%} + {%- elif item.type == "text" -%} + {%- set _ns.result = _ns.result + item.text -%} + {%- else -%} + {%- set _ns.result = _ns.result + item | tojson -%} + {%- endif -%} + {%- endfor -%} + {{- _ns.result -}} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_calls(tool_calls) -%} + {%- set tool_calls_ns = namespace(tool_calls=[]) -%} + {%- for tool_call in tool_calls -%} + {%- set func_name = tool_call.function.name -%} + {%- set func_args = tool_call.function.arguments -%} + {%- set args_ns = namespace(arg_strings=[]) -%} + {%- for arg_name, arg_value in func_args.items() -%} + {%- set args_ns.arg_strings = args_ns.arg_strings + [arg_name + "=" + format_arg_value(arg_value)] -%} + {%- endfor -%} + {%- set tool_calls_ns.tool_calls = tool_calls_ns.tool_calls + [func_name + "(" + (args_ns.arg_strings | join(", ")) + ")"] -%} + {%- endfor -%} + {{- "<|tool_call_start|>[" + (tool_calls_ns.tool_calls | join(", ")) + "]<|tool_call_end|>" -}} +{%- endmacro -%} + +{%- set ns = namespace(system_prompt="", last_assistant_index=-1) -%} +{%- if messages[0].role == "system" -%} + {%- if messages[0].content is defined -%} + {%- set ns.system_prompt = parse_content(messages[0].content) -%} + {%- endif -%} + {%- set messages = messages[1:] -%} +{%- endif -%} +{%- if tools -%} + {%- set ns.system_prompt = ns.system_prompt + ("\n\n" if ns.system_prompt else "") + "Today's date: " + strftime_now("%Y-%m-%d") + "\n\nList of tools: " + (tools | tojson) -%} +{%- endif -%} +{%- if ns.system_prompt -%} + {{- "<|im_start|>system\n" + ns.system_prompt + "<|im_end|>\n" -}} +{%- endif -%} +{%- for message in messages -%} + {%- if message.role == "assistant" -%} + {%- set ns.last_assistant_index = loop.index0 -%} + {%- endif -%} +{%- endfor -%} +{%- for message in messages -%} + {{- "<|im_start|>" + message.role + "\n" -}} + {%- if message.role == "assistant" -%} + {%- generation -%} + {%- if message.thinking is defined and (keep_past_thinking or loop.index0 == ns.last_assistant_index) -%} + {{- "" + message.thinking + "" -}} + {%- endif -%} + {%- if message.tool_calls is defined -%} + {{- render_tool_calls(message.tool_calls) -}} + {%- endif -%} + {%- if message.content is defined -%} + {%- set content = parse_content(message.content) -%} + {%- if not keep_past_thinking and loop.index0 != ns.last_assistant_index -%} + {%- if "" in content -%} + {%- set content = content.split("")[-1] | trim -%} + {%- endif -%} + {%- endif -%} + {{- content + ("" if (continue_final_message and loop.last) else "<|im_end|>\n") -}} + {%- endif -%} + {%- endgeneration -%} + {%- else %} + {%- if message.content is defined -%} + {{- parse_content(message.content) + "<|im_end|>\n" -}} + {%- endif -%} + {%- endif %} +{%- endfor -%} +{%- if add_generation_prompt -%} + {{- "<|im_start|>assistant\n" -}} +{%- endif -%} diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 11fa68f6a736..341e7acebd9d 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -6012,6 +6012,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { "models/templates/LFM2-8B-A1B.jinja", "models/templates/LFM2.5-Instruct.jinja", "models/templates/LFM2.5-8B-A1B.jinja", + "models/templates/LFM2.5-VL.jinja", }) { test_lfm2_parser(tmpl, detailed_debug); } @@ -8215,6 +8216,7 @@ static void test_template_generation_prompt() { "models/templates/LFM2-8B-A1B.jinja", "models/templates/LFM2.5-Instruct.jinja", "models/templates/LFM2.5-8B-A1B.jinja", + "models/templates/LFM2.5-VL.jinja", }) { auto tmpls = read_templates(tmpl); check(tmpls, basic(), "<|im_start|>assistant\n"); From f4f6f2e7db76e98c95cc9b7fc608ea669c806044 Mon Sep 17 00:00:00 2001 From: Alexey Kopytko Date: Mon, 23 Nov 2026 09:48:16 +0900 Subject: [PATCH 051/401] ggml-backend : generic fallback in ggml_backend_tensor_memset (#32574) --- ggml/src/ggml-backend-impl.h | 3 +- ggml/src/ggml-backend.cpp | 12 +++++- ggml/src/ggml-rpc/ggml-rpc.cpp | 4 -- src/llama-impl.cpp | 10 ----- src/llama-impl.h | 2 - src/llama-kv-cache.cpp | 12 +++--- src/llama-memory-recurrent.cpp | 6 +-- tests/test-backend-tensor.cpp | 67 ++++++++++++++++++++++++++++++++-- 8 files changed, 86 insertions(+), 30 deletions(-) diff --git a/ggml/src/ggml-backend-impl.h b/ggml/src/ggml-backend-impl.h index 545880b068c7..aaec8ac41d80 100644 --- a/ggml/src/ggml-backend-impl.h +++ b/ggml/src/ggml-backend-impl.h @@ -57,8 +57,9 @@ extern "C" { void * (*get_base) (ggml_backend_buffer_t buffer); // (optional) initialize a tensor in the buffer (eg. add tensor extras) enum ggml_status (*init_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor); - // tensor data access + // (optional) fill tensor data with a value, ggml_backend_tensor_memset falls back to set_tensor void (*memset_tensor)(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size); + // tensor data access void (*set_tensor) (ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size); void (*get_tensor) (ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size); // (optional) 2d data copies diff --git a/ggml/src/ggml-backend.cpp b/ggml/src/ggml-backend.cpp index d598ca3d86d1..8e175649b14d 100644 --- a/ggml/src/ggml-backend.cpp +++ b/ggml/src/ggml-backend.cpp @@ -761,7 +761,17 @@ void ggml_backend_tensor_memset(struct ggml_tensor * tensor, uint8_t value, size GGML_ASSERT(buf != NULL && "tensor buffer not set"); GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds"); - GGML_ASSERT(buf->iface.memset_tensor != NULL && "memset not implemented by backend buffer"); + + if (buf->iface.memset_tensor == NULL) { + GGML_ASSERT(buf->iface.set_tensor != NULL && "memset not implemented by backend buffer"); + + // fallback: write the value in chunks with set_tensor + const std::vector chunk(std::min(size, (size_t) 1024*1024), value); + for (size_t chunk_offset = 0; chunk_offset < size; chunk_offset += chunk.size()) { + ggml_backend_tensor_set(tensor, chunk.data(), offset + chunk_offset, std::min(size - chunk_offset, chunk.size())); + } + return; + } buf->iface.memset_tensor(buf, tensor, value, offset, size); } diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index e4a84cb0caf0..dbd7dd467709 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -1683,10 +1683,6 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { LOG_ERROR("[%s] tensor region out of buffer bounds\n", __func__); return false; } - if (tensor->buffer->iface.memset_tensor == nullptr) { - LOG_ERROR("[%s] memset not implemented by backend buffer\n", __func__); - return false; - } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, value: %u\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void *) tensor->buffer, tensor->data, request.offset, diff --git a/src/llama-impl.cpp b/src/llama-impl.cpp index 4ca836ca66c3..9c39c921c00c 100644 --- a/src/llama-impl.cpp +++ b/src/llama-impl.cpp @@ -88,16 +88,6 @@ void llama_log_callback_default(ggml_log_level level, const char * text, void * fflush(stderr); } -void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size) { - static const std::vector zeros(1024*1024, 0); - - // not all backend buffers implement ggml_backend_tensor_memset(), so write zeros instead - // TODO: make this a generic fallback in `ggml_backend_tensor_memset` when `set_tensor` is available - for (size_t ofs = 0; ofs < size; ofs += zeros.size()) { - ggml_backend_tensor_set(t, zeros.data(), offset + ofs, std::min(size - ofs, zeros.size())); - } -} - void replace_all(std::string & s, const std::string & search, const std::string & replace) { if (search.empty()) { return; diff --git a/src/llama-impl.h b/src/llama-impl.h index 884dca647995..927657ba4025 100644 --- a/src/llama-impl.h +++ b/src/llama-impl.h @@ -96,8 +96,6 @@ struct buffer_view { } }; -void llama_clear_tensor_data(ggml_tensor * t, size_t offset, size_t size); - void replace_all(std::string & s, const std::string & search, const std::string & replace); // TODO: rename to llama_format ? diff --git a/src/llama-kv-cache.cpp b/src/llama-kv-cache.cpp index fbe422a2717a..bb546f7cdec8 100644 --- a/src/llama-kv-cache.cpp +++ b/src/llama-kv-cache.cpp @@ -2919,10 +2919,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_ const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa); if (is_contiguous) { - llama_clear_tensor_data(k, sinfo.head() * k_size_row, cell_count * k_size_row); + ggml_backend_tensor_memset(k, 0, sinfo.head() * k_size_row, cell_count * k_size_row); } else { for (uint32_t i = 0; i < cell_count; ++i) { - llama_clear_tensor_data(k, sinfo.idxs[0][i] * k_size_row, k_size_row); + ggml_backend_tensor_memset(k, 0, sinfo.idxs[0][i] * k_size_row, k_size_row); } } } @@ -2941,10 +2941,10 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_ const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa); if (is_contiguous) { - llama_clear_tensor_data(v, sinfo.head() * v_size_row, cell_count * v_size_row); + ggml_backend_tensor_memset(v, 0, sinfo.head() * v_size_row, cell_count * v_size_row); } else { for (uint32_t i = 0; i < cell_count; ++i) { - llama_clear_tensor_data(v, sinfo.idxs[0][i] * v_size_row, v_size_row); + ggml_backend_tensor_memset(v, 0, sinfo.idxs[0][i] * v_size_row, v_size_row); } } } else { @@ -2954,12 +2954,12 @@ void llama_kv_cache::state_clear(llama_seq_id seq_id, uint32_t strm, const slot_ const uint32_t h = sinfo.head(); for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { - llama_clear_tensor_data(v, (h + j * cells.size()) * v_size_el, cell_count * v_size_el); + ggml_backend_tensor_memset(v, 0, (h + j * cells.size()) * v_size_el, cell_count * v_size_el); } } else { for (uint32_t j = 0; j < n_embd_v_gqa; ++j) { for (uint32_t i = 0; i < cell_count; ++i) { - llama_clear_tensor_data(v, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el); + ggml_backend_tensor_memset(v, 0, (sinfo.idxs[0][i] + j * cells.size()) * v_size_el, v_size_el); } } } diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 2bb8ef18c118..0d5739695186 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -1265,17 +1265,17 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head for (uint32_t il = 0; il < n_layer; ++il) { if (r_l[il] != nullptr) { const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); - llama_clear_tensor_data(r_l[il], cell_head * r_size_row, cell_count * r_size_row); + ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row); } if (s_l[il] != nullptr) { const size_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s()); - llama_clear_tensor_data(s_l[il], cell_head * s_size_row, cell_count * s_size_row); + ggml_backend_tensor_memset(s_l[il], 0, cell_head * s_size_row, cell_count * s_size_row); } if (p_l[il] != nullptr) { const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); - llama_clear_tensor_data(p_l[il], cell_head * p_size_row, cell_count * p_size_row); + ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row); } } } diff --git a/tests/test-backend-tensor.cpp b/tests/test-backend-tensor.cpp index 84c4dc2bd30f..3f480a9ec3b8 100644 --- a/tests/test-backend-tensor.cpp +++ b/tests/test-backend-tensor.cpp @@ -357,14 +357,17 @@ static bool test_buft(ggml_backend_buffer_type_t buft) { // Mock buffer type // // Ad-hoc host-backed buffer type used to exercise the dispatch logic in -// ggml_backend_tensor_{set,get,copy}_n without relying on real backend hooks. +// ggml_backend_tensor_{set,get,copy}_n and ggml_backend_tensor_memset +// without relying on real backend hooks. // struct mock_config { + bool memset; bool set_n; bool get_n; bool cpy_n; bool cpy_n_result; + int set_calls; int set_n_calls; int get_n_calls; int cpy_n_calls; @@ -373,10 +376,12 @@ struct mock_config { static mock_config g_mock = {}; static void mock_config_reset(bool set_n, bool get_n, bool cpy_n, bool cpy_n_result) { + g_mock.memset = true; g_mock.set_n = set_n; g_mock.get_n = get_n; g_mock.cpy_n = cpy_n; g_mock.cpy_n_result = cpy_n_result; + g_mock.set_calls = 0; g_mock.set_n_calls = 0; g_mock.get_n_calls = 0; g_mock.cpy_n_calls = 0; @@ -397,6 +402,7 @@ static void mock_buffer_memset_tensor(ggml_backend_buffer_t buffer, struct ggml_ } static void mock_buffer_set_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) { + g_mock.set_calls++; memcpy((char *) tensor->data + offset, data, size); GGML_UNUSED(buffer); @@ -466,7 +472,7 @@ static ggml_backend_buffer_t mock_buft_alloc_buffer(ggml_backend_buffer_type_t b /* .free_buffer = */ mock_buffer_free_buffer, /* .get_base = */ mock_buffer_get_base, /* .init_tensor = */ NULL, - /* .memset_tensor = */ mock_buffer_memset_tensor, + /* .memset_tensor = */ NULL, /* .set_tensor = */ mock_buffer_set_tensor, /* .get_tensor = */ mock_buffer_get_tensor, /* .set_tensor_2d = */ NULL, @@ -478,6 +484,7 @@ static ggml_backend_buffer_t mock_buft_alloc_buffer(ggml_backend_buffer_type_t b /* .get_tensor_n = */ NULL, /* .cpy_tensor_n = */ NULL, }; + if (g_mock.memset) iface.memset_tensor = mock_buffer_memset_tensor; if (g_mock.set_n) iface.set_tensor_n = mock_buffer_set_tensor_n; if (g_mock.get_n) iface.get_tensor_n = mock_buffer_get_tensor_n; if (g_mock.cpy_n) iface.cpy_tensor_n = mock_buffer_cpy_tensor_n; @@ -665,13 +672,67 @@ static bool test_mock_grouping() { return true; } +// verify that memset routes to memset_tensor when the buffer has it and to set_tensor otherwise +static bool test_mock_memset(bool with_hook) { + mock_config_reset(false, false, false, true); + g_mock.memset = with_hook; + + ggml_init_params params = {}; + params.mem_size = ggml_tensor_overhead(); + params.no_alloc = true; + + ggml_context_ptr ctx(ggml_init(params)); + if (!ctx) { + return false; + } + + // the fallback writes in chunks of this size, see ggml_backend_tensor_memset + const size_t chunk_size = 1024*1024; + const int n_chunks = 2; + + std::vector tensors; + ggml_backend_buffer_ptr buf = alloc_tensors(ctx.get(), mock_buft(), { n_chunks*chunk_size/sizeof(float) }, tensors); + if (!buf) { + return false; + } + + const size_t n_bytes = ggml_nbytes(tensors[0]); + + // leaves untouched bytes at both ends + const size_t offset = 3; + const size_t size = n_bytes - 2*offset; + + std::vector expected(n_bytes, 0), out(n_bytes, 0); + memset(expected.data() + offset, 0xA5, size); + + ggml_backend_tensor_set(tensors[0], out.data(), 0, n_bytes); + + g_mock.set_calls = 0; + ggml_backend_tensor_memset(tensors[0], 0xA5, offset, size); + ggml_backend_tensor_get(tensors[0], out.data(), 0, n_bytes); + + if (out != expected) { + return false; + } + + // the hook writes without set_tensor, the fallback with one set_tensor call per chunk + const int expected_calls = with_hook ? 0 : n_chunks; + if (g_mock.set_calls != expected_calls) { + return false; + } + + return true; +} + static bool test_mock() { return test_mock_set_get_n(true) && test_mock_set_get_n(false) && test_mock_copy_n(true) && test_mock_copy_n(false) && - test_mock_grouping(); + test_mock_grouping() && + test_mock_memset(true) && + test_mock_memset(false); } int main() { From 7778de0c3fe4c4b05857d0abaad6195e470b6515 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Mon, 23 Nov 2026 10:32:56 +0800 Subject: [PATCH 052/401] tests : compare only the guaranteed GDN snapshot slots (#32820) --- tests/test-backend-ops.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 91ff4c86a5f3..ca415adf0950 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -5366,6 +5366,14 @@ struct test_gated_delta_net : public test_case { // lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence const float g_min; + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "GATED_DELTA_NET"; + } + + // compare only the view returned by build_graph, not the full op output + bool run_whole_graph() override { return K > 1 && n_seq_tokens > K; } + std::string vars() override { std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); if (g_min != -20.0f) { @@ -5423,6 +5431,10 @@ struct test_gated_delta_net : public test_case { k = ggml_cpy(ctx, k, k_permuted); } ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); + if (K > 1 && n_seq_tokens > K) { + // n_tokens > K: only slot 0 is guaranteed, so keep the scores and slot 0 + out = ggml_view_2d(ctx, out, out->ne[0], out->ne[1] - (K - 1) * head_size * n_seqs, out->nb[1], 0); + } return out; } From 44d50873b56b568c28ef2ad8d6445069feaa9fbd Mon Sep 17 00:00:00 2001 From: lhez Date: Sun, 22 Nov 2026 18:46:40 -0800 Subject: [PATCH 053/401] opencl: add q4_k coop-k c8 GEMM for spec verify (#32716) * opencl: add q4_k coop-k c8 GEMM for spec verify Co-authored-by: Hongqiang Wang Assisted-by: Codex * opencl: enable q4_k c8 GEMM for n >= 2 for X2 --------- Co-authored-by: Hongqiang Wang --- ggml/src/ggml-opencl/CMakeLists.txt | 1 + ggml/src/ggml-opencl/ggml-opencl.cpp | 249 +++++++++++++++++- .../gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl | 187 +++++++++++++ 3 files changed, 428 insertions(+), 9 deletions(-) create mode 100644 ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index aadf5ddb3321..d71802c0385c 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -226,6 +226,7 @@ set(GGML_OPENCL_KERNELS gemm_noshuffle_q4_0_q8_1_dp4a gemm_coopk_q4_0_q8_1_dp4a gemm_coopk_q4_k_q8_1_dp4a + gemm_coopk_q4_k_q8_1_dp4a_bin_c8 gemm_coopk_q6_k_q8_1_dp4a pack_b_f16_coopmat gemm_noshuffle_q4_0_f32_coopmat diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index d35c6d047167..c2f3b874a29f 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1514,6 +1514,15 @@ struct ggml_backend_opencl_context { cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 = nullptr; int nsg_coopk_dp4a_q4_k_bin_c4 = 8; int nsg_coopk_dp4a_q4_k_bin_c2 = 8; + cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = nullptr; + cl_kernel kernel_quant_a_q8_1_k4 = nullptr; + int nsg_coopk_dp4a_q4_k_bin_c8 = 4; + cl_mem coopk_c8_qa_image = nullptr; + cl_mem coopk_c8_qa_buffer = nullptr; + size_t coopk_c8_qa_image_bytes = 0; + cl_mem coopk_c8_ds_image = nullptr; + cl_mem coopk_c8_ds_buffer = nullptr; + size_t coopk_c8_ds_image_bytes = 0; cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c4 = nullptr; cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr; int nsg_coopk_dp4a_q6_k = 8; @@ -1521,6 +1530,22 @@ struct ggml_backend_opencl_context { #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + for (cl_kernel kernel : { + kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8, + kernel_quant_a_q8_1_k4 + } + ) { + if (kernel != nullptr) { + CL_CHECK(clReleaseKernel(kernel)); + } + } + for (cl_mem image : {coopk_c8_qa_image, coopk_c8_ds_image}) { + if (image != nullptr) { + CL_CHECK(clReleaseMemObject(image)); + } + } +#endif for (cl_kernel kernel : { kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, @@ -1851,13 +1876,22 @@ static bool ggml_cl_coopk_dp4a_narrow_on(const ggml_backend_opencl_context * bac // COOPK_NSG sizes the local reduction buffer, so a smaller workgroup requires a rebuild. static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * backend_ctx, const char * kernel_src, const char * kernel_name, - const std::string & opts_base, int & nsg) { + const std::string & opts_base, int & nsg, bool fatal = true) { while (nsg >= 2) { const std::string opts = opts_base + " -DCOOPK_NSG=" + std::to_string(nsg); - cl_program program = build_program_from_source(backend_ctx, kernel_src, opts); + cl_program program = build_program_from_source(backend_ctx, kernel_src, opts, fatal); + if (program == nullptr) { + return nullptr; + } cl_int err; cl_kernel kernel = clCreateKernel(program, kernel_name, &err); - CL_CHECK(err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + if (fatal) { + CL_CHECK(err); + } + return nullptr; + } size_t max_workgroup_size = 0; CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup_size), &max_workgroup_size, NULL)); @@ -1871,6 +1905,46 @@ static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * back return nullptr; } +static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl"); +#endif + cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), + "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, + backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8, false); + if (program == nullptr) { + return; + } + + cl_int err; + + cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", &err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + return; + } + + cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4", &err); + CL_CHECK(clReleaseProgram(program)); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseKernel(gemm)); + return; + } + + if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { + CL_CHECK(clReleaseKernel(gemm)); + CL_CHECK(clReleaseKernel(quant)); + return; + } + + backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = gemm; + backend_ctx->kernel_quant_a_q8_1_k4 = quant; +} + static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx, const std::string & kernel_src, const char * kernel_name, int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) { @@ -1940,8 +2014,12 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4, backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c2); - const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); - if (use_adreno_bin_kernels(backend_ctx) && (!env || !*env || atoi(env) != 0)) { + static const bool use_coopk_bin = [] { + const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); + return !env || !*env || atoi(env) != 0; + }(); + + if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { const std::string base_opts = backend_ctx->kernel_compile_opts + " -DCOOPK_Q_BIN=1 -DCOOPK_ROWS=" + std::to_string(backend_ctx->rows_coopk_dp4a_q4_k); for (int cols = 4; cols >= 2; cols -= 2) { @@ -1965,6 +2043,7 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx } nsg = nsg_eff; } + load_cl_kernel_coopk_q4_k_bin_c8(backend_ctx); } GGML_LOG_CONT("."); } @@ -28117,6 +28196,69 @@ static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_t } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS +// make sure the image1d_buffer `image` is a proper view of `buffer` by either +// creating a new image1d_buffer or reuse existing one. +// upon success, `image_buffer` is set to the cl_mem in `buffer` and +// `image_bytes` the size in `buffer` and `image` is the image1d_buffer. +static bool ggml_cl_coopk_c8_image( + ggml_backend_opencl_context * backend_ctx, + ggml_cl_buffer & buffer, + size_t bytes, + cl_mem & image, + cl_mem & image_buffer, + size_t & image_bytes +) { + // required bytes exceed image1d_buffer limit + if (bytes / 16 > backend_ctx->image_max_buffer_size) { + return false; + } + // existing image1d_buffer can be reused + if (image != nullptr && image_buffer == buffer.buffer && image_bytes >= bytes) { + return true; + } + // a new one is needed, so release the existing one + if (image != nullptr) { + CL_CHECK(clReleaseMemObject(image)); + image = nullptr; + } + + image_buffer = nullptr; + image_bytes = 0; + + cl_image_format format = {CL_RGBA, CL_UNSIGNED_INT32}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = bytes / 16; + desc.buffer = buffer.buffer; + + cl_int err; + image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + if (err != CL_SUCCESS) { + image = nullptr; + return false; + } + + image_buffer = buffer.buffer; + image_bytes = bytes; + return true; +} + +static int ggml_cl_coopk_ksplit(const ggml_backend_opencl_context * backend_ctx, int base_wg, int n_blocks) { + const int cu = MAX(1, (int) backend_ctx->fa.compute_units); + int ksplit = 1; + float best_eff = 0.0f; + for (int k = 1; k <= MIN(8, n_blocks); ++k) { + const int wg = base_wg * k; + const int waves = CEIL_DIV(wg, cu); + const float eff = (float) wg / (waves * cu); + if (eff > best_eff + 0.06f) { + best_eff = eff; + ksplit = k; + } + } + return ksplit; +} + static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); @@ -28154,11 +28296,100 @@ static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const gg int N = ne1; int K = ne00; + const int coopk_c8_min_n = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 2 : 5; + if (backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 != nullptr && + N >= coopk_c8_min_n && N <= 8 && M > 0 && K > 0 && M % 256 == 0 && K % 256 == 0 && + src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && + K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && + src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && + src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && + ggml_is_contiguous(src1) && ggml_is_contiguous(dst) + ) { + const int kb = K / 32; + const size_t qa_bytes = (size_t)8 * K; + const size_t ds_bytes = (size_t)16 * kb * sizeof(cl_half); + + backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); + backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); + + if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, + backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && + ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, + backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) + ) { + const int n_blocks = N * kb; + + cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); + CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); + + size_t quant_local[] = {64}; + size_t quant_global[] = {(size_t)8 * kb}; + backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); + + int ksplit = ggml_cl_coopk_ksplit(backend_ctx, M / 256, kb); + if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) { + ksplit = 1; + } + + cl_mem out = extrad->data_device; + cl_ulong out_offset = offsetd; + + if (ksplit > 1) { + backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float)); + out = backend_ctx->prealloc_splitk_partial.buffer; + out_offset = 0; + } + + const cl_uchar mask_d6 = 0x3F; + const cl_uchar mask_d4 = 0x0F; + const cl_uchar mask_hi2 = 0xC0; + + const size_t nsg = backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8; + cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8; + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q4_k->q)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(gemm, 12, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(gemm, 13, sizeof(cl_uchar), &mask_hi2)); + CL_CHECK(clSetKernelArg(gemm, 14, sizeof(int), &ksplit)); + + size_t local[] = {64, nsg, 1}; + size_t global[] = {(size_t)M / 4, nsg * ksplit, 1}; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + + if (ksplit > 1) { + const int rows = M * N; + cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); + CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); + size_t reduce_local[] = {64}; + size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64}; + backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); + } + return; + } + } + // CoopK handles with _bin use the bin weight layout (uint-transposed q), with K-major Q8_1 activations (K contiguous). - // This switch disables only this bin-layout path; weight conversion is unchanged. - static const char * env_coopk_bin = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); - const bool use_coopk_bin = !env_coopk_bin || !*env_coopk_bin || atoi(env_coopk_bin) != 0; - if (use_coopk_bin && ne1 >= 2 && ne1 <= 4 && + if (ne1 >= 2 && ne1 <= 4 && ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q4_k) && backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 != nullptr && ((ne1 <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 diff --git a/ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl b/ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl new file mode 100644 index 000000000000..15f79cbe1d91 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl @@ -0,0 +1,187 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#ifndef COOPK_NSG +#define COOPK_NSG 4 +#endif +#define COK_SG 64 +#define COK_ROWS 4 + +#define COK_PACK4(a, b, c, e) \ + (((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) | (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24)) + +// Pack each four K values as (0, 2, 1, 3); scales and sums are interleaved at width eight. +kernel void kernel_quant_a_q8_1_k4( + global const float * src, + global uint * qa, + global half * ds, + ulong offset_src, + int total_blocks, + int k_b +) { + const int blk = get_global_id(0); + if (blk >= 8 * k_b) { + return; + } + const int col = blk / k_b; + const int b = blk % k_b; + if (blk >= total_blocks) { + vstore8((uint8)(0), 0, qa + blk * 8); + ds[(2 * b) * 8 + col] = (half)0; + ds[(2 * b + 1) * 8 + col] = (half)0; + return; + } + src = (global const float *)((global const char *)src + offset_src); + const int base = blk * 32; + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 32; ++i) { + v[i] = src[base + i]; + amax = fmax(amax, fabs(v[i])); + } + const float d = amax / 127.0f; + const float id = amax > 0.0f ? 127.0f / amax : 0.0f; + int q[32]; + int sum = 0; + #pragma unroll + for (int i = 0; i < 32; ++i) { + q[i] = (int)rint(v[i] * id); + sum += q[i]; + } + uint8 out; + out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]); + out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]); + out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]); + out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]); + out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]); + out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]); + out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]); + out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]); + vstore8(out, 0, qa + blk * 8); + ds[(2 * b) * 8 + col] = (half)d; + ds[(2 * b + 1) * 8 + col] = (half)(d * (float)sum); +} + +#define COK_SPREAD(t) (((t) | ((t) << 12)) & 0x0F0F0F0Fu) +#define COK_DOT_RC4(r, c) \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W0.s##r, A.s0, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W1.s##r, A.s1, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W2.s##r, A.s2, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(W3.s##r, A.s3, d##r.s##c); +#define COK_DOT_COL4(c, t) \ + { const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \ + COK_DOT_RC4(0, c) COK_DOT_RC4(1, c) COK_DOT_RC4(2, c) COK_DOT_RC4(3, c) } + +kernel void kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8( + global const uint * src0_q, + global const uchar * src0_s, + global const half * src0_d, + global const half * src0_dm, + read_only image1d_buffer_t src1_qa, + read_only image1d_buffer_t src1_ds, + global float * dst, + ulong offsetd, + int m, + int k, + int n_no_padding, + uchar mask_d6, + uchar mask_d4, + uchar mask_hi2, + int ksplit +) { + dst = (global float *)((global char *)dst + offsetd); + const int gx = get_global_id(0); + const int sg = get_local_id(1); + const int lane = get_local_id(0); + const int ks = get_group_id(1); + const int row0 = gx * COK_ROWS; + const int num_32blk = k / 32; + const int k_t = k >> 4; + const int fence = (int)(mask_d6 >> 6); + const int nslice = ksplit * COOPK_NSG; + const int chunk = (num_32blk + nslice - 1) / nslice; + const int b_beg = (ks * COOPK_NSG + sg) * chunk; + const int b_end = min(b_beg + chunk, num_32blk); + float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f); + float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f); + + for (int sb = b_beg >> 3; sb * 8 < b_end; ++sb) { + const half4 dd = vload4(0, src0_d + row0 + sb * m); + const half4 dmm = vload4(0, src0_dm + row0 + sb * m); + global const uchar * sc = src0_s + sb * 12 * m + row0; + const int j_beg = max(b_beg - sb * 8, 0); + const int j_end = min(b_end - sb * 8, 8); + for (int j = j_beg; j < j_end; ++j) { + const int blk = sb * 8 + j; + int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0); + for (int h = 0; h < 2; ++h) { + const int u0 = (blk << 2) + (h << 1); + const int at = (blk << 1) + h; + const uint4 wa = vload4(0, src0_q + row0 + u0 * m); + const uint4 wb = vload4(0, src0_q + row0 + (u0 + 1) * m); + const uint4 W0 = COK_SPREAD(wa & 0xFFFFu); + const uint4 W1 = COK_SPREAD(wa >> 16); + const uint4 W2 = COK_SPREAD(wb & 0xFFFFu); + const uint4 W3 = COK_SPREAD(wb >> 16); + COK_DOT_COL4(0, at) COK_DOT_COL4(1, at) COK_DOT_COL4(2, at) COK_DOT_COL4(3, at) + // Keep the second activation group dependent on the first dot products. + const int at4 = at + (d0.s0 & fence); + COK_DOT_COL4(4, at4) COK_DOT_COL4(5, at4) COK_DOT_COL4(6, at4) COK_DOT_COL4(7, at4) + } + uchar4 scv, mnv; + if (j < 4) { + scv = vload4(0, sc + j * m) & (uchar4)(mask_d6); + mnv = vload4(0, sc + (j + 4) * m) & (uchar4)(mask_d6); + } else { + const uchar4 bh = vload4(0, sc + (j + 4) * m); + const uchar4 bl = vload4(0, sc + (j - 4) * m); + const uchar4 bj = vload4(0, sc + j * m); + scv = (bh & (uchar4)(mask_d4)) | ((bl >> (uchar4)(6)) << (uchar4)(4)); + mnv = (bh >> (uchar4)(4)) | ((bj >> (uchar4)(6)) << (uchar4)(4)); + } + const float4 scf = convert_float4(dd) * convert_float4(scv); + const float4 mnf = convert_float4(dmm) * convert_float4(mnv); + const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk))); + acc0 = mad(convert_float8(d0), da * scf.s0, acc0); + acc1 = mad(convert_float8(d1), da * scf.s1, acc1); + acc2 = mad(convert_float8(d2), da * scf.s2, acc2); + acc3 = mad(convert_float8(d3), da * scf.s3, acc3); + const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 2 * blk + 1))); + acc0 = mad(sa, -mnf.s0, acc0); + acc1 = mad(sa, -mnf.s1, acc1); + acc2 = mad(sa, -mnf.s2, acc2); + acc3 = mad(sa, -mnf.s3, acc3); + } + } + + local float8 reduceLM[COK_SG * (COOPK_NSG - 1)]; + float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f); + float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f); +#define COK_REDUCE(accv, outv) \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg == 0) { \ + float8 sum = (accv); \ + for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \ + (outv) = sum; \ + } + COK_REDUCE(acc0, out0) + COK_REDUCE(acc1, out1) + COK_REDUCE(acc2, out2) + COK_REDUCE(acc3, out3) +#undef COK_REDUCE +#define COK_STORE_COL(c) \ + if ((c) < n_no_padding) { \ + vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \ + } + if (sg == 0) { + dst += (size_t)ks * (size_t)m * (size_t)n_no_padding; + COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3) + COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7) + } +#undef COK_STORE_COL +} From 1f8baae28d096624bd47d33d2d179ec479d47720 Mon Sep 17 00:00:00 2001 From: lhez Date: Sun, 22 Nov 2026 22:26:55 -0800 Subject: [PATCH 054/401] opencl: add xielu (#32791) Assisted-by: Codex --- docs/ops.md | 2 +- docs/ops/OpenCL.csv | 8 +-- ggml/src/ggml-opencl/ggml-opencl.cpp | 63 +++++++++++++++++++++++ ggml/src/ggml-opencl/kernels/unary_ext.cl | 26 ++++++++++ 4 files changed, 94 insertions(+), 5 deletions(-) diff --git a/docs/ops.md b/docs/ops.md index 88e92c701d10..855bf1cff83e 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -133,4 +133,4 @@ Legend: | TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | -| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | +| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | diff --git a/docs/ops/OpenCL.csv b/docs/ops/OpenCL.csv index e5f2bbd0cf00..bee117961fc8 100644 --- a/docs/ops/OpenCL.csv +++ b/docs/ops/OpenCL.csv @@ -16812,11 +16812,11 @@ "OpenCL","CUMSUM","type=f32,ne=[242004,1,1,1]","support","1","yes","OpenCL" "OpenCL","CUMSUM","type=f32,ne=[375960,1,1,1]","support","1","yes","OpenCL" "OpenCL","CUMSUM","type=f32,ne=[20481,4,1,1]","support","1","yes","OpenCL" -"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL" -"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","XIELU","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL" +"OpenCL","XIELU","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","XIELU","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL" -"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","0","no","OpenCL" -"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","0","no","OpenCL" +"OpenCL","XIELU","type=f32,ne=[512,16,1,1]","support","1","yes","OpenCL" +"OpenCL","XIELU","type=f16,ne=[512,16,1,1]","support","1","yes","OpenCL" "OpenCL","XIELU","type=bf16,ne=[512,16,1,1]","support","0","no","OpenCL" "OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=3","support","1","yes","OpenCL" "OpenCL","TRI","type=f32,ne=[10,10,4,3],tri_type=2","support","1","yes","OpenCL" diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index c2f3b874a29f..05a05fe9f95f 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1163,6 +1163,8 @@ struct ggml_backend_opencl_context { cl_kernel kernel_sgn_f32, kernel_sgn_f32_4, kernel_sgn_f32_nc, kernel_sgn_f16, kernel_sgn_f16_4, kernel_sgn_f16_nc; cl_kernel kernel_step_f32, kernel_step_f32_4, kernel_step_f32_nc, kernel_step_f16, kernel_step_f16_4, kernel_step_f16_nc; cl_kernel kernel_elu_f32, kernel_elu_f32_4, kernel_elu_f32_nc, kernel_elu_f16, kernel_elu_f16_4, kernel_elu_f16_nc; + cl_kernel kernel_xielu_f32 = nullptr; + cl_kernel kernel_xielu_f16 = nullptr; cl_kernel kernel_hardswish_f32, kernel_hardswish_f32_4, kernel_hardswish_f32_nc, kernel_hardswish_f16, kernel_hardswish_f16_4, kernel_hardswish_f16_nc; cl_kernel kernel_hardsigmoid_f32, kernel_hardsigmoid_f32_4, kernel_hardsigmoid_f32_nc, kernel_hardsigmoid_f16, kernel_hardsigmoid_f16_4, kernel_hardsigmoid_f16_nc; cl_kernel kernel_floor_f32, kernel_floor_f32_4, kernel_floor_f32_nc, kernel_floor_f16, kernel_floor_f16_4, kernel_floor_f16_nc; @@ -1547,6 +1549,8 @@ struct ggml_backend_opencl_context { } #endif for (cl_kernel kernel : { + kernel_xielu_f32, + kernel_xielu_f16, kernel_mul_mm_f16_f32_kq_p8, kernel_mul_mm_q8_f32_kqv, kernel_fa_p8_fixup, @@ -4918,6 +4922,8 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { CL_UNARY_EXT_K(round) CL_UNARY_EXT_K(trunc) #undef CL_UNARY_EXT_K + CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err)); + CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err)); CL_CHECK(clReleaseProgram(prog)); GGML_LOG_CONT("."); } @@ -12286,6 +12292,14 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te case GGML_UNARY_OP_SILU: return op->src[0]->type == op->type && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); + case GGML_UNARY_OP_XIELU: + for (int64_t ne : op->src[0]->ne) { + if (ne > INT_MAX) { + return false; + } + } + return op->src[0]->type == op->type && + (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); case GGML_UNARY_OP_GELU: case GGML_UNARY_OP_RELU: case GGML_UNARY_OP_GELU_ERF: @@ -21318,6 +21332,51 @@ GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc) #undef GGML_CL_UNARY_EXT_WRAP +static void ggml_cl_xielu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + UNUSED(src1); + + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + cl_kernel kernel = src0->type == GGML_TYPE_F16 ? backend_ctx->kernel_xielu_f16 : backend_ctx->kernel_xielu_f32; + + const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; + const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + const float alpha_n = ggml_get_op_params_f32(dst, 1); + const float alpha_p = ggml_get_op_params_f32(dst, 2); + const float beta = ggml_get_op_params_f32(dst, 3); + const float eps = ggml_get_op_params_f32(dst, 4); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha_n)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &alpha_p)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &beta)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &eps)); + + const size_t nth = 64; + size_t global[] = {(size_t) ne01*nth, (size_t) ne02, (size_t) ne03}; + size_t local[] = {nth, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); +} + static void ggml_cl_softplus(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { GGML_ASSERT(src0); GGML_ASSERT(src0->extra); @@ -40747,6 +40806,10 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor if (!any_on_device) { return false; } func = ggml_cl_elu; break; + case GGML_UNARY_OP_XIELU: + if (!any_on_device) { return false; } + func = ggml_cl_xielu; + break; case GGML_UNARY_OP_HARDSWISH: if (!any_on_device) { return false; } func = ggml_cl_hardswish; diff --git a/ggml/src/ggml-opencl/kernels/unary_ext.cl b/ggml/src/ggml-opencl/kernels/unary_ext.cl index e86eadfa5f5c..e58cc0153ff1 100644 --- a/ggml/src/ggml-opencl/kernels/unary_ext.cl +++ b/ggml/src/ggml-opencl/kernels/unary_ext.cl @@ -83,3 +83,29 @@ UNARY_EXT(floor, floor(x), floor UNARY_EXT(ceil, ceil(x), ceil(x)) UNARY_EXT(round, round(x), round(x)) UNARY_EXT(trunc, trunc(x), trunc(x)) + +// xielu has more args, cannot fit in UNARY_EXT +inline float xielu(float x, float alpha_n, float alpha_p, float beta, float eps) { + return x > 0.0f ? alpha_p*x*x + beta*x : (expm1(fmin(x, eps)) - x)*alpha_n + beta*x; +} + +#define XIELU_KERNEL(NAME, TYPE) \ +kernel void kernel_xielu_##NAME( \ + global const char * src0, ulong offset0, \ + global char * dst, ulong offsetd, \ + int ne00, ulong nb00, ulong nb01, ulong nb02, ulong nb03, \ + ulong nb0, ulong nb1, ulong nb2, ulong nb3, \ + float alpha_n, float alpha_p, float beta, float eps) { \ + const size_t i3 = get_group_id(2); \ + const size_t i2 = get_group_id(1); \ + const size_t i1 = get_group_id(0); \ + src0 += offset0 + i3*nb03 + i2*nb02 + i1*nb01; \ + dst += offsetd + i3*nb3 + i2*nb2 + i1*nb1; \ + for (size_t i0 = get_local_id(0); i0 < (size_t) ne00; i0 += get_local_size(0)) { \ + const float x = *(global const TYPE *)(src0 + i0*nb00); \ + *(global TYPE *)(dst + i0*nb0) = xielu(x, alpha_n, alpha_p, beta, eps); \ + } \ +} + +XIELU_KERNEL(f32, float) +XIELU_KERNEL(f16, half) From dd53f70d089f8b57db9d9e4f44f3201a16668637 Mon Sep 17 00:00:00 2001 From: Aldehir Rojas Date: Mon, 23 Nov 2026 01:54:42 -0600 Subject: [PATCH 055/401] chat : improve inkling parser/grammar (#32833) --- common/parsers/inkling.cpp | 74 +++++++++++++++++++------------------- tests/test-chat.cpp | 41 ++++++++++++++++----- 2 files changed, 68 insertions(+), 47 deletions(-) diff --git a/common/parsers/inkling.cpp b/common/parsers/inkling.cpp index 9c30cdb87962..082bd86fdfd2 100644 --- a/common/parsers/inkling.cpp +++ b/common/parsers/inkling.cpp @@ -100,18 +100,18 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & auto use_tools = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE; auto extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE; - data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) { - auto header = p.literal(HEADER); - auto end = p.literal(END); + data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) { + auto header = p.token(HEADER); + auto end = p.token(END); - auto think = p.literal(THINK); - auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end : - p.atomic(p.content(think)) + p.content(p.until(END) + end)); - auto text = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end); + auto think = p.token(THINK); + auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(end)) + end : + p.atomic(p.content(think)) + p.content(p.until(end) + end)); + auto text = p.rule("text", p.token(TEXT) + p.content(p.until(end)) + end); if (has_response_format) { auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema))); - return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end; + return p.zero_or_more(header + thinking) + header + p.token(TEXT) + response_format + end; } auto blocks = p.zero_or_more(header + (thinking | text)); @@ -120,45 +120,43 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template & return blocks; } - auto tool_choice = p.choice(); - foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { - const auto & function = tool.at("function"); - std::string name = function.at("name"); - - auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":"); - auto args = p.tool_args(p.json()); - - tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end)); - }); - - // tool calls are the last blocks of the turn - auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice; - auto tool_calls = header + p.trigger_rule("tool-calls", calls); + // the call takes the name in the JSON + auto tool_json = p.token(TOOL_JSON); + auto tool_body = [&](const common_peg_parser & json_name) { + return p.tool_open(p.literal("{")) << p.json_member("name", p.literal("\"") + p.tool_name(json_name) + p.literal("\"")) << p.literal(",") + << p.json_member("args", p.tool_args(p.json())) << p.tool_close(p.literal("}")) + end; + }; if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) { - return blocks + tool_calls; + auto tool_choice = p.choice(); + foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) { + const auto & function = tool.at("function"); + std::string name = function.at("name"); + std::string quoted = json(name).dump(); + + // The research model does not generate a tool name before the tool call token + auto json_name = p.literal(quoted.substr(1, quoted.size() - 2)); + tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name))); + }); + + auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice; + return blocks + header + calls; } - return blocks + p.optional(tool_calls); + auto name = p.until(tool_json); + auto body = tool_body(p.string_content('"')); + auto next = p.rule("tool-call", header + p.tool(name + tool_json + body)); + auto more = inputs.parallel_tool_calls ? p.zero_or_more(next) : p.eps(); + auto calls = header + name + p.trigger_rule("tool-calls", tool_json, body + more); + + return blocks + p.optional(calls); }); if (has_response_format || use_tools) { - data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED; + data.grammar_lazy = false; data.grammar = build_grammar([&](const common_grammar_builder & builder) { - data.parser.build_grammar(builder, data.grammar_lazy); + data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO); }); - - if (data.grammar_lazy) { - // a header followed by text and not by a content token is a tool call, the grammar starts at the name - data.grammar_triggers = { - { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" }, - }; - // Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt. - // an output that starts with no content token is a tool call. not for a continuation, it starts with text - if (!inputs.has_continuation()) { - data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" }); - } - } } return data; diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp index 341e7acebd9d..20a3cc6a0747 100644 --- a/tests/test-chat.cpp +++ b/tests/test-chat.cpp @@ -5653,6 +5653,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) { for (const int version : { 1, 2 }) { auto tst = peg_tester(version == 1 ? "models/templates/thinkingmachines-Inkling.jinja" : "models/templates/thinkingmachines-Inkling-2-Small.jinja", detailed_debug); + tst.specials({ "<|message_model|>", "<|content_thinking|>", "<|content_text|>", "<|content_invoke_tool_json|>", "<|end_message|>" }); // Inkling 1 has the first header in the generation prompt, Inkling 2 writes it const std::string H = "<|message_model|>"; @@ -5693,7 +5694,8 @@ static void test_template_output_peg_parsers(bool detailed_debug) { .expect_tool_calls({ { "special_function", R"({"arg1":1})", "" }, }) - .expect_rules({ "tool-0" }) + .expect_rules({ "tool-calls" }) + .expect_grammar() .run(); // Thinking, content, then a tool call @@ -5721,20 +5723,41 @@ static void test_template_output_peg_parsers(bool detailed_debug) { }) .run(); - // The block closer inside a string argument does not end the block - tst.test(P + "python<|content_invoke_tool_json|>{\"name\":\"python\",\"args\":{\"code\":\"print('<|end_message|>')\"}}" + E) - .tools({ python_tool }) - .expect_tool_calls({ - { "python", R"JSON({"code":"print('<|end_message|>')"})JSON", "" }, - }) - .run(); - // Forced tool call tst.test(P + "<|content_thinking|>I should call it" + E + H + CALL) .reasoning_format(COMMON_REASONING_FORMAT_AUTO) .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED) .tools({ special_function_tool }) .expect(simple_assist_msg("", "I should call it", "special_function", R"({"arg1":1})", "")) + .expect_rules({ "tool-0" }) + .expect_grammar() + .run(); + + // The research model does not write the name before the tool token + for (const auto tool_choice : { COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED }) { + tst.test(P + "<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E) + .tool_choice(tool_choice) + .tools({ special_function_tool }) + .expect_tool_calls({ + { "special_function", R"({"arg1":1})", "" }, + }) + .run(); + } + + // A tool that is not in the list, with spaces in the JSON + tst.test(P + "unknown_tool<|content_invoke_tool_json|>{\"name\": \"unknown_tool\", \"args\": {\"arg1\": 1}}" + E) + .tools({ special_function_tool }) + .expect_tool_calls({ + { "unknown_tool", R"({"arg1": 1})", "" }, + }) + .run(); + + // The call takes the name in the JSON, not the one before the tool token + tst.test(P + "special<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E) + .tools({ special_function_tool }) + .expect_tool_calls({ + { "special_function", R"({"arg1":1})", "" }, + }) .run(); // Response format From f5e6915c28f10330885fcb9243a93ae98d3115ab Mon Sep 17 00:00:00 2001 From: Leon <3077740163@qq.com> Date: Mon, 23 Nov 2026 15:56:54 +0800 Subject: [PATCH 056/401] webgpu : add ROLL support (#31887) * webgpu : add ROLL support * tests : keep ROLL cases portable across backends --- docs/ops.md | 2 +- docs/ops/WebGPU.csv | 8 ++++++- .../ggml-webgpu/ggml-webgpu-shader-lib.hpp | 2 +- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 22 +++++++++++-------- tests/test-backend-ops.cpp | 19 +++++++++++----- 5 files changed, 36 insertions(+), 17 deletions(-) diff --git a/docs/ops.md b/docs/ops.md index 855bf1cff83e..6c226e150020 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -97,7 +97,7 @@ Legend: | REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | -| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | | ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | | ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 2ad8ded659ec..8e09ddaf3de0 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -12345,7 +12345,13 @@ "WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[257,7,1,1],pad_0=0,pad_1=256,view=0","support","1","yes","WebGPU" "WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[2,16777217,1,1],pad_0=1,pad_1=1,view=0","support","1","yes","WebGPU" "WebGPU: WebGPU","PAD_REFLECT_1D","type=f32,ne_a=[3000,384,4,1],pad_0=10,pad_1=9,view=0","support","1","yes","WebGPU" -"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1","support","0","no","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=0,ne_a=[10,5,4,3]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=3,shift1=-2,shift3=1,shift4=-1,permute=1,ne_a=[10,5,4,3]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=0,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[1,1,1,1]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=256,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[257,1,1,1]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=-16,shift1=6,shift3=-2,shift4=1,permute=0,ne_a=[17,7,3,2]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[42,512,1,1]","support","1","yes","WebGPU" +"WebGPU: WebGPU","ROLL","shift0=4,shift1=0,shift3=0,shift4=0,permute=0,ne_a=[380,512,1,1]","support","1","yes","WebGPU" "WebGPU: WebGPU","ARANGE","type=f32,start=0.000000,stop=10.000000,step=1.000000","support","1","yes","WebGPU" "WebGPU: WebGPU","ARANGE","type=f32,start=3.000000,stop=3.500000,step=1.000000","support","1","yes","WebGPU" "WebGPU: WebGPU","ARANGE","type=f32,start=-10.000000,stop=10.000000,step=0.300000","support","1","yes","WebGPU" diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index cc7f660ef8e4..8896efb5af4a 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -2117,7 +2117,7 @@ class ggml_webgpu_shader_lib { webgpu_pipeline get_pad_pipeline(const ggml_webgpu_shader_lib_context & context) { ggml_webgpu_pad_pipeline_key key = {}; key.reflect = context.dst->op == GGML_OP_PAD_REFLECT_1D; - key.circular = !key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0; + key.circular = context.dst->op == GGML_OP_ROLL || (!key.reflect && ggml_get_op_params_i32(context.dst, 8) != 0); auto it = pad_pipelines.find(key); if (it != pad_pipelines.end()) { diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 886760849796..b857f4927764 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -964,16 +964,18 @@ static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src (uint32_t) dst->ne[1], (uint32_t) dst->ne[2], (uint32_t) dst->ne[3], - // Pad sizes - (uint32_t) ggml_get_op_params_i32(dst, 0), - (uint32_t) ggml_get_op_params_i32(dst, 1), - (uint32_t) ggml_get_op_params_i32(dst, 2), - (uint32_t) ggml_get_op_params_i32(dst, 3), - (uint32_t) ggml_get_op_params_i32(dst, 4), - (uint32_t) ggml_get_op_params_i32(dst, 5), - (uint32_t) ggml_get_op_params_i32(dst, 6), - (uint32_t) ggml_get_op_params_i32(dst, 7), }; + for (int i = 0; i < 4; i++) { + if (dst->op == GGML_OP_ROLL) { + // Circular padding with unchanged dimensions implements a roll. + const int64_t shift = ggml_get_op_params_i32(dst, i); + params.push_back((uint32_t) (shift < 0 ? shift + src->ne[i] : shift)); + params.push_back(0); + } else { + params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i)); + params.push_back((uint32_t) ggml_get_op_params_i32(dst, 2 * i + 1)); + } + } std::vector entries = { ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), @@ -3740,6 +3742,7 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, return ggml_webgpu_pool2d(ctx, src0, node); case GGML_OP_COL2IM_1D: return ggml_webgpu_col2im_1d(ctx, src0, node); + case GGML_OP_ROLL: case GGML_OP_PAD_REFLECT_1D: case GGML_OP_PAD: return ggml_webgpu_pad(ctx, src0, node); @@ -5299,6 +5302,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const case GGML_OP_PAD_REFLECT_1D: supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32; break; + case GGML_OP_ROLL: case GGML_OP_PAD: supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32; break; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index ca415adf0950..53961f776ef1 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9087,17 +9087,18 @@ struct test_roll : public test_case { const int shift3; const int shift4; const bool permute; + const std::array ne_a; std::string vars() override { - return VARS_TO_STR5(shift0, shift1, shift3, shift4, permute); + return VARS_TO_STR6(shift0, shift1, shift3, shift4, permute, ne_a); } - test_roll(int shift0 = 3, int shift1 = -2, int shift3 = 1, int shift4 = -1, bool permute = false) - : shift0(shift0), shift1(shift1), shift3(shift3), shift4(shift4), permute(permute) {} + test_roll(int shift0 = 3, int shift1 = -2, int shift3 = 1, int shift4 = -1, bool permute = false, + std::array ne_a = {10, 5, 4, 3}) + : shift0(shift0), shift1(shift1), shift3(shift3), shift4(shift4), permute(permute), ne_a(ne_a) {} ggml_tensor * build_graph(ggml_context * ctx) override { - int64_t ne[4] = {10, 5, 4, 3}; - ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne); + ggml_tensor * a = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne_a.data()); ggml_set_name(a, "a"); if (permute) { @@ -13183,6 +13184,11 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_pad_reflect_1d(GGML_TYPE_F32, {3000, 384, 4, 1})); test_cases.emplace_back(new test_roll()); test_cases.emplace_back(new test_roll(3, -2, 1, -1, true)); + test_cases.emplace_back(new test_roll(0, 0, 0, 0, false, {1, 1, 1, 1})); + test_cases.emplace_back(new test_roll(256, 0, 0, 0, false, {257, 1, 1, 1})); + test_cases.emplace_back(new test_roll(-16, 6, -2, 1, false, {17, 7, 3, 2})); + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {42, 512, 1, 1})); + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {380, 512, 1, 1})); test_cases.emplace_back(new test_arange()); test_cases.emplace_back(new test_arange(GGML_TYPE_F32, 3.0f, 3.5f, 1.0f)); test_cases.emplace_back(new test_arange(GGML_TYPE_F32, -10.0f, 10.0f, 0.3f)); @@ -13916,6 +13922,9 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_arange(GGML_TYPE_F32, 0.0f, n, 1.0f)); } + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {42, 512, 1, 1})); + test_cases.emplace_back(new test_roll(4, 0, 0, 0, false, {380, 512, 1, 1})); + // embedding lookups: one token (decode) and one batch of 2048 tokens (prefill) for (int r : {16, 32768}) { test_cases.emplace_back(new test_get_rows(GGML_TYPE_F8_E4M3, 160, 2000000, r, 1, 1, false)); // Qwen4-Exp n-gram table, 16 rows per token From 212c547fe908b288f6659d48741e6ffac1ff409c Mon Sep 17 00:00:00 2001 From: Wenyu Chen Date: Mon, 23 Nov 2026 03:27:44 -0500 Subject: [PATCH 057/401] ui: add cancel button to cancel model loading (#32225) --- .../app/models/ModelLoadControl.svelte | 24 ++++++++++++++++++- .../chat/src/lib/constants/icons.constants.ts | 2 ++ .../src/lib/stores/models/status.svelte.ts | 19 ++++++++++++--- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte index 0607ddcedcc2..454b9f2c4b82 100644 --- a/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte +++ b/ui/apps/chat/src/lib/components/app/models/ModelLoadControl.svelte @@ -31,7 +31,29 @@
{#if isLoading} - + + +
+ modelsStore.status.cancelLoad(option.model)} + stopPropagationOnClick + tooltip="Cancel loading model" + tooltipAsTitle + /> +
{:else} {#if showAction && revealOnHover} diff --git a/ui/apps/chat/src/lib/constants/icons.constants.ts b/ui/apps/chat/src/lib/constants/icons.constants.ts index c096e9a69285..c61000967523 100644 --- a/ui/apps/chat/src/lib/constants/icons.constants.ts +++ b/ui/apps/chat/src/lib/constants/icons.constants.ts @@ -22,6 +22,7 @@ import LoadIcon from '@lucide/svelte/icons/power'; import RetryIcon from '@lucide/svelte/icons/rotate-cw'; import PromptCommandIcon from '@lucide/svelte/icons/sparkles'; import VideoIcon from '@lucide/svelte/icons/video'; +import CancelLoadIcon from '@lucide/svelte/icons/x'; import { ChatFormCommandAction, FileTypeCategory, ModelCapability } from '#lib/enums/index.ts'; import type { ModelCapabilities } from '#lib/types/models.js'; import type { Component } from 'svelte'; @@ -80,6 +81,7 @@ export const MODEL_DOWNLOAD_ICONS = { /** Icons the model load control shows for its states and actions. */ export const MODEL_LOAD_ICONS = { + cancel: CancelLoadIcon, failed: LoadFailedIcon, load: LoadIcon, loading: LoadingIcon, diff --git a/ui/apps/chat/src/lib/stores/models/status.svelte.ts b/ui/apps/chat/src/lib/stores/models/status.svelte.ts index ade2b701a881..01d36e96cda9 100644 --- a/ui/apps/chat/src/lib/stores/models/status.svelte.ts +++ b/ui/apps/chat/src/lib/stores/models/status.svelte.ts @@ -152,6 +152,8 @@ export class ModelStatusManager { private listedSidecarsByRepo = $derived.by(() => ModelsService.draftSidecarsByRepo(this.host.routerModels) ); + /** Models whose load the user cancelled; the failure the force-kill triggers is intentional, not a load failure. */ + private loadCancelRequests = new SvelteSet(); private loadingStates = new SvelteMap(); private loadProgress = new SvelteMap(); /** Paused downloads with their last reported progress, or null when none arrived before the pause. */ @@ -198,8 +200,8 @@ export class ModelStatusManager { }); // /models/sse feed state, the single source of truth for status and load progress private statusAbort: AbortController | null = null; - private statusReaderActive = false; + private statusReaderActive = false; private statusWaiters = new SvelteMap< string, { target: ServerModelStatus; resolve: () => void; reject: (e: Error) => void }[] @@ -269,10 +271,15 @@ export class ModelStatusManager { this.subscribe(); + // mark before the kill: the feed can report the child's death before + // this request returns, and load() must not toast it as a failure + this.loadCancelRequests.add(modelId); + try { await ModelsService.unload(modelId); toast.info(`Load cancelled: ${this.host.toDisplayName(modelId)}`); } catch (error) { + this.loadCancelRequests.delete(modelId); toast.error(`Failed to cancel load: ${this.host.toDisplayName(modelId)}`); throw error; @@ -516,11 +523,17 @@ export class ModelStatusManager { toast.success(`Model loaded: ${this.host.toDisplayName(modelId)}`); } catch (error) { this.rejectStatus(modelId, error instanceof Error ? error : new Error('load failed')); - this.host.error = error instanceof Error ? error.message : 'Failed to load model'; - toast.error(`Failed to load model: ${this.host.toDisplayName(modelId)}`); + + // a user cancel force-kills the child, which settles this waiter as a + // failure; cancelLoad already reported the cancel, so stay silent + if (!this.loadCancelRequests.delete(modelId)) { + this.host.error = error instanceof Error ? error.message : 'Failed to load model'; + toast.error(`Failed to load model: ${this.host.toDisplayName(modelId)}`); + } throw error; } finally { + this.loadCancelRequests.delete(modelId); this.loadingStates.set(modelId, false); } } From 7d9b931df9bb7c689f067a7fed23e7f5253951f6 Mon Sep 17 00:00:00 2001 From: Daniel Bevenius Date: Mon, 23 Nov 2026 11:05:21 +0100 Subject: [PATCH 058/401] ggml : update cmake MATH_LIBRARY check (#32864) This commit updates the cmake check for `MATH_LIBRARY` and removes the DEFINED operator for the if() command. The motivation for this is that on windows if a parent project of ggml calls find_library(MATH_LIBRARY) this could return `MATH_LIBRARY-NOTFOUND` which will cause the if clause to be true. Removing the DEFINED operator will work as intended will evaluate to false, as specified by cmake if command docs: ```console False if the constant is 0, OFF, NO, FALSE, N, IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND. ``` This commit was originally opened in a PR against whisper.cpp, see link below. Refs: https://github.com/ggml-org/whisper.cpp/pull/4168 Refs: https://cmake.org/cmake/help/latest/command/if.html#constant --- ggml/src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/CMakeLists.txt b/ggml/src/CMakeLists.txt index eee1a460d16b..74ddb51ca88e 100644 --- a/ggml/src/CMakeLists.txt +++ b/ggml/src/CMakeLists.txt @@ -621,7 +621,7 @@ endforeach() target_link_libraries(ggml-base PRIVATE Threads::Threads) -if (DEFINED MATH_LIBRARY) +if (MATH_LIBRARY) target_link_libraries(ggml-base PRIVATE ${MATH_LIBRARY}) elseif (NOT WIN32 AND NOT DEFINED ENV{ONEAPI_ROOT}) target_link_libraries(ggml-base PRIVATE m) From a8f8294c45076538f4509754e4c79fc51a1a486b Mon Sep 17 00:00:00 2001 From: Vladislav Merkulov <150796351+merkulovlad@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:45:31 +0300 Subject: [PATCH 059/401] tests : update Qwen3.6-27B snapshot (#32845) --- tests/snapshots/qwen3.6-27b.schema | 1928 +++++++++++++--------------- 1 file changed, 916 insertions(+), 1012 deletions(-) diff --git a/tests/snapshots/qwen3.6-27b.schema b/tests/snapshots/qwen3.6-27b.schema index 40802053364b..f36752ffcd8c 100644 --- a/tests/snapshots/qwen3.6-27b.schema +++ b/tests/snapshots/qwen3.6-27b.schema @@ -1,4 +1,4 @@ -# Model: Qwen3.5-27B +# Model: Qwen3.6-27B # n_embd=5120, n_ff=17408, n_vocab=248320, n_layer=64, n_head=24, n_head_kv=4 [F32] f32 @@ -21,146 +21,146 @@ output.weight q6_K [Q2_K] q2_K output.weight q6_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q3_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q3_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q3_K blk.3.attn_output.weight q3_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q3_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q3_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q3_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q3_K blk.7.attn_output.weight q3_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q3_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_down.weight q3_K -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_down.weight q3_K -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_down.weight q3_K blk.11.attn_output.weight q3_K blk.11.attn_v.weight q4_K blk.11.ffn_down.weight q3_K -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_down.weight q3_K -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_down.weight q3_K -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_down.weight q3_K blk.15.attn_output.weight q3_K blk.15.attn_v.weight q4_K blk.15.ffn_down.weight q3_K -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_down.weight q3_K -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_down.weight q3_K -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_down.weight q3_K blk.19.attn_output.weight q3_K blk.19.attn_v.weight q4_K blk.19.ffn_down.weight q3_K -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_down.weight q3_K -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_down.weight q3_K -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_down.weight q3_K blk.23.attn_output.weight q3_K blk.23.attn_v.weight q4_K blk.23.ffn_down.weight q3_K -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_down.weight q3_K -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_down.weight q3_K -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_down.weight q3_K blk.27.attn_output.weight q3_K blk.27.attn_v.weight q4_K blk.27.ffn_down.weight q3_K -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_down.weight q3_K -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_down.weight q3_K -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_down.weight q3_K blk.31.attn_output.weight q3_K blk.31.attn_v.weight q4_K blk.31.ffn_down.weight q3_K -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_down.weight q3_K -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_down.weight q3_K -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_down.weight q3_K blk.35.attn_output.weight q3_K blk.35.attn_v.weight q4_K blk.35.ffn_down.weight q3_K -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_down.weight q3_K -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_down.weight q3_K -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_down.weight q3_K blk.39.attn_output.weight q3_K blk.39.attn_v.weight q4_K blk.39.ffn_down.weight q3_K -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_down.weight q3_K -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_down.weight q3_K -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_down.weight q3_K blk.43.attn_output.weight q3_K blk.43.attn_v.weight q4_K blk.43.ffn_down.weight q3_K -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_down.weight q3_K -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_down.weight q3_K -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_down.weight q3_K blk.47.attn_output.weight q3_K blk.47.attn_v.weight q4_K blk.47.ffn_down.weight q3_K -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_down.weight q3_K -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_down.weight q3_K -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_down.weight q3_K blk.51.attn_output.weight q3_K blk.51.attn_v.weight q4_K blk.51.ffn_down.weight q3_K -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_down.weight q3_K -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_down.weight q3_K -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_down.weight q3_K blk.55.attn_output.weight q3_K blk.55.attn_v.weight q4_K blk.55.ffn_down.weight q3_K -blk.56.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K blk.56.ffn_down.weight q3_K -blk.57.attn_qkv.weight q4_K +blk.57.attn_qkv_gate.weight q4_K blk.57.ffn_down.weight q3_K -blk.58.attn_qkv.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.58.ffn_down.weight q3_K blk.59.attn_output.weight q3_K blk.59.attn_v.weight q4_K blk.59.ffn_down.weight q3_K -blk.60.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K blk.60.ffn_down.weight q3_K -blk.61.attn_qkv.weight q4_K +blk.61.attn_qkv_gate.weight q4_K blk.61.ffn_down.weight q3_K -blk.62.attn_qkv.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.62.ffn_down.weight q3_K blk.63.attn_output.weight q3_K blk.63.attn_v.weight q4_K @@ -171,146 +171,146 @@ output.weight q6_K [Q3_K_M] q3_K output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q5_K blk.3.attn_output.weight q4_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_output.weight q4_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_down.weight q4_K -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_down.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_down.weight q4_K blk.11.attn_output.weight q4_K blk.11.attn_v.weight q4_K blk.11.ffn_down.weight q4_K -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_down.weight q4_K -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_down.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_down.weight q4_K blk.15.attn_output.weight q4_K blk.15.attn_v.weight q4_K blk.15.ffn_down.weight q4_K -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_down.weight q4_K -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_down.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_down.weight q4_K blk.19.attn_output.weight q4_K blk.19.attn_v.weight q4_K blk.19.ffn_down.weight q4_K -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_down.weight q4_K -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_down.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_down.weight q4_K blk.23.attn_output.weight q4_K blk.23.attn_v.weight q4_K blk.23.ffn_down.weight q4_K -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_down.weight q4_K -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_down.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_down.weight q4_K blk.27.attn_output.weight q4_K blk.27.attn_v.weight q4_K blk.27.ffn_down.weight q4_K -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_down.weight q4_K -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_down.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_down.weight q4_K blk.31.attn_output.weight q4_K blk.31.attn_v.weight q4_K blk.31.ffn_down.weight q4_K -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_down.weight q4_K -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_down.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_down.weight q4_K blk.35.attn_output.weight q4_K blk.35.attn_v.weight q4_K blk.35.ffn_down.weight q4_K -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_down.weight q4_K -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_down.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_down.weight q4_K blk.39.attn_output.weight q4_K blk.39.attn_v.weight q4_K blk.39.ffn_down.weight q4_K -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_down.weight q4_K -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_down.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_down.weight q4_K blk.43.attn_output.weight q4_K blk.43.attn_v.weight q4_K blk.43.ffn_down.weight q4_K -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_down.weight q4_K -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_down.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_down.weight q4_K blk.47.attn_output.weight q4_K blk.47.attn_v.weight q4_K blk.47.ffn_down.weight q4_K -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_down.weight q4_K -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_down.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_down.weight q4_K blk.51.attn_output.weight q4_K blk.51.attn_v.weight q4_K blk.51.ffn_down.weight q4_K -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_down.weight q4_K -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_down.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_down.weight q4_K blk.55.attn_output.weight q4_K blk.55.attn_v.weight q4_K blk.55.ffn_down.weight q4_K -blk.56.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K blk.56.ffn_down.weight q4_K -blk.57.attn_qkv.weight q4_K +blk.57.attn_qkv_gate.weight q4_K blk.57.ffn_down.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.58.ffn_down.weight q4_K blk.59.attn_output.weight q4_K blk.59.attn_v.weight q4_K blk.59.ffn_down.weight q4_K -blk.60.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K blk.60.ffn_down.weight q4_K -blk.61.attn_qkv.weight q4_K +blk.61.attn_qkv_gate.weight q4_K blk.61.ffn_down.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.62.ffn_down.weight q4_K blk.63.attn_output.weight q4_K blk.63.attn_v.weight q4_K @@ -318,146 +318,146 @@ blk.63.ffn_down.weight q4_K [Q3_K_L] q3_K output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_output.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q5_K +blk.4.attn_qkv_gate.weight q5_K blk.4.ffn_down.weight q5_K -blk.5.attn_qkv.weight q5_K +blk.5.attn_qkv_gate.weight q5_K blk.5.ffn_down.weight q5_K -blk.6.attn_qkv.weight q5_K +blk.6.attn_qkv_gate.weight q5_K blk.6.ffn_down.weight q5_K blk.7.attn_output.weight q5_K blk.7.attn_v.weight q5_K blk.7.ffn_down.weight q5_K -blk.8.attn_qkv.weight q5_K +blk.8.attn_qkv_gate.weight q5_K blk.8.ffn_down.weight q5_K -blk.9.attn_qkv.weight q5_K +blk.9.attn_qkv_gate.weight q5_K blk.9.ffn_down.weight q5_K -blk.10.attn_qkv.weight q5_K +blk.10.attn_qkv_gate.weight q5_K blk.10.ffn_down.weight q5_K blk.11.attn_output.weight q5_K blk.11.attn_v.weight q5_K blk.11.ffn_down.weight q5_K -blk.12.attn_qkv.weight q5_K +blk.12.attn_qkv_gate.weight q5_K blk.12.ffn_down.weight q5_K -blk.13.attn_qkv.weight q5_K +blk.13.attn_qkv_gate.weight q5_K blk.13.ffn_down.weight q5_K -blk.14.attn_qkv.weight q5_K +blk.14.attn_qkv_gate.weight q5_K blk.14.ffn_down.weight q5_K blk.15.attn_output.weight q5_K blk.15.attn_v.weight q5_K blk.15.ffn_down.weight q5_K -blk.16.attn_qkv.weight q5_K +blk.16.attn_qkv_gate.weight q5_K blk.16.ffn_down.weight q5_K -blk.17.attn_qkv.weight q5_K +blk.17.attn_qkv_gate.weight q5_K blk.17.ffn_down.weight q5_K -blk.18.attn_qkv.weight q5_K +blk.18.attn_qkv_gate.weight q5_K blk.18.ffn_down.weight q5_K blk.19.attn_output.weight q5_K blk.19.attn_v.weight q5_K blk.19.ffn_down.weight q5_K -blk.20.attn_qkv.weight q5_K +blk.20.attn_qkv_gate.weight q5_K blk.20.ffn_down.weight q5_K -blk.21.attn_qkv.weight q5_K +blk.21.attn_qkv_gate.weight q5_K blk.21.ffn_down.weight q5_K -blk.22.attn_qkv.weight q5_K +blk.22.attn_qkv_gate.weight q5_K blk.22.ffn_down.weight q5_K blk.23.attn_output.weight q5_K blk.23.attn_v.weight q5_K blk.23.ffn_down.weight q5_K -blk.24.attn_qkv.weight q5_K +blk.24.attn_qkv_gate.weight q5_K blk.24.ffn_down.weight q5_K -blk.25.attn_qkv.weight q5_K +blk.25.attn_qkv_gate.weight q5_K blk.25.ffn_down.weight q5_K -blk.26.attn_qkv.weight q5_K +blk.26.attn_qkv_gate.weight q5_K blk.26.ffn_down.weight q5_K blk.27.attn_output.weight q5_K blk.27.attn_v.weight q5_K blk.27.ffn_down.weight q5_K -blk.28.attn_qkv.weight q5_K +blk.28.attn_qkv_gate.weight q5_K blk.28.ffn_down.weight q5_K -blk.29.attn_qkv.weight q5_K +blk.29.attn_qkv_gate.weight q5_K blk.29.ffn_down.weight q5_K -blk.30.attn_qkv.weight q5_K +blk.30.attn_qkv_gate.weight q5_K blk.30.ffn_down.weight q5_K blk.31.attn_output.weight q5_K blk.31.attn_v.weight q5_K blk.31.ffn_down.weight q5_K -blk.32.attn_qkv.weight q5_K +blk.32.attn_qkv_gate.weight q5_K blk.32.ffn_down.weight q5_K -blk.33.attn_qkv.weight q5_K +blk.33.attn_qkv_gate.weight q5_K blk.33.ffn_down.weight q5_K -blk.34.attn_qkv.weight q5_K +blk.34.attn_qkv_gate.weight q5_K blk.34.ffn_down.weight q5_K blk.35.attn_output.weight q5_K blk.35.attn_v.weight q5_K blk.35.ffn_down.weight q5_K -blk.36.attn_qkv.weight q5_K +blk.36.attn_qkv_gate.weight q5_K blk.36.ffn_down.weight q5_K -blk.37.attn_qkv.weight q5_K +blk.37.attn_qkv_gate.weight q5_K blk.37.ffn_down.weight q5_K -blk.38.attn_qkv.weight q5_K +blk.38.attn_qkv_gate.weight q5_K blk.38.ffn_down.weight q5_K blk.39.attn_output.weight q5_K blk.39.attn_v.weight q5_K blk.39.ffn_down.weight q5_K -blk.40.attn_qkv.weight q5_K +blk.40.attn_qkv_gate.weight q5_K blk.40.ffn_down.weight q5_K -blk.41.attn_qkv.weight q5_K +blk.41.attn_qkv_gate.weight q5_K blk.41.ffn_down.weight q5_K -blk.42.attn_qkv.weight q5_K +blk.42.attn_qkv_gate.weight q5_K blk.42.ffn_down.weight q5_K blk.43.attn_output.weight q5_K blk.43.attn_v.weight q5_K blk.43.ffn_down.weight q5_K -blk.44.attn_qkv.weight q5_K +blk.44.attn_qkv_gate.weight q5_K blk.44.ffn_down.weight q5_K -blk.45.attn_qkv.weight q5_K +blk.45.attn_qkv_gate.weight q5_K blk.45.ffn_down.weight q5_K -blk.46.attn_qkv.weight q5_K +blk.46.attn_qkv_gate.weight q5_K blk.46.ffn_down.weight q5_K blk.47.attn_output.weight q5_K blk.47.attn_v.weight q5_K blk.47.ffn_down.weight q5_K -blk.48.attn_qkv.weight q5_K +blk.48.attn_qkv_gate.weight q5_K blk.48.ffn_down.weight q5_K -blk.49.attn_qkv.weight q5_K +blk.49.attn_qkv_gate.weight q5_K blk.49.ffn_down.weight q5_K -blk.50.attn_qkv.weight q5_K +blk.50.attn_qkv_gate.weight q5_K blk.50.ffn_down.weight q5_K blk.51.attn_output.weight q5_K blk.51.attn_v.weight q5_K blk.51.ffn_down.weight q5_K -blk.52.attn_qkv.weight q5_K +blk.52.attn_qkv_gate.weight q5_K blk.52.ffn_down.weight q5_K -blk.53.attn_qkv.weight q5_K +blk.53.attn_qkv_gate.weight q5_K blk.53.ffn_down.weight q5_K -blk.54.attn_qkv.weight q5_K +blk.54.attn_qkv_gate.weight q5_K blk.54.ffn_down.weight q5_K blk.55.attn_output.weight q5_K blk.55.attn_v.weight q5_K blk.55.ffn_down.weight q5_K -blk.56.attn_qkv.weight q5_K +blk.56.attn_qkv_gate.weight q5_K blk.56.ffn_down.weight q5_K -blk.57.attn_qkv.weight q5_K +blk.57.attn_qkv_gate.weight q5_K blk.57.ffn_down.weight q5_K -blk.58.attn_qkv.weight q5_K +blk.58.attn_qkv_gate.weight q5_K blk.58.ffn_down.weight q5_K blk.59.attn_output.weight q5_K blk.59.attn_v.weight q5_K blk.59.ffn_down.weight q5_K -blk.60.attn_qkv.weight q5_K +blk.60.attn_qkv_gate.weight q5_K blk.60.ffn_down.weight q5_K -blk.61.attn_qkv.weight q5_K +blk.61.attn_qkv_gate.weight q5_K blk.61.ffn_down.weight q5_K -blk.62.attn_qkv.weight q5_K +blk.62.attn_qkv_gate.weight q5_K blk.62.ffn_down.weight q5_K blk.63.attn_output.weight q5_K blk.63.attn_v.weight q5_K @@ -465,11 +465,11 @@ blk.63.ffn_down.weight q5_K [Q4_K_S] q4_K output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K @@ -480,67 +480,67 @@ blk.7.ffn_down.weight q5_K [Q4_K_M] q4_K output.weight q6_K -blk.0.attn_qkv.weight q6_K +blk.0.attn_qkv_gate.weight q6_K blk.0.ffn_down.weight q6_K -blk.1.attn_qkv.weight q6_K +blk.1.attn_qkv_gate.weight q6_K blk.1.ffn_down.weight q6_K -blk.2.attn_qkv.weight q6_K +blk.2.attn_qkv_gate.weight q6_K blk.2.ffn_down.weight q6_K blk.3.attn_v.weight q6_K blk.3.ffn_down.weight q6_K -blk.4.attn_qkv.weight q6_K +blk.4.attn_qkv_gate.weight q6_K blk.4.ffn_down.weight q6_K -blk.5.attn_qkv.weight q6_K +blk.5.attn_qkv_gate.weight q6_K blk.5.ffn_down.weight q6_K -blk.6.attn_qkv.weight q6_K +blk.6.attn_qkv_gate.weight q6_K blk.6.ffn_down.weight q6_K blk.7.attn_v.weight q6_K blk.7.ffn_down.weight q6_K -blk.10.attn_qkv.weight q6_K +blk.10.attn_qkv_gate.weight q6_K blk.10.ffn_down.weight q6_K -blk.13.attn_qkv.weight q6_K +blk.13.attn_qkv_gate.weight q6_K blk.13.ffn_down.weight q6_K -blk.16.attn_qkv.weight q6_K +blk.16.attn_qkv_gate.weight q6_K blk.16.ffn_down.weight q6_K blk.19.attn_v.weight q6_K blk.19.ffn_down.weight q6_K -blk.22.attn_qkv.weight q6_K +blk.22.attn_qkv_gate.weight q6_K blk.22.ffn_down.weight q6_K -blk.25.attn_qkv.weight q6_K +blk.25.attn_qkv_gate.weight q6_K blk.25.ffn_down.weight q6_K -blk.28.attn_qkv.weight q6_K +blk.28.attn_qkv_gate.weight q6_K blk.28.ffn_down.weight q6_K blk.31.attn_v.weight q6_K blk.31.ffn_down.weight q6_K -blk.34.attn_qkv.weight q6_K +blk.34.attn_qkv_gate.weight q6_K blk.34.ffn_down.weight q6_K -blk.37.attn_qkv.weight q6_K +blk.37.attn_qkv_gate.weight q6_K blk.37.ffn_down.weight q6_K -blk.40.attn_qkv.weight q6_K +blk.40.attn_qkv_gate.weight q6_K blk.40.ffn_down.weight q6_K blk.43.attn_v.weight q6_K blk.43.ffn_down.weight q6_K -blk.46.attn_qkv.weight q6_K +blk.46.attn_qkv_gate.weight q6_K blk.46.ffn_down.weight q6_K -blk.49.attn_qkv.weight q6_K +blk.49.attn_qkv_gate.weight q6_K blk.49.ffn_down.weight q6_K -blk.52.attn_qkv.weight q6_K +blk.52.attn_qkv_gate.weight q6_K blk.52.ffn_down.weight q6_K blk.55.attn_v.weight q6_K blk.55.ffn_down.weight q6_K -blk.56.attn_qkv.weight q6_K +blk.56.attn_qkv_gate.weight q6_K blk.56.ffn_down.weight q6_K -blk.57.attn_qkv.weight q6_K +blk.57.attn_qkv_gate.weight q6_K blk.57.ffn_down.weight q6_K -blk.58.attn_qkv.weight q6_K +blk.58.attn_qkv_gate.weight q6_K blk.58.ffn_down.weight q6_K blk.59.attn_v.weight q6_K blk.59.ffn_down.weight q6_K -blk.60.attn_qkv.weight q6_K +blk.60.attn_qkv_gate.weight q6_K blk.60.ffn_down.weight q6_K -blk.61.attn_qkv.weight q6_K +blk.61.attn_qkv_gate.weight q6_K blk.61.ffn_down.weight q6_K -blk.62.attn_qkv.weight q6_K +blk.62.attn_qkv_gate.weight q6_K blk.62.ffn_down.weight q6_K blk.63.attn_v.weight q6_K blk.63.ffn_down.weight q6_K @@ -550,67 +550,67 @@ output.weight q6_K [Q5_K_M] q5_K output.weight q6_K -blk.0.attn_qkv.weight q6_K +blk.0.attn_qkv_gate.weight q6_K blk.0.ffn_down.weight q6_K -blk.1.attn_qkv.weight q6_K +blk.1.attn_qkv_gate.weight q6_K blk.1.ffn_down.weight q6_K -blk.2.attn_qkv.weight q6_K +blk.2.attn_qkv_gate.weight q6_K blk.2.ffn_down.weight q6_K blk.3.attn_v.weight q6_K blk.3.ffn_down.weight q6_K -blk.4.attn_qkv.weight q6_K +blk.4.attn_qkv_gate.weight q6_K blk.4.ffn_down.weight q6_K -blk.5.attn_qkv.weight q6_K +blk.5.attn_qkv_gate.weight q6_K blk.5.ffn_down.weight q6_K -blk.6.attn_qkv.weight q6_K +blk.6.attn_qkv_gate.weight q6_K blk.6.ffn_down.weight q6_K blk.7.attn_v.weight q6_K blk.7.ffn_down.weight q6_K -blk.10.attn_qkv.weight q6_K +blk.10.attn_qkv_gate.weight q6_K blk.10.ffn_down.weight q6_K -blk.13.attn_qkv.weight q6_K +blk.13.attn_qkv_gate.weight q6_K blk.13.ffn_down.weight q6_K -blk.16.attn_qkv.weight q6_K +blk.16.attn_qkv_gate.weight q6_K blk.16.ffn_down.weight q6_K blk.19.attn_v.weight q6_K blk.19.ffn_down.weight q6_K -blk.22.attn_qkv.weight q6_K +blk.22.attn_qkv_gate.weight q6_K blk.22.ffn_down.weight q6_K -blk.25.attn_qkv.weight q6_K +blk.25.attn_qkv_gate.weight q6_K blk.25.ffn_down.weight q6_K -blk.28.attn_qkv.weight q6_K +blk.28.attn_qkv_gate.weight q6_K blk.28.ffn_down.weight q6_K blk.31.attn_v.weight q6_K blk.31.ffn_down.weight q6_K -blk.34.attn_qkv.weight q6_K +blk.34.attn_qkv_gate.weight q6_K blk.34.ffn_down.weight q6_K -blk.37.attn_qkv.weight q6_K +blk.37.attn_qkv_gate.weight q6_K blk.37.ffn_down.weight q6_K -blk.40.attn_qkv.weight q6_K +blk.40.attn_qkv_gate.weight q6_K blk.40.ffn_down.weight q6_K blk.43.attn_v.weight q6_K blk.43.ffn_down.weight q6_K -blk.46.attn_qkv.weight q6_K +blk.46.attn_qkv_gate.weight q6_K blk.46.ffn_down.weight q6_K -blk.49.attn_qkv.weight q6_K +blk.49.attn_qkv_gate.weight q6_K blk.49.ffn_down.weight q6_K -blk.52.attn_qkv.weight q6_K +blk.52.attn_qkv_gate.weight q6_K blk.52.ffn_down.weight q6_K blk.55.attn_v.weight q6_K blk.55.ffn_down.weight q6_K -blk.56.attn_qkv.weight q6_K +blk.56.attn_qkv_gate.weight q6_K blk.56.ffn_down.weight q6_K -blk.57.attn_qkv.weight q6_K +blk.57.attn_qkv_gate.weight q6_K blk.57.ffn_down.weight q6_K -blk.58.attn_qkv.weight q6_K +blk.58.attn_qkv_gate.weight q6_K blk.58.ffn_down.weight q6_K blk.59.attn_v.weight q6_K blk.59.ffn_down.weight q6_K -blk.60.attn_qkv.weight q6_K +blk.60.attn_qkv_gate.weight q6_K blk.60.ffn_down.weight q6_K -blk.61.attn_qkv.weight q6_K +blk.61.attn_qkv_gate.weight q6_K blk.61.ffn_down.weight q6_K -blk.62.attn_qkv.weight q6_K +blk.62.attn_qkv_gate.weight q6_K blk.62.ffn_down.weight q6_K blk.63.attn_v.weight q6_K blk.63.ffn_down.weight q6_K @@ -620,251 +620,251 @@ blk.63.ffn_down.weight q6_K [IQ2_XXS] iq2_xxs output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [IQ2_XS] iq2_xs output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [Q2_K_S] q2_K output.weight q6_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q4_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q4_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q4_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [IQ3_XS] iq3_s output.weight q6_K -blk.0.attn_qkv.weight q4_K -blk.1.attn_qkv.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K +blk.1.attn_qkv_gate.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.3.attn_k.weight iq3_xxs blk.3.attn_q.weight iq3_xxs blk.3.attn_v.weight q4_K -blk.4.attn_qkv.weight q4_K -blk.5.attn_qkv.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K +blk.5.attn_qkv_gate.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.7.attn_k.weight iq3_xxs blk.7.attn_q.weight iq3_xxs blk.7.attn_v.weight q4_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_gate.weight iq3_xxs blk.8.ffn_up.weight iq3_xxs -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_gate.weight iq3_xxs blk.9.ffn_up.weight iq3_xxs -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_gate.weight iq3_xxs blk.10.ffn_up.weight iq3_xxs blk.11.attn_k.weight iq3_xxs @@ -872,13 +872,13 @@ blk.11.attn_q.weight iq3_xxs blk.11.attn_v.weight q4_K blk.11.ffn_gate.weight iq3_xxs blk.11.ffn_up.weight iq3_xxs -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_gate.weight iq3_xxs blk.12.ffn_up.weight iq3_xxs -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_gate.weight iq3_xxs blk.13.ffn_up.weight iq3_xxs -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_gate.weight iq3_xxs blk.14.ffn_up.weight iq3_xxs blk.15.attn_k.weight iq3_xxs @@ -886,13 +886,13 @@ blk.15.attn_q.weight iq3_xxs blk.15.attn_v.weight q4_K blk.15.ffn_gate.weight iq3_xxs blk.15.ffn_up.weight iq3_xxs -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_gate.weight iq3_xxs blk.16.ffn_up.weight iq3_xxs -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_gate.weight iq3_xxs blk.17.ffn_up.weight iq3_xxs -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_gate.weight iq3_xxs blk.18.ffn_up.weight iq3_xxs blk.19.attn_k.weight iq3_xxs @@ -900,13 +900,13 @@ blk.19.attn_q.weight iq3_xxs blk.19.attn_v.weight q4_K blk.19.ffn_gate.weight iq3_xxs blk.19.ffn_up.weight iq3_xxs -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_gate.weight iq3_xxs blk.20.ffn_up.weight iq3_xxs -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_gate.weight iq3_xxs blk.21.ffn_up.weight iq3_xxs -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_gate.weight iq3_xxs blk.22.ffn_up.weight iq3_xxs blk.23.attn_k.weight iq3_xxs @@ -914,13 +914,13 @@ blk.23.attn_q.weight iq3_xxs blk.23.attn_v.weight q4_K blk.23.ffn_gate.weight iq3_xxs blk.23.ffn_up.weight iq3_xxs -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_gate.weight iq3_xxs blk.24.ffn_up.weight iq3_xxs -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_gate.weight iq3_xxs blk.25.ffn_up.weight iq3_xxs -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_gate.weight iq3_xxs blk.26.ffn_up.weight iq3_xxs blk.27.attn_k.weight iq3_xxs @@ -928,13 +928,13 @@ blk.27.attn_q.weight iq3_xxs blk.27.attn_v.weight q4_K blk.27.ffn_gate.weight iq3_xxs blk.27.ffn_up.weight iq3_xxs -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_gate.weight iq3_xxs blk.28.ffn_up.weight iq3_xxs -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_gate.weight iq3_xxs blk.29.ffn_up.weight iq3_xxs -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_gate.weight iq3_xxs blk.30.ffn_up.weight iq3_xxs blk.31.attn_k.weight iq3_xxs @@ -942,13 +942,13 @@ blk.31.attn_q.weight iq3_xxs blk.31.attn_v.weight q4_K blk.31.ffn_gate.weight iq3_xxs blk.31.ffn_up.weight iq3_xxs -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_gate.weight iq3_xxs blk.32.ffn_up.weight iq3_xxs -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_gate.weight iq3_xxs blk.33.ffn_up.weight iq3_xxs -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_gate.weight iq3_xxs blk.34.ffn_up.weight iq3_xxs blk.35.attn_k.weight iq3_xxs @@ -956,13 +956,13 @@ blk.35.attn_q.weight iq3_xxs blk.35.attn_v.weight q4_K blk.35.ffn_gate.weight iq3_xxs blk.35.ffn_up.weight iq3_xxs -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_gate.weight iq3_xxs blk.36.ffn_up.weight iq3_xxs -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_gate.weight iq3_xxs blk.37.ffn_up.weight iq3_xxs -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_gate.weight iq3_xxs blk.38.ffn_up.weight iq3_xxs blk.39.attn_k.weight iq3_xxs @@ -970,13 +970,13 @@ blk.39.attn_q.weight iq3_xxs blk.39.attn_v.weight q4_K blk.39.ffn_gate.weight iq3_xxs blk.39.ffn_up.weight iq3_xxs -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_gate.weight iq3_xxs blk.40.ffn_up.weight iq3_xxs -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_gate.weight iq3_xxs blk.41.ffn_up.weight iq3_xxs -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_gate.weight iq3_xxs blk.42.ffn_up.weight iq3_xxs blk.43.attn_k.weight iq3_xxs @@ -984,13 +984,13 @@ blk.43.attn_q.weight iq3_xxs blk.43.attn_v.weight q4_K blk.43.ffn_gate.weight iq3_xxs blk.43.ffn_up.weight iq3_xxs -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_gate.weight iq3_xxs blk.44.ffn_up.weight iq3_xxs -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_gate.weight iq3_xxs blk.45.ffn_up.weight iq3_xxs -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_gate.weight iq3_xxs blk.46.ffn_up.weight iq3_xxs blk.47.attn_k.weight iq3_xxs @@ -998,13 +998,13 @@ blk.47.attn_q.weight iq3_xxs blk.47.attn_v.weight q4_K blk.47.ffn_gate.weight iq3_xxs blk.47.ffn_up.weight iq3_xxs -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_gate.weight iq3_xxs blk.48.ffn_up.weight iq3_xxs -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_gate.weight iq3_xxs blk.49.ffn_up.weight iq3_xxs -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_gate.weight iq3_xxs blk.50.ffn_up.weight iq3_xxs blk.51.attn_k.weight iq3_xxs @@ -1012,13 +1012,13 @@ blk.51.attn_q.weight iq3_xxs blk.51.attn_v.weight q4_K blk.51.ffn_gate.weight iq3_xxs blk.51.ffn_up.weight iq3_xxs -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_gate.weight iq3_xxs blk.52.ffn_up.weight iq3_xxs -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_gate.weight iq3_xxs blk.53.ffn_up.weight iq3_xxs -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_gate.weight iq3_xxs blk.54.ffn_up.weight iq3_xxs blk.55.attn_k.weight iq3_xxs @@ -1026,15 +1026,15 @@ blk.55.attn_q.weight iq3_xxs blk.55.attn_v.weight q4_K blk.55.ffn_gate.weight iq3_xxs blk.55.ffn_up.weight iq3_xxs -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_k.weight iq3_xxs blk.59.attn_q.weight iq3_xxs blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_k.weight iq3_xxs blk.63.attn_q.weight iq3_xxs blk.63.attn_v.weight q4_K @@ -1042,176 +1042,176 @@ blk.63.attn_v.weight q4_K [IQ3_XXS] iq3_xxs output.weight q5_K token_embd.weight iq3_s -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q4_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q4_K blk.3.attn_k.weight iq2_s blk.3.attn_output.weight iq3_s blk.3.attn_q.weight iq2_s blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q4_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_k.weight iq2_s blk.7.attn_output.weight iq3_s blk.7.attn_q.weight iq2_s blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K blk.8.ffn_down.weight q3_K -blk.9.attn_qkv.weight q4_K +blk.9.attn_qkv_gate.weight q4_K blk.9.ffn_down.weight q3_K -blk.10.attn_qkv.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.10.ffn_down.weight q3_K blk.11.attn_k.weight iq2_s blk.11.attn_output.weight iq3_s blk.11.attn_q.weight iq2_s blk.11.attn_v.weight q4_K blk.11.ffn_down.weight q3_K -blk.12.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K blk.12.ffn_down.weight q3_K -blk.13.attn_qkv.weight q4_K +blk.13.attn_qkv_gate.weight q4_K blk.13.ffn_down.weight q3_K -blk.14.attn_qkv.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.14.ffn_down.weight q3_K blk.15.attn_k.weight iq2_s blk.15.attn_output.weight iq3_s blk.15.attn_q.weight iq2_s blk.15.attn_v.weight q4_K blk.15.ffn_down.weight q3_K -blk.16.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K blk.16.ffn_down.weight q3_K -blk.17.attn_qkv.weight q4_K +blk.17.attn_qkv_gate.weight q4_K blk.17.ffn_down.weight q3_K -blk.18.attn_qkv.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.18.ffn_down.weight q3_K blk.19.attn_k.weight iq2_s blk.19.attn_output.weight iq3_s blk.19.attn_q.weight iq2_s blk.19.attn_v.weight q4_K blk.19.ffn_down.weight q3_K -blk.20.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K blk.20.ffn_down.weight q3_K -blk.21.attn_qkv.weight q4_K +blk.21.attn_qkv_gate.weight q4_K blk.21.ffn_down.weight q3_K -blk.22.attn_qkv.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.22.ffn_down.weight q3_K blk.23.attn_k.weight iq2_s blk.23.attn_output.weight iq3_s blk.23.attn_q.weight iq2_s blk.23.attn_v.weight q4_K blk.23.ffn_down.weight q3_K -blk.24.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K blk.24.ffn_down.weight q3_K -blk.25.attn_qkv.weight q4_K +blk.25.attn_qkv_gate.weight q4_K blk.25.ffn_down.weight q3_K -blk.26.attn_qkv.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.26.ffn_down.weight q3_K blk.27.attn_k.weight iq2_s blk.27.attn_output.weight iq3_s blk.27.attn_q.weight iq2_s blk.27.attn_v.weight q4_K blk.27.ffn_down.weight q3_K -blk.28.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K blk.28.ffn_down.weight q3_K -blk.29.attn_qkv.weight q4_K +blk.29.attn_qkv_gate.weight q4_K blk.29.ffn_down.weight q3_K -blk.30.attn_qkv.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.30.ffn_down.weight q3_K blk.31.attn_k.weight iq2_s blk.31.attn_output.weight iq3_s blk.31.attn_q.weight iq2_s blk.31.attn_v.weight q4_K blk.31.ffn_down.weight q3_K -blk.32.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K blk.32.ffn_down.weight q3_K -blk.33.attn_qkv.weight q4_K +blk.33.attn_qkv_gate.weight q4_K blk.33.ffn_down.weight q3_K -blk.34.attn_qkv.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.34.ffn_down.weight q3_K blk.35.attn_k.weight iq2_s blk.35.attn_output.weight iq3_s blk.35.attn_q.weight iq2_s blk.35.attn_v.weight q4_K blk.35.ffn_down.weight q3_K -blk.36.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K blk.36.ffn_down.weight q3_K -blk.37.attn_qkv.weight q4_K +blk.37.attn_qkv_gate.weight q4_K blk.37.ffn_down.weight q3_K -blk.38.attn_qkv.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.38.ffn_down.weight q3_K blk.39.attn_k.weight iq2_s blk.39.attn_output.weight iq3_s blk.39.attn_q.weight iq2_s blk.39.attn_v.weight q4_K blk.39.ffn_down.weight q3_K -blk.40.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K blk.40.ffn_down.weight q3_K -blk.41.attn_qkv.weight q4_K +blk.41.attn_qkv_gate.weight q4_K blk.41.ffn_down.weight q3_K -blk.42.attn_qkv.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.42.ffn_down.weight q3_K blk.43.attn_k.weight iq2_s blk.43.attn_output.weight iq3_s blk.43.attn_q.weight iq2_s blk.43.attn_v.weight q4_K blk.43.ffn_down.weight q3_K -blk.44.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K blk.44.ffn_down.weight q3_K -blk.45.attn_qkv.weight q4_K +blk.45.attn_qkv_gate.weight q4_K blk.45.ffn_down.weight q3_K -blk.46.attn_qkv.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.46.ffn_down.weight q3_K blk.47.attn_k.weight iq2_s blk.47.attn_output.weight iq3_s blk.47.attn_q.weight iq2_s blk.47.attn_v.weight q4_K blk.47.ffn_down.weight q3_K -blk.48.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K blk.48.ffn_down.weight q3_K -blk.49.attn_qkv.weight q4_K +blk.49.attn_qkv_gate.weight q4_K blk.49.ffn_down.weight q3_K -blk.50.attn_qkv.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.50.ffn_down.weight q3_K blk.51.attn_k.weight iq2_s blk.51.attn_output.weight iq3_s blk.51.attn_q.weight iq2_s blk.51.attn_v.weight q4_K blk.51.ffn_down.weight q3_K -blk.52.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K blk.52.ffn_down.weight q3_K -blk.53.attn_qkv.weight q4_K +blk.53.attn_qkv_gate.weight q4_K blk.53.ffn_down.weight q3_K -blk.54.attn_qkv.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.54.ffn_down.weight q3_K blk.55.attn_k.weight iq2_s blk.55.attn_output.weight iq3_s blk.55.attn_q.weight iq2_s blk.55.attn_v.weight q4_K blk.55.ffn_down.weight q3_K -blk.56.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K blk.56.ffn_down.weight q3_K -blk.57.attn_qkv.weight q4_K +blk.57.attn_qkv_gate.weight q4_K blk.57.ffn_down.weight q3_K -blk.58.attn_qkv.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.58.ffn_down.weight q3_K blk.59.attn_k.weight iq2_s blk.59.attn_output.weight iq3_s blk.59.attn_q.weight iq2_s blk.59.attn_v.weight q4_K blk.59.ffn_down.weight q3_K -blk.60.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K blk.60.ffn_down.weight q3_K -blk.61.attn_qkv.weight q4_K +blk.61.attn_qkv_gate.weight q4_K blk.61.ffn_down.weight q3_K -blk.62.attn_qkv.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.62.ffn_down.weight q3_K blk.63.attn_k.weight iq2_s blk.63.attn_output.weight iq3_s @@ -1222,676 +1222,676 @@ blk.63.ffn_down.weight q3_K [IQ1_S] iq1_s output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_output.weight iq2_xxs blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_output.weight iq2_xxs blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq2_xxs blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq2_xxs blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq2_xxs blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq2_xxs blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq2_xxs blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq2_xxs blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq2_xxs blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq2_xxs blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq2_xxs blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq2_xxs blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq2_xxs blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq2_xxs blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq2_xxs blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq2_xxs blk.63.attn_v.weight q4_K [IQ4_NL] iq4_nl output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q5_K +blk.4.attn_qkv_gate.weight q5_K blk.4.ffn_down.weight q5_K -blk.5.attn_qkv.weight q5_K +blk.5.attn_qkv_gate.weight q5_K blk.5.ffn_down.weight q5_K -blk.6.attn_qkv.weight q5_K +blk.6.attn_qkv_gate.weight q5_K blk.6.ffn_down.weight q5_K blk.7.attn_v.weight q5_K blk.7.ffn_down.weight q5_K -blk.8.attn_qkv.weight q5_K -blk.9.attn_qkv.weight q5_K -blk.10.attn_qkv.weight q5_K +blk.8.attn_qkv_gate.weight q5_K +blk.9.attn_qkv_gate.weight q5_K +blk.10.attn_qkv_gate.weight q5_K blk.11.attn_v.weight q5_K -blk.12.attn_qkv.weight q5_K -blk.13.attn_qkv.weight q5_K -blk.14.attn_qkv.weight q5_K +blk.12.attn_qkv_gate.weight q5_K +blk.13.attn_qkv_gate.weight q5_K +blk.14.attn_qkv_gate.weight q5_K blk.15.attn_v.weight q5_K -blk.16.attn_qkv.weight q5_K -blk.17.attn_qkv.weight q5_K -blk.18.attn_qkv.weight q5_K +blk.16.attn_qkv_gate.weight q5_K +blk.17.attn_qkv_gate.weight q5_K +blk.18.attn_qkv_gate.weight q5_K blk.19.attn_v.weight q5_K -blk.20.attn_qkv.weight q5_K -blk.21.attn_qkv.weight q5_K -blk.22.attn_qkv.weight q5_K +blk.20.attn_qkv_gate.weight q5_K +blk.21.attn_qkv_gate.weight q5_K +blk.22.attn_qkv_gate.weight q5_K blk.23.attn_v.weight q5_K -blk.24.attn_qkv.weight q5_K -blk.25.attn_qkv.weight q5_K -blk.26.attn_qkv.weight q5_K +blk.24.attn_qkv_gate.weight q5_K +blk.25.attn_qkv_gate.weight q5_K +blk.26.attn_qkv_gate.weight q5_K blk.27.attn_v.weight q5_K -blk.28.attn_qkv.weight q5_K -blk.29.attn_qkv.weight q5_K -blk.30.attn_qkv.weight q5_K +blk.28.attn_qkv_gate.weight q5_K +blk.29.attn_qkv_gate.weight q5_K +blk.30.attn_qkv_gate.weight q5_K blk.31.attn_v.weight q5_K -blk.32.attn_qkv.weight q5_K -blk.33.attn_qkv.weight q5_K -blk.34.attn_qkv.weight q5_K +blk.32.attn_qkv_gate.weight q5_K +blk.33.attn_qkv_gate.weight q5_K +blk.34.attn_qkv_gate.weight q5_K blk.35.attn_v.weight q5_K -blk.36.attn_qkv.weight q5_K -blk.37.attn_qkv.weight q5_K -blk.38.attn_qkv.weight q5_K +blk.36.attn_qkv_gate.weight q5_K +blk.37.attn_qkv_gate.weight q5_K +blk.38.attn_qkv_gate.weight q5_K blk.39.attn_v.weight q5_K -blk.40.attn_qkv.weight q5_K -blk.41.attn_qkv.weight q5_K -blk.42.attn_qkv.weight q5_K +blk.40.attn_qkv_gate.weight q5_K +blk.41.attn_qkv_gate.weight q5_K +blk.42.attn_qkv_gate.weight q5_K blk.43.attn_v.weight q5_K -blk.44.attn_qkv.weight q5_K -blk.45.attn_qkv.weight q5_K -blk.46.attn_qkv.weight q5_K +blk.44.attn_qkv_gate.weight q5_K +blk.45.attn_qkv_gate.weight q5_K +blk.46.attn_qkv_gate.weight q5_K blk.47.attn_v.weight q5_K -blk.48.attn_qkv.weight q5_K -blk.49.attn_qkv.weight q5_K -blk.50.attn_qkv.weight q5_K +blk.48.attn_qkv_gate.weight q5_K +blk.49.attn_qkv_gate.weight q5_K +blk.50.attn_qkv_gate.weight q5_K blk.51.attn_v.weight q5_K -blk.52.attn_qkv.weight q5_K -blk.53.attn_qkv.weight q5_K -blk.54.attn_qkv.weight q5_K +blk.52.attn_qkv_gate.weight q5_K +blk.53.attn_qkv_gate.weight q5_K +blk.54.attn_qkv_gate.weight q5_K blk.55.attn_v.weight q5_K -blk.56.attn_qkv.weight q5_K -blk.57.attn_qkv.weight q5_K -blk.58.attn_qkv.weight q5_K +blk.56.attn_qkv_gate.weight q5_K +blk.57.attn_qkv_gate.weight q5_K +blk.58.attn_qkv_gate.weight q5_K blk.59.attn_v.weight q5_K -blk.60.attn_qkv.weight q5_K -blk.61.attn_qkv.weight q5_K -blk.62.attn_qkv.weight q5_K +blk.60.attn_qkv_gate.weight q5_K +blk.61.attn_qkv_gate.weight q5_K +blk.62.attn_qkv_gate.weight q5_K blk.63.attn_v.weight q5_K [IQ3_S] iq3_s output.weight q6_K -blk.0.attn_qkv.weight q4_K -blk.1.attn_qkv.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K +blk.1.attn_qkv_gate.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.3.attn_v.weight q4_K -blk.4.attn_qkv.weight q4_K -blk.5.attn_qkv.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K +blk.5.attn_qkv_gate.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.7.attn_v.weight q4_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_v.weight q4_K [IQ3_M] iq3_s output.weight q6_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q4_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q4_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q4_K blk.3.attn_output.weight q4_K blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q4_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q4_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q4_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q4_K blk.7.attn_output.weight q4_K blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q4_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight q4_K blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight q4_K blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight q4_K blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight q4_K blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight q4_K blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight q4_K blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight q4_K blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight q4_K blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight q4_K blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight q4_K blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight q4_K blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight q4_K blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight q4_K blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight q4_K blk.63.attn_v.weight q4_K [IQ2_S] iq2_xs output.weight q5_K token_embd.weight iq3_s -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight iq3_s -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight iq3_s -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight iq3_s blk.3.attn_output.weight iq3_s blk.3.attn_v.weight q4_K blk.3.ffn_down.weight iq3_s -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight iq3_s -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight iq3_s -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight iq3_s blk.7.attn_output.weight iq3_s blk.7.attn_v.weight q4_K blk.7.ffn_down.weight iq3_s -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq3_s blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq3_s blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq3_s blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq3_s blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq3_s blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq3_s blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq3_s blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq3_s blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq3_s blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq3_s blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq3_s blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq3_s blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq3_s blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq3_s blk.63.attn_v.weight q4_K [IQ2_M] iq2_s output.weight q5_K token_embd.weight iq3_s -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight iq3_s -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight iq3_s -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight iq3_s blk.3.attn_output.weight iq3_s blk.3.attn_v.weight q4_K blk.3.ffn_down.weight iq3_s -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight iq3_s -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight iq3_s -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight iq3_s blk.7.attn_output.weight iq3_s blk.7.attn_v.weight q4_K blk.7.ffn_down.weight iq3_s -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq3_s blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq3_s blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq3_s blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq3_s blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq3_s blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq3_s blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq3_s blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq3_s blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq3_s blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq3_s blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq3_s blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq3_s blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq3_s blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq3_s blk.63.attn_v.weight q4_K [IQ4_XS] iq4_xs output.weight q6_K -blk.0.attn_qkv.weight q5_K +blk.0.attn_qkv_gate.weight q5_K blk.0.ffn_down.weight q5_K -blk.1.attn_qkv.weight q5_K +blk.1.attn_qkv_gate.weight q5_K blk.1.ffn_down.weight q5_K -blk.2.attn_qkv.weight q5_K +blk.2.attn_qkv_gate.weight q5_K blk.2.ffn_down.weight q5_K blk.3.attn_v.weight q5_K blk.3.ffn_down.weight q5_K -blk.4.attn_qkv.weight q5_K +blk.4.attn_qkv_gate.weight q5_K blk.4.ffn_down.weight q5_K -blk.5.attn_qkv.weight q5_K +blk.5.attn_qkv_gate.weight q5_K blk.5.ffn_down.weight q5_K -blk.6.attn_qkv.weight q5_K +blk.6.attn_qkv_gate.weight q5_K blk.6.ffn_down.weight q5_K blk.7.attn_v.weight q5_K blk.7.ffn_down.weight q5_K -blk.8.attn_qkv.weight q5_K -blk.9.attn_qkv.weight q5_K -blk.10.attn_qkv.weight q5_K +blk.8.attn_qkv_gate.weight q5_K +blk.9.attn_qkv_gate.weight q5_K +blk.10.attn_qkv_gate.weight q5_K blk.11.attn_v.weight q5_K -blk.12.attn_qkv.weight q5_K -blk.13.attn_qkv.weight q5_K -blk.14.attn_qkv.weight q5_K +blk.12.attn_qkv_gate.weight q5_K +blk.13.attn_qkv_gate.weight q5_K +blk.14.attn_qkv_gate.weight q5_K blk.15.attn_v.weight q5_K -blk.16.attn_qkv.weight q5_K -blk.17.attn_qkv.weight q5_K -blk.18.attn_qkv.weight q5_K +blk.16.attn_qkv_gate.weight q5_K +blk.17.attn_qkv_gate.weight q5_K +blk.18.attn_qkv_gate.weight q5_K blk.19.attn_v.weight q5_K -blk.20.attn_qkv.weight q5_K -blk.21.attn_qkv.weight q5_K -blk.22.attn_qkv.weight q5_K +blk.20.attn_qkv_gate.weight q5_K +blk.21.attn_qkv_gate.weight q5_K +blk.22.attn_qkv_gate.weight q5_K blk.23.attn_v.weight q5_K -blk.24.attn_qkv.weight q5_K -blk.25.attn_qkv.weight q5_K -blk.26.attn_qkv.weight q5_K +blk.24.attn_qkv_gate.weight q5_K +blk.25.attn_qkv_gate.weight q5_K +blk.26.attn_qkv_gate.weight q5_K blk.27.attn_v.weight q5_K -blk.28.attn_qkv.weight q5_K -blk.29.attn_qkv.weight q5_K -blk.30.attn_qkv.weight q5_K +blk.28.attn_qkv_gate.weight q5_K +blk.29.attn_qkv_gate.weight q5_K +blk.30.attn_qkv_gate.weight q5_K blk.31.attn_v.weight q5_K -blk.32.attn_qkv.weight q5_K -blk.33.attn_qkv.weight q5_K -blk.34.attn_qkv.weight q5_K +blk.32.attn_qkv_gate.weight q5_K +blk.33.attn_qkv_gate.weight q5_K +blk.34.attn_qkv_gate.weight q5_K blk.35.attn_v.weight q5_K -blk.36.attn_qkv.weight q5_K -blk.37.attn_qkv.weight q5_K -blk.38.attn_qkv.weight q5_K +blk.36.attn_qkv_gate.weight q5_K +blk.37.attn_qkv_gate.weight q5_K +blk.38.attn_qkv_gate.weight q5_K blk.39.attn_v.weight q5_K -blk.40.attn_qkv.weight q5_K -blk.41.attn_qkv.weight q5_K -blk.42.attn_qkv.weight q5_K +blk.40.attn_qkv_gate.weight q5_K +blk.41.attn_qkv_gate.weight q5_K +blk.42.attn_qkv_gate.weight q5_K blk.43.attn_v.weight q5_K -blk.44.attn_qkv.weight q5_K -blk.45.attn_qkv.weight q5_K -blk.46.attn_qkv.weight q5_K +blk.44.attn_qkv_gate.weight q5_K +blk.45.attn_qkv_gate.weight q5_K +blk.46.attn_qkv_gate.weight q5_K blk.47.attn_v.weight q5_K -blk.48.attn_qkv.weight q5_K -blk.49.attn_qkv.weight q5_K -blk.50.attn_qkv.weight q5_K +blk.48.attn_qkv_gate.weight q5_K +blk.49.attn_qkv_gate.weight q5_K +blk.50.attn_qkv_gate.weight q5_K blk.51.attn_v.weight q5_K -blk.52.attn_qkv.weight q5_K -blk.53.attn_qkv.weight q5_K -blk.54.attn_qkv.weight q5_K +blk.52.attn_qkv_gate.weight q5_K +blk.53.attn_qkv_gate.weight q5_K +blk.54.attn_qkv_gate.weight q5_K blk.55.attn_v.weight q5_K -blk.56.attn_qkv.weight q5_K -blk.57.attn_qkv.weight q5_K -blk.58.attn_qkv.weight q5_K +blk.56.attn_qkv_gate.weight q5_K +blk.57.attn_qkv_gate.weight q5_K +blk.58.attn_qkv_gate.weight q5_K blk.59.attn_v.weight q5_K -blk.60.attn_qkv.weight q5_K -blk.61.attn_qkv.weight q5_K -blk.62.attn_qkv.weight q5_K +blk.60.attn_qkv_gate.weight q5_K +blk.61.attn_qkv_gate.weight q5_K +blk.62.attn_qkv_gate.weight q5_K blk.63.attn_v.weight q5_K [IQ1_M] iq1_m output.weight q5_K token_embd.weight q2_K -blk.0.attn_qkv.weight q4_K +blk.0.attn_qkv_gate.weight q4_K blk.0.ffn_down.weight q2_K -blk.1.attn_qkv.weight q4_K +blk.1.attn_qkv_gate.weight q4_K blk.1.ffn_down.weight q2_K -blk.2.attn_qkv.weight q4_K +blk.2.attn_qkv_gate.weight q4_K blk.2.ffn_down.weight q2_K blk.3.attn_output.weight iq2_xxs blk.3.attn_v.weight q4_K blk.3.ffn_down.weight q2_K -blk.4.attn_qkv.weight q4_K +blk.4.attn_qkv_gate.weight q4_K blk.4.ffn_down.weight q2_K -blk.5.attn_qkv.weight q4_K +blk.5.attn_qkv_gate.weight q4_K blk.5.ffn_down.weight q2_K -blk.6.attn_qkv.weight q4_K +blk.6.attn_qkv_gate.weight q4_K blk.6.ffn_down.weight q2_K blk.7.attn_output.weight iq2_xxs blk.7.attn_v.weight q4_K blk.7.ffn_down.weight q2_K -blk.8.attn_qkv.weight q4_K -blk.9.attn_qkv.weight q4_K -blk.10.attn_qkv.weight q4_K +blk.8.attn_qkv_gate.weight q4_K +blk.9.attn_qkv_gate.weight q4_K +blk.10.attn_qkv_gate.weight q4_K blk.11.attn_output.weight iq2_xxs blk.11.attn_v.weight q4_K -blk.12.attn_qkv.weight q4_K -blk.13.attn_qkv.weight q4_K -blk.14.attn_qkv.weight q4_K +blk.12.attn_qkv_gate.weight q4_K +blk.13.attn_qkv_gate.weight q4_K +blk.14.attn_qkv_gate.weight q4_K blk.15.attn_output.weight iq2_xxs blk.15.attn_v.weight q4_K -blk.16.attn_qkv.weight q4_K -blk.17.attn_qkv.weight q4_K -blk.18.attn_qkv.weight q4_K +blk.16.attn_qkv_gate.weight q4_K +blk.17.attn_qkv_gate.weight q4_K +blk.18.attn_qkv_gate.weight q4_K blk.19.attn_output.weight iq2_xxs blk.19.attn_v.weight q4_K -blk.20.attn_qkv.weight q4_K -blk.21.attn_qkv.weight q4_K -blk.22.attn_qkv.weight q4_K +blk.20.attn_qkv_gate.weight q4_K +blk.21.attn_qkv_gate.weight q4_K +blk.22.attn_qkv_gate.weight q4_K blk.23.attn_output.weight iq2_xxs blk.23.attn_v.weight q4_K -blk.24.attn_qkv.weight q4_K -blk.25.attn_qkv.weight q4_K -blk.26.attn_qkv.weight q4_K +blk.24.attn_qkv_gate.weight q4_K +blk.25.attn_qkv_gate.weight q4_K +blk.26.attn_qkv_gate.weight q4_K blk.27.attn_output.weight iq2_xxs blk.27.attn_v.weight q4_K -blk.28.attn_qkv.weight q4_K -blk.29.attn_qkv.weight q4_K -blk.30.attn_qkv.weight q4_K +blk.28.attn_qkv_gate.weight q4_K +blk.29.attn_qkv_gate.weight q4_K +blk.30.attn_qkv_gate.weight q4_K blk.31.attn_output.weight iq2_xxs blk.31.attn_v.weight q4_K -blk.32.attn_qkv.weight q4_K -blk.33.attn_qkv.weight q4_K -blk.34.attn_qkv.weight q4_K +blk.32.attn_qkv_gate.weight q4_K +blk.33.attn_qkv_gate.weight q4_K +blk.34.attn_qkv_gate.weight q4_K blk.35.attn_output.weight iq2_xxs blk.35.attn_v.weight q4_K -blk.36.attn_qkv.weight q4_K -blk.37.attn_qkv.weight q4_K -blk.38.attn_qkv.weight q4_K +blk.36.attn_qkv_gate.weight q4_K +blk.37.attn_qkv_gate.weight q4_K +blk.38.attn_qkv_gate.weight q4_K blk.39.attn_output.weight iq2_xxs blk.39.attn_v.weight q4_K -blk.40.attn_qkv.weight q4_K -blk.41.attn_qkv.weight q4_K -blk.42.attn_qkv.weight q4_K +blk.40.attn_qkv_gate.weight q4_K +blk.41.attn_qkv_gate.weight q4_K +blk.42.attn_qkv_gate.weight q4_K blk.43.attn_output.weight iq2_xxs blk.43.attn_v.weight q4_K -blk.44.attn_qkv.weight q4_K -blk.45.attn_qkv.weight q4_K -blk.46.attn_qkv.weight q4_K +blk.44.attn_qkv_gate.weight q4_K +blk.45.attn_qkv_gate.weight q4_K +blk.46.attn_qkv_gate.weight q4_K blk.47.attn_output.weight iq2_xxs blk.47.attn_v.weight q4_K -blk.48.attn_qkv.weight q4_K -blk.49.attn_qkv.weight q4_K -blk.50.attn_qkv.weight q4_K +blk.48.attn_qkv_gate.weight q4_K +blk.49.attn_qkv_gate.weight q4_K +blk.50.attn_qkv_gate.weight q4_K blk.51.attn_output.weight iq2_xxs blk.51.attn_v.weight q4_K -blk.52.attn_qkv.weight q4_K -blk.53.attn_qkv.weight q4_K -blk.54.attn_qkv.weight q4_K +blk.52.attn_qkv_gate.weight q4_K +blk.53.attn_qkv_gate.weight q4_K +blk.54.attn_qkv_gate.weight q4_K blk.55.attn_output.weight iq2_xxs blk.55.attn_v.weight q4_K -blk.56.attn_qkv.weight q4_K -blk.57.attn_qkv.weight q4_K -blk.58.attn_qkv.weight q4_K +blk.56.attn_qkv_gate.weight q4_K +blk.57.attn_qkv_gate.weight q4_K +blk.58.attn_qkv_gate.weight q4_K blk.59.attn_output.weight iq2_xxs blk.59.attn_v.weight q4_K -blk.60.attn_qkv.weight q4_K -blk.61.attn_qkv.weight q4_K -blk.62.attn_qkv.weight q4_K +blk.60.attn_qkv_gate.weight q4_K +blk.61.attn_qkv_gate.weight q4_K +blk.62.attn_qkv_gate.weight q4_K blk.63.attn_output.weight iq2_xxs blk.63.attn_v.weight q4_K @@ -1908,29 +1908,23 @@ token_embd.weight q4_K [MXFP4_MOE] mxfp4 output.weight q8_0 token_embd.weight q8_0 -blk.0.attn_gate.weight q8_0 -blk.0.attn_qkv.weight q8_0 +blk.0.attn_qkv_gate.weight q8_0 blk.0.ffn_down.weight q8_0 blk.0.ffn_gate.weight q8_0 blk.0.ffn_up.weight q8_0 -blk.0.ssm_alpha.weight q8_0 -blk.0.ssm_beta.weight q8_0 +blk.0.ssm_beta_alpha.weight q8_0 blk.0.ssm_out.weight q8_0 -blk.1.attn_gate.weight q8_0 -blk.1.attn_qkv.weight q8_0 +blk.1.attn_qkv_gate.weight q8_0 blk.1.ffn_down.weight q8_0 blk.1.ffn_gate.weight q8_0 blk.1.ffn_up.weight q8_0 -blk.1.ssm_alpha.weight q8_0 -blk.1.ssm_beta.weight q8_0 +blk.1.ssm_beta_alpha.weight q8_0 blk.1.ssm_out.weight q8_0 -blk.2.attn_gate.weight q8_0 -blk.2.attn_qkv.weight q8_0 +blk.2.attn_qkv_gate.weight q8_0 blk.2.ffn_down.weight q8_0 blk.2.ffn_gate.weight q8_0 blk.2.ffn_up.weight q8_0 -blk.2.ssm_alpha.weight q8_0 -blk.2.ssm_beta.weight q8_0 +blk.2.ssm_beta_alpha.weight q8_0 blk.2.ssm_out.weight q8_0 blk.3.attn_k.weight q8_0 blk.3.attn_output.weight q8_0 @@ -1939,29 +1933,23 @@ blk.3.attn_v.weight q8_0 blk.3.ffn_down.weight q8_0 blk.3.ffn_gate.weight q8_0 blk.3.ffn_up.weight q8_0 -blk.4.attn_gate.weight q8_0 -blk.4.attn_qkv.weight q8_0 +blk.4.attn_qkv_gate.weight q8_0 blk.4.ffn_down.weight q8_0 blk.4.ffn_gate.weight q8_0 blk.4.ffn_up.weight q8_0 -blk.4.ssm_alpha.weight q8_0 -blk.4.ssm_beta.weight q8_0 +blk.4.ssm_beta_alpha.weight q8_0 blk.4.ssm_out.weight q8_0 -blk.5.attn_gate.weight q8_0 -blk.5.attn_qkv.weight q8_0 +blk.5.attn_qkv_gate.weight q8_0 blk.5.ffn_down.weight q8_0 blk.5.ffn_gate.weight q8_0 blk.5.ffn_up.weight q8_0 -blk.5.ssm_alpha.weight q8_0 -blk.5.ssm_beta.weight q8_0 +blk.5.ssm_beta_alpha.weight q8_0 blk.5.ssm_out.weight q8_0 -blk.6.attn_gate.weight q8_0 -blk.6.attn_qkv.weight q8_0 +blk.6.attn_qkv_gate.weight q8_0 blk.6.ffn_down.weight q8_0 blk.6.ffn_gate.weight q8_0 blk.6.ffn_up.weight q8_0 -blk.6.ssm_alpha.weight q8_0 -blk.6.ssm_beta.weight q8_0 +blk.6.ssm_beta_alpha.weight q8_0 blk.6.ssm_out.weight q8_0 blk.7.attn_k.weight q8_0 blk.7.attn_output.weight q8_0 @@ -1970,29 +1958,23 @@ blk.7.attn_v.weight q8_0 blk.7.ffn_down.weight q8_0 blk.7.ffn_gate.weight q8_0 blk.7.ffn_up.weight q8_0 -blk.8.attn_gate.weight q8_0 -blk.8.attn_qkv.weight q8_0 +blk.8.attn_qkv_gate.weight q8_0 blk.8.ffn_down.weight q8_0 blk.8.ffn_gate.weight q8_0 blk.8.ffn_up.weight q8_0 -blk.8.ssm_alpha.weight q8_0 -blk.8.ssm_beta.weight q8_0 +blk.8.ssm_beta_alpha.weight q8_0 blk.8.ssm_out.weight q8_0 -blk.9.attn_gate.weight q8_0 -blk.9.attn_qkv.weight q8_0 +blk.9.attn_qkv_gate.weight q8_0 blk.9.ffn_down.weight q8_0 blk.9.ffn_gate.weight q8_0 blk.9.ffn_up.weight q8_0 -blk.9.ssm_alpha.weight q8_0 -blk.9.ssm_beta.weight q8_0 +blk.9.ssm_beta_alpha.weight q8_0 blk.9.ssm_out.weight q8_0 -blk.10.attn_gate.weight q8_0 -blk.10.attn_qkv.weight q8_0 +blk.10.attn_qkv_gate.weight q8_0 blk.10.ffn_down.weight q8_0 blk.10.ffn_gate.weight q8_0 blk.10.ffn_up.weight q8_0 -blk.10.ssm_alpha.weight q8_0 -blk.10.ssm_beta.weight q8_0 +blk.10.ssm_beta_alpha.weight q8_0 blk.10.ssm_out.weight q8_0 blk.11.attn_k.weight q8_0 blk.11.attn_output.weight q8_0 @@ -2001,29 +1983,23 @@ blk.11.attn_v.weight q8_0 blk.11.ffn_down.weight q8_0 blk.11.ffn_gate.weight q8_0 blk.11.ffn_up.weight q8_0 -blk.12.attn_gate.weight q8_0 -blk.12.attn_qkv.weight q8_0 +blk.12.attn_qkv_gate.weight q8_0 blk.12.ffn_down.weight q8_0 blk.12.ffn_gate.weight q8_0 blk.12.ffn_up.weight q8_0 -blk.12.ssm_alpha.weight q8_0 -blk.12.ssm_beta.weight q8_0 +blk.12.ssm_beta_alpha.weight q8_0 blk.12.ssm_out.weight q8_0 -blk.13.attn_gate.weight q8_0 -blk.13.attn_qkv.weight q8_0 +blk.13.attn_qkv_gate.weight q8_0 blk.13.ffn_down.weight q8_0 blk.13.ffn_gate.weight q8_0 blk.13.ffn_up.weight q8_0 -blk.13.ssm_alpha.weight q8_0 -blk.13.ssm_beta.weight q8_0 +blk.13.ssm_beta_alpha.weight q8_0 blk.13.ssm_out.weight q8_0 -blk.14.attn_gate.weight q8_0 -blk.14.attn_qkv.weight q8_0 +blk.14.attn_qkv_gate.weight q8_0 blk.14.ffn_down.weight q8_0 blk.14.ffn_gate.weight q8_0 blk.14.ffn_up.weight q8_0 -blk.14.ssm_alpha.weight q8_0 -blk.14.ssm_beta.weight q8_0 +blk.14.ssm_beta_alpha.weight q8_0 blk.14.ssm_out.weight q8_0 blk.15.attn_k.weight q8_0 blk.15.attn_output.weight q8_0 @@ -2032,29 +2008,23 @@ blk.15.attn_v.weight q8_0 blk.15.ffn_down.weight q8_0 blk.15.ffn_gate.weight q8_0 blk.15.ffn_up.weight q8_0 -blk.16.attn_gate.weight q8_0 -blk.16.attn_qkv.weight q8_0 +blk.16.attn_qkv_gate.weight q8_0 blk.16.ffn_down.weight q8_0 blk.16.ffn_gate.weight q8_0 blk.16.ffn_up.weight q8_0 -blk.16.ssm_alpha.weight q8_0 -blk.16.ssm_beta.weight q8_0 +blk.16.ssm_beta_alpha.weight q8_0 blk.16.ssm_out.weight q8_0 -blk.17.attn_gate.weight q8_0 -blk.17.attn_qkv.weight q8_0 +blk.17.attn_qkv_gate.weight q8_0 blk.17.ffn_down.weight q8_0 blk.17.ffn_gate.weight q8_0 blk.17.ffn_up.weight q8_0 -blk.17.ssm_alpha.weight q8_0 -blk.17.ssm_beta.weight q8_0 +blk.17.ssm_beta_alpha.weight q8_0 blk.17.ssm_out.weight q8_0 -blk.18.attn_gate.weight q8_0 -blk.18.attn_qkv.weight q8_0 +blk.18.attn_qkv_gate.weight q8_0 blk.18.ffn_down.weight q8_0 blk.18.ffn_gate.weight q8_0 blk.18.ffn_up.weight q8_0 -blk.18.ssm_alpha.weight q8_0 -blk.18.ssm_beta.weight q8_0 +blk.18.ssm_beta_alpha.weight q8_0 blk.18.ssm_out.weight q8_0 blk.19.attn_k.weight q8_0 blk.19.attn_output.weight q8_0 @@ -2063,29 +2033,23 @@ blk.19.attn_v.weight q8_0 blk.19.ffn_down.weight q8_0 blk.19.ffn_gate.weight q8_0 blk.19.ffn_up.weight q8_0 -blk.20.attn_gate.weight q8_0 -blk.20.attn_qkv.weight q8_0 +blk.20.attn_qkv_gate.weight q8_0 blk.20.ffn_down.weight q8_0 blk.20.ffn_gate.weight q8_0 blk.20.ffn_up.weight q8_0 -blk.20.ssm_alpha.weight q8_0 -blk.20.ssm_beta.weight q8_0 +blk.20.ssm_beta_alpha.weight q8_0 blk.20.ssm_out.weight q8_0 -blk.21.attn_gate.weight q8_0 -blk.21.attn_qkv.weight q8_0 +blk.21.attn_qkv_gate.weight q8_0 blk.21.ffn_down.weight q8_0 blk.21.ffn_gate.weight q8_0 blk.21.ffn_up.weight q8_0 -blk.21.ssm_alpha.weight q8_0 -blk.21.ssm_beta.weight q8_0 +blk.21.ssm_beta_alpha.weight q8_0 blk.21.ssm_out.weight q8_0 -blk.22.attn_gate.weight q8_0 -blk.22.attn_qkv.weight q8_0 +blk.22.attn_qkv_gate.weight q8_0 blk.22.ffn_down.weight q8_0 blk.22.ffn_gate.weight q8_0 blk.22.ffn_up.weight q8_0 -blk.22.ssm_alpha.weight q8_0 -blk.22.ssm_beta.weight q8_0 +blk.22.ssm_beta_alpha.weight q8_0 blk.22.ssm_out.weight q8_0 blk.23.attn_k.weight q8_0 blk.23.attn_output.weight q8_0 @@ -2094,29 +2058,23 @@ blk.23.attn_v.weight q8_0 blk.23.ffn_down.weight q8_0 blk.23.ffn_gate.weight q8_0 blk.23.ffn_up.weight q8_0 -blk.24.attn_gate.weight q8_0 -blk.24.attn_qkv.weight q8_0 +blk.24.attn_qkv_gate.weight q8_0 blk.24.ffn_down.weight q8_0 blk.24.ffn_gate.weight q8_0 blk.24.ffn_up.weight q8_0 -blk.24.ssm_alpha.weight q8_0 -blk.24.ssm_beta.weight q8_0 +blk.24.ssm_beta_alpha.weight q8_0 blk.24.ssm_out.weight q8_0 -blk.25.attn_gate.weight q8_0 -blk.25.attn_qkv.weight q8_0 +blk.25.attn_qkv_gate.weight q8_0 blk.25.ffn_down.weight q8_0 blk.25.ffn_gate.weight q8_0 blk.25.ffn_up.weight q8_0 -blk.25.ssm_alpha.weight q8_0 -blk.25.ssm_beta.weight q8_0 +blk.25.ssm_beta_alpha.weight q8_0 blk.25.ssm_out.weight q8_0 -blk.26.attn_gate.weight q8_0 -blk.26.attn_qkv.weight q8_0 +blk.26.attn_qkv_gate.weight q8_0 blk.26.ffn_down.weight q8_0 blk.26.ffn_gate.weight q8_0 blk.26.ffn_up.weight q8_0 -blk.26.ssm_alpha.weight q8_0 -blk.26.ssm_beta.weight q8_0 +blk.26.ssm_beta_alpha.weight q8_0 blk.26.ssm_out.weight q8_0 blk.27.attn_k.weight q8_0 blk.27.attn_output.weight q8_0 @@ -2125,29 +2083,23 @@ blk.27.attn_v.weight q8_0 blk.27.ffn_down.weight q8_0 blk.27.ffn_gate.weight q8_0 blk.27.ffn_up.weight q8_0 -blk.28.attn_gate.weight q8_0 -blk.28.attn_qkv.weight q8_0 +blk.28.attn_qkv_gate.weight q8_0 blk.28.ffn_down.weight q8_0 blk.28.ffn_gate.weight q8_0 blk.28.ffn_up.weight q8_0 -blk.28.ssm_alpha.weight q8_0 -blk.28.ssm_beta.weight q8_0 +blk.28.ssm_beta_alpha.weight q8_0 blk.28.ssm_out.weight q8_0 -blk.29.attn_gate.weight q8_0 -blk.29.attn_qkv.weight q8_0 +blk.29.attn_qkv_gate.weight q8_0 blk.29.ffn_down.weight q8_0 blk.29.ffn_gate.weight q8_0 blk.29.ffn_up.weight q8_0 -blk.29.ssm_alpha.weight q8_0 -blk.29.ssm_beta.weight q8_0 +blk.29.ssm_beta_alpha.weight q8_0 blk.29.ssm_out.weight q8_0 -blk.30.attn_gate.weight q8_0 -blk.30.attn_qkv.weight q8_0 +blk.30.attn_qkv_gate.weight q8_0 blk.30.ffn_down.weight q8_0 blk.30.ffn_gate.weight q8_0 blk.30.ffn_up.weight q8_0 -blk.30.ssm_alpha.weight q8_0 -blk.30.ssm_beta.weight q8_0 +blk.30.ssm_beta_alpha.weight q8_0 blk.30.ssm_out.weight q8_0 blk.31.attn_k.weight q8_0 blk.31.attn_output.weight q8_0 @@ -2156,29 +2108,23 @@ blk.31.attn_v.weight q8_0 blk.31.ffn_down.weight q8_0 blk.31.ffn_gate.weight q8_0 blk.31.ffn_up.weight q8_0 -blk.32.attn_gate.weight q8_0 -blk.32.attn_qkv.weight q8_0 +blk.32.attn_qkv_gate.weight q8_0 blk.32.ffn_down.weight q8_0 blk.32.ffn_gate.weight q8_0 blk.32.ffn_up.weight q8_0 -blk.32.ssm_alpha.weight q8_0 -blk.32.ssm_beta.weight q8_0 +blk.32.ssm_beta_alpha.weight q8_0 blk.32.ssm_out.weight q8_0 -blk.33.attn_gate.weight q8_0 -blk.33.attn_qkv.weight q8_0 +blk.33.attn_qkv_gate.weight q8_0 blk.33.ffn_down.weight q8_0 blk.33.ffn_gate.weight q8_0 blk.33.ffn_up.weight q8_0 -blk.33.ssm_alpha.weight q8_0 -blk.33.ssm_beta.weight q8_0 +blk.33.ssm_beta_alpha.weight q8_0 blk.33.ssm_out.weight q8_0 -blk.34.attn_gate.weight q8_0 -blk.34.attn_qkv.weight q8_0 +blk.34.attn_qkv_gate.weight q8_0 blk.34.ffn_down.weight q8_0 blk.34.ffn_gate.weight q8_0 blk.34.ffn_up.weight q8_0 -blk.34.ssm_alpha.weight q8_0 -blk.34.ssm_beta.weight q8_0 +blk.34.ssm_beta_alpha.weight q8_0 blk.34.ssm_out.weight q8_0 blk.35.attn_k.weight q8_0 blk.35.attn_output.weight q8_0 @@ -2187,29 +2133,23 @@ blk.35.attn_v.weight q8_0 blk.35.ffn_down.weight q8_0 blk.35.ffn_gate.weight q8_0 blk.35.ffn_up.weight q8_0 -blk.36.attn_gate.weight q8_0 -blk.36.attn_qkv.weight q8_0 +blk.36.attn_qkv_gate.weight q8_0 blk.36.ffn_down.weight q8_0 blk.36.ffn_gate.weight q8_0 blk.36.ffn_up.weight q8_0 -blk.36.ssm_alpha.weight q8_0 -blk.36.ssm_beta.weight q8_0 +blk.36.ssm_beta_alpha.weight q8_0 blk.36.ssm_out.weight q8_0 -blk.37.attn_gate.weight q8_0 -blk.37.attn_qkv.weight q8_0 +blk.37.attn_qkv_gate.weight q8_0 blk.37.ffn_down.weight q8_0 blk.37.ffn_gate.weight q8_0 blk.37.ffn_up.weight q8_0 -blk.37.ssm_alpha.weight q8_0 -blk.37.ssm_beta.weight q8_0 +blk.37.ssm_beta_alpha.weight q8_0 blk.37.ssm_out.weight q8_0 -blk.38.attn_gate.weight q8_0 -blk.38.attn_qkv.weight q8_0 +blk.38.attn_qkv_gate.weight q8_0 blk.38.ffn_down.weight q8_0 blk.38.ffn_gate.weight q8_0 blk.38.ffn_up.weight q8_0 -blk.38.ssm_alpha.weight q8_0 -blk.38.ssm_beta.weight q8_0 +blk.38.ssm_beta_alpha.weight q8_0 blk.38.ssm_out.weight q8_0 blk.39.attn_k.weight q8_0 blk.39.attn_output.weight q8_0 @@ -2218,29 +2158,23 @@ blk.39.attn_v.weight q8_0 blk.39.ffn_down.weight q8_0 blk.39.ffn_gate.weight q8_0 blk.39.ffn_up.weight q8_0 -blk.40.attn_gate.weight q8_0 -blk.40.attn_qkv.weight q8_0 +blk.40.attn_qkv_gate.weight q8_0 blk.40.ffn_down.weight q8_0 blk.40.ffn_gate.weight q8_0 blk.40.ffn_up.weight q8_0 -blk.40.ssm_alpha.weight q8_0 -blk.40.ssm_beta.weight q8_0 +blk.40.ssm_beta_alpha.weight q8_0 blk.40.ssm_out.weight q8_0 -blk.41.attn_gate.weight q8_0 -blk.41.attn_qkv.weight q8_0 +blk.41.attn_qkv_gate.weight q8_0 blk.41.ffn_down.weight q8_0 blk.41.ffn_gate.weight q8_0 blk.41.ffn_up.weight q8_0 -blk.41.ssm_alpha.weight q8_0 -blk.41.ssm_beta.weight q8_0 +blk.41.ssm_beta_alpha.weight q8_0 blk.41.ssm_out.weight q8_0 -blk.42.attn_gate.weight q8_0 -blk.42.attn_qkv.weight q8_0 +blk.42.attn_qkv_gate.weight q8_0 blk.42.ffn_down.weight q8_0 blk.42.ffn_gate.weight q8_0 blk.42.ffn_up.weight q8_0 -blk.42.ssm_alpha.weight q8_0 -blk.42.ssm_beta.weight q8_0 +blk.42.ssm_beta_alpha.weight q8_0 blk.42.ssm_out.weight q8_0 blk.43.attn_k.weight q8_0 blk.43.attn_output.weight q8_0 @@ -2249,29 +2183,23 @@ blk.43.attn_v.weight q8_0 blk.43.ffn_down.weight q8_0 blk.43.ffn_gate.weight q8_0 blk.43.ffn_up.weight q8_0 -blk.44.attn_gate.weight q8_0 -blk.44.attn_qkv.weight q8_0 +blk.44.attn_qkv_gate.weight q8_0 blk.44.ffn_down.weight q8_0 blk.44.ffn_gate.weight q8_0 blk.44.ffn_up.weight q8_0 -blk.44.ssm_alpha.weight q8_0 -blk.44.ssm_beta.weight q8_0 +blk.44.ssm_beta_alpha.weight q8_0 blk.44.ssm_out.weight q8_0 -blk.45.attn_gate.weight q8_0 -blk.45.attn_qkv.weight q8_0 +blk.45.attn_qkv_gate.weight q8_0 blk.45.ffn_down.weight q8_0 blk.45.ffn_gate.weight q8_0 blk.45.ffn_up.weight q8_0 -blk.45.ssm_alpha.weight q8_0 -blk.45.ssm_beta.weight q8_0 +blk.45.ssm_beta_alpha.weight q8_0 blk.45.ssm_out.weight q8_0 -blk.46.attn_gate.weight q8_0 -blk.46.attn_qkv.weight q8_0 +blk.46.attn_qkv_gate.weight q8_0 blk.46.ffn_down.weight q8_0 blk.46.ffn_gate.weight q8_0 blk.46.ffn_up.weight q8_0 -blk.46.ssm_alpha.weight q8_0 -blk.46.ssm_beta.weight q8_0 +blk.46.ssm_beta_alpha.weight q8_0 blk.46.ssm_out.weight q8_0 blk.47.attn_k.weight q8_0 blk.47.attn_output.weight q8_0 @@ -2280,29 +2208,23 @@ blk.47.attn_v.weight q8_0 blk.47.ffn_down.weight q8_0 blk.47.ffn_gate.weight q8_0 blk.47.ffn_up.weight q8_0 -blk.48.attn_gate.weight q8_0 -blk.48.attn_qkv.weight q8_0 +blk.48.attn_qkv_gate.weight q8_0 blk.48.ffn_down.weight q8_0 blk.48.ffn_gate.weight q8_0 blk.48.ffn_up.weight q8_0 -blk.48.ssm_alpha.weight q8_0 -blk.48.ssm_beta.weight q8_0 +blk.48.ssm_beta_alpha.weight q8_0 blk.48.ssm_out.weight q8_0 -blk.49.attn_gate.weight q8_0 -blk.49.attn_qkv.weight q8_0 +blk.49.attn_qkv_gate.weight q8_0 blk.49.ffn_down.weight q8_0 blk.49.ffn_gate.weight q8_0 blk.49.ffn_up.weight q8_0 -blk.49.ssm_alpha.weight q8_0 -blk.49.ssm_beta.weight q8_0 +blk.49.ssm_beta_alpha.weight q8_0 blk.49.ssm_out.weight q8_0 -blk.50.attn_gate.weight q8_0 -blk.50.attn_qkv.weight q8_0 +blk.50.attn_qkv_gate.weight q8_0 blk.50.ffn_down.weight q8_0 blk.50.ffn_gate.weight q8_0 blk.50.ffn_up.weight q8_0 -blk.50.ssm_alpha.weight q8_0 -blk.50.ssm_beta.weight q8_0 +blk.50.ssm_beta_alpha.weight q8_0 blk.50.ssm_out.weight q8_0 blk.51.attn_k.weight q8_0 blk.51.attn_output.weight q8_0 @@ -2311,29 +2233,23 @@ blk.51.attn_v.weight q8_0 blk.51.ffn_down.weight q8_0 blk.51.ffn_gate.weight q8_0 blk.51.ffn_up.weight q8_0 -blk.52.attn_gate.weight q8_0 -blk.52.attn_qkv.weight q8_0 +blk.52.attn_qkv_gate.weight q8_0 blk.52.ffn_down.weight q8_0 blk.52.ffn_gate.weight q8_0 blk.52.ffn_up.weight q8_0 -blk.52.ssm_alpha.weight q8_0 -blk.52.ssm_beta.weight q8_0 +blk.52.ssm_beta_alpha.weight q8_0 blk.52.ssm_out.weight q8_0 -blk.53.attn_gate.weight q8_0 -blk.53.attn_qkv.weight q8_0 +blk.53.attn_qkv_gate.weight q8_0 blk.53.ffn_down.weight q8_0 blk.53.ffn_gate.weight q8_0 blk.53.ffn_up.weight q8_0 -blk.53.ssm_alpha.weight q8_0 -blk.53.ssm_beta.weight q8_0 +blk.53.ssm_beta_alpha.weight q8_0 blk.53.ssm_out.weight q8_0 -blk.54.attn_gate.weight q8_0 -blk.54.attn_qkv.weight q8_0 +blk.54.attn_qkv_gate.weight q8_0 blk.54.ffn_down.weight q8_0 blk.54.ffn_gate.weight q8_0 blk.54.ffn_up.weight q8_0 -blk.54.ssm_alpha.weight q8_0 -blk.54.ssm_beta.weight q8_0 +blk.54.ssm_beta_alpha.weight q8_0 blk.54.ssm_out.weight q8_0 blk.55.attn_k.weight q8_0 blk.55.attn_output.weight q8_0 @@ -2342,29 +2258,23 @@ blk.55.attn_v.weight q8_0 blk.55.ffn_down.weight q8_0 blk.55.ffn_gate.weight q8_0 blk.55.ffn_up.weight q8_0 -blk.56.attn_gate.weight q8_0 -blk.56.attn_qkv.weight q8_0 +blk.56.attn_qkv_gate.weight q8_0 blk.56.ffn_down.weight q8_0 blk.56.ffn_gate.weight q8_0 blk.56.ffn_up.weight q8_0 -blk.56.ssm_alpha.weight q8_0 -blk.56.ssm_beta.weight q8_0 +blk.56.ssm_beta_alpha.weight q8_0 blk.56.ssm_out.weight q8_0 -blk.57.attn_gate.weight q8_0 -blk.57.attn_qkv.weight q8_0 +blk.57.attn_qkv_gate.weight q8_0 blk.57.ffn_down.weight q8_0 blk.57.ffn_gate.weight q8_0 blk.57.ffn_up.weight q8_0 -blk.57.ssm_alpha.weight q8_0 -blk.57.ssm_beta.weight q8_0 +blk.57.ssm_beta_alpha.weight q8_0 blk.57.ssm_out.weight q8_0 -blk.58.attn_gate.weight q8_0 -blk.58.attn_qkv.weight q8_0 +blk.58.attn_qkv_gate.weight q8_0 blk.58.ffn_down.weight q8_0 blk.58.ffn_gate.weight q8_0 blk.58.ffn_up.weight q8_0 -blk.58.ssm_alpha.weight q8_0 -blk.58.ssm_beta.weight q8_0 +blk.58.ssm_beta_alpha.weight q8_0 blk.58.ssm_out.weight q8_0 blk.59.attn_k.weight q8_0 blk.59.attn_output.weight q8_0 @@ -2373,29 +2283,23 @@ blk.59.attn_v.weight q8_0 blk.59.ffn_down.weight q8_0 blk.59.ffn_gate.weight q8_0 blk.59.ffn_up.weight q8_0 -blk.60.attn_gate.weight q8_0 -blk.60.attn_qkv.weight q8_0 +blk.60.attn_qkv_gate.weight q8_0 blk.60.ffn_down.weight q8_0 blk.60.ffn_gate.weight q8_0 blk.60.ffn_up.weight q8_0 -blk.60.ssm_alpha.weight q8_0 -blk.60.ssm_beta.weight q8_0 +blk.60.ssm_beta_alpha.weight q8_0 blk.60.ssm_out.weight q8_0 -blk.61.attn_gate.weight q8_0 -blk.61.attn_qkv.weight q8_0 +blk.61.attn_qkv_gate.weight q8_0 blk.61.ffn_down.weight q8_0 blk.61.ffn_gate.weight q8_0 blk.61.ffn_up.weight q8_0 -blk.61.ssm_alpha.weight q8_0 -blk.61.ssm_beta.weight q8_0 +blk.61.ssm_beta_alpha.weight q8_0 blk.61.ssm_out.weight q8_0 -blk.62.attn_gate.weight q8_0 -blk.62.attn_qkv.weight q8_0 +blk.62.attn_qkv_gate.weight q8_0 blk.62.ffn_down.weight q8_0 blk.62.ffn_gate.weight q8_0 blk.62.ffn_up.weight q8_0 -blk.62.ssm_alpha.weight q8_0 -blk.62.ssm_beta.weight q8_0 +blk.62.ssm_beta_alpha.weight q8_0 blk.62.ssm_out.weight q8_0 blk.63.attn_k.weight q8_0 blk.63.attn_output.weight q8_0 From 969d7333172c522d6a60fffb8dd35288ce8df236 Mon Sep 17 00:00:00 2001 From: Aaron Teo Date: Mon, 23 Nov 2026 19:30:24 +0800 Subject: [PATCH 060/401] cmake: treat kleidiai files as vendored (#32605) * cmake: treat kleidiai files as vendored Signed-off-by: Aaron Teo * cmake: use quotes and semicolon separators Signed-off-by: Aaron Teo --------- Signed-off-by: Aaron Teo --- ggml/src/ggml-cpu/kleidiai/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt b/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt index b36cb6d3a9d9..dece531f87ab 100644 --- a/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt +++ b/ggml/src/ggml-cpu/kleidiai/CMakeLists.txt @@ -8,7 +8,7 @@ if (NOT TARGET kleidiai) endif() if (MSVC) - target_compile_options(kleidiai PRIVATE $<$:/WX->) + target_compile_options(kleidiai PRIVATE "$<$:/WX-;/w>") else() - target_compile_options(kleidiai PRIVATE $<$:-Wno-error>) + target_compile_options(kleidiai PRIVATE "$<$:-Wno-error;-w>") endif() From 4663f9ca8a97c525ba3d248711fa2b52050920ec Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 14:12:41 +0100 Subject: [PATCH 061/401] ui: smooth height transition for every collapsible (#32873) * ui: give every collapsible the smooth height transition Llama UI's Collapsible.Content now force-mounts the bits-ui content and renders the animated region the chat used to keep as CollapsibleRegion: height eases open and shut, and the body unmounts once the collapse is over. The chat's standalone regions use Collapsible.Root/Content, so the tool groups in settings, the tools menu and drawer and the terminal block animate like the rest. Assisted-by: Claude (Opus 5.5 Medium) * ui: keep collapsible spacing inside the content Collapsible.Content now stays in the layout while closed, so a margin on it left a gap under a closed MCP tools list, connection log or server info. The margin moves onto the content inside, as does the story's spacing. Assisted-by: Claude (Opus 5.5 Medium) --- .../content/CollapsibleContentBlock.svelte | 26 +++---- .../content/CollapsibleTerminalBlock.svelte | 10 +-- .../app/mcp/McpConnectionLogs.svelte | 4 +- .../McpServerCardToolsList.svelte | 4 +- .../components/app/mcp/McpServerInfo.svelte | 4 +- .../app/misc/CollapsibleSection.svelte | 10 ++- .../components/app/misc/GroupedList.svelte | 30 ++++---- .../chat/src/lib/components/app/misc/index.ts | 1 - .../ModelsManagerModelsTable.svelte | 28 +++---- .../SidebarNavigationConversationList.svelte | 73 ++++++++++--------- .../SidebarNavigationGroupSection.svelte | 60 +++++++-------- .../chat/src/lib/constants/ui.constants.ts | 5 +- .../collapsible-lazy-body.svelte.test.ts | 14 ++-- ui/lib/ui/package-lock.json | 4 +- ui/lib/ui/package.json | 2 +- .../ui/collapsible/collapsible-content.svelte | 16 +++- .../ui/collapsible/collapsible-region.svelte} | 26 +++++-- ui/lib/ui/src/lib/constants/ui.constants.ts | 3 + .../display/Collapsible.stories.svelte | 13 ++-- 19 files changed, 181 insertions(+), 152 deletions(-) rename ui/{apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte => lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte} (69%) diff --git a/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte b/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte index 89a0b36218ec..797a4f2fecee 100644 --- a/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/content/CollapsibleContentBlock.svelte @@ -2,7 +2,6 @@ import * as Collapsible from '@ggml-org/llama-ui/ui/collapsible'; import { cn } from '@ggml-org/llama-ui/utils'; import ChevronDown from '@lucide/svelte/icons/chevron-down'; - import CollapsibleRegion from '#lib/components/app/misc/CollapsibleRegion.svelte'; import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; import type { Snippet } from 'svelte'; import type { Component } from 'svelte'; @@ -157,23 +156,16 @@ {/if} {#if collapsible} - - - -
-
- {@render children()} -
+ + +
+
+ {@render children()}
- +
{/if} diff --git a/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte b/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte index 798a0ed204f5..ebfcb7c2f9bd 100644 --- a/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/content/CollapsibleTerminalBlock.svelte @@ -95,13 +95,9 @@ - - {#if open} -
- {@render children()} -
- {/if} +
+ {@render children()} +
diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte index 87efebf7a2e5..cff6fa0dbc3b 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpConnectionLogs.svelte @@ -48,9 +48,9 @@
- +
{#each logs as log (log.timestamp.getTime() + log.message)} {@const IconComponent = getMcpLogLevelIcon(log.level)} diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte index bc3631ddf28e..48846d3364bb 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerCard/McpServerCardToolsList.svelte @@ -31,8 +31,8 @@ {toolsCount} tools available · Show details - -
+ +
{#each tools as tool (tool.name)}
{tool.name} diff --git a/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte b/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte index 220e6c6d954f..e895d8ce0a7a 100644 --- a/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/mcp/McpServerInfo.svelte @@ -26,8 +26,8 @@ Server instructions - -

+ +

{instructions}

diff --git a/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte b/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte index 86d6cc2c2bbc..5963a36f79f3 100644 --- a/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte +++ b/ui/apps/chat/src/lib/components/app/misc/CollapsibleSection.svelte @@ -1,5 +1,5 @@ - + + + {#snippet child({ open, props })} + + {@render children?.()} + + {/snippet} + diff --git a/ui/apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte similarity index 69% rename from ui/apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte rename to ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte index 40809de45819..9910753395da 100644 --- a/ui/apps/chat/src/lib/components/app/misc/CollapsibleRegion.svelte +++ b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte @@ -1,16 +1,20 @@ -
+
{#if contentMounted}
- {@render children()} + {@render children?.()}
{/if}
@@ -80,4 +84,10 @@ overflow: clip; } } + + @media (prefers-reduced-motion: reduce) { + .collapsible-region { + transition: none; + } + } diff --git a/ui/lib/ui/src/lib/constants/ui.constants.ts b/ui/lib/ui/src/lib/constants/ui.constants.ts index ff1bde2c960f..9f538214100d 100644 --- a/ui/lib/ui/src/lib/constants/ui.constants.ts +++ b/ui/lib/ui/src/lib/constants/ui.constants.ts @@ -7,3 +7,6 @@ export const UI_DATA_ATTRS = { /** How close to the bottom (px) a streaming code block counts as at the bottom. */ export const SYNTAX_CODE_SCROLL_AT_BOTTOM_THRESHOLD_PX = 32; + +/** How long a collapsible's body takes to expand or collapse; matches the region's CSS transition. */ +export const COLLAPSIBLE_TRANSITION_MS = 200; diff --git a/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte b/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte index 2690a1f80c9a..0291f94140e0 100644 --- a/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte +++ b/ui/lib/ui/tests/stories/components/display/Collapsible.stories.svelte @@ -16,7 +16,7 @@ {#snippet section(open: boolean)} - +
Advanced sampling @@ -29,12 +29,15 @@
-
temperature 0.8
+
temperature 0.8
- -
top_p 0.95
+ + +
+
top_p 0.95
-
min_p 0.05
+
min_p 0.05
+
{/snippet} From 46f4da217419ecac95708600e0f6ebc4bdb91cfd Mon Sep 17 00:00:00 2001 From: thelittlefireman <5165783+thelittlefireman@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:17:15 +0100 Subject: [PATCH 062/401] ggml-cuda : handle zero blocks in few-row MMQ quantization (#32566) Assisted-by: ChatGPT (GPT-6) --- ggml/src/ggml-cuda/quantize.cu | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/quantize.cu b/ggml/src/ggml-cuda/quantize.cu index b37ab3d0afd4..23936c305610 100644 --- a/ggml/src/ggml-cuda/quantize.cu +++ b/ggml/src/ggml-cuda/quantize.cu @@ -607,13 +607,13 @@ static __device__ __forceinline__ void quantize_mmq_few_store(const float4 xi, i float amax = fmaxf(fmaxf(fabsf(xi.x), fabsf(xi.y)), fmaxf(fabsf(xi.z), fabsf(xi.w))); amax = warp_reduce_max<8>(amax); - const float d_inv = 127.0f / amax; + const float d_inv = amax == 0.0f ? 0.0f : 127.0f / amax; char4 q; q.x = roundf(xi.x*d_inv); q.y = roundf(xi.y*d_inv); q.z = roundf(xi.z*d_inv); q.w = roundf(xi.w*d_inv); - const float d = 1.0f / d_inv; + const float d = amax == 0.0f ? 0.0f : 1.0f / d_inv; // as in quantize_mmq_q8_1: the sum of the quantized values; the int warp_reduce_sum reduces the whole warp on Ampere+ [[maybe_unused]] float sum = 0.0f; From 03813c56e47f6cd7a9b9bc2ad8edcebed88ce342 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Mon, 23 Nov 2026 22:28:40 +0800 Subject: [PATCH 063/401] rpc : typed request helpers and a single validation step on the server (#32651) * rpc : typed request helpers and a single validation step on the server Client and server share one table (rpc_msg_types) that maps each fixed-size command to its request and response structs. The client sends them with dispatcher->call() and call_async(), the server serves them with rpc_serve(), so the per-command code in rpc_serve_client and at the call sites is gone and a wrong struct for a command does not compile. SET_TENSOR, SET_TENSOR_2D and GRAPH_COMPUTE get header structs, written with rpc_writer and parsed with a bounds-checked rpc_reader. The wire format is unchanged. Validation of client data is now in one place: - deserialize_tensor rejects what ggml_new_tensor would assert on (op range, ne[0] not a multiple of the block size, element count overflow) and computes the tensor size without overflow before the buffer check - rpc_check_region replaces the per-handler bounds checks and checks the request against the tensor size, which ggml_backend_tensor_set/get/memset assert on, so an in-buffer but out-of-tensor request no longer aborts - graph_compute builds the graph in one pass over the tensors, which the client sends in topological order: no recursion, and unknown or duplicate ids, duplicate nodes, sources sent after their users, compute nodes with unallocated operands and views outside their view_src buffer are rejected; a tensor may be its own source (ggml_cast) - GET_ALLOC_SIZE fails if a source tensor is invalid - a client-sized allocation that fails closes the connection instead of terminating the server * rpc : trim comments --- ggml/src/ggml-rpc/ggml-rpc.cpp | 1260 +++++++++++++------------------- 1 file changed, 513 insertions(+), 747 deletions(-) diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index dbd7dd467709..6197f01c285e 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -245,7 +246,8 @@ struct rpc_msg_graph_recompute_req { uint64_t uid; }; -struct rpc_msg_get_tensor_2d_req { +// GET_TENSOR_2D request and SET_TENSOR_2D header +struct rpc_msg_tensor_2d_req { rpc_tensor tensor; uint64_t offset; uint64_t size; @@ -274,8 +276,49 @@ struct rpc_msg_comm_free_req { uint32_t device; }; +// SET_TENSOR header, followed by the data +struct rpc_msg_set_tensor_req { + rpc_tensor tensor; + uint8_t cache_flag; + uint64_t offset; +}; + +// GRAPH_COMPUTE header, followed by the node ids and the tensors +struct rpc_msg_graph_compute_req { + uint32_t device; + uint64_t uid; + uint32_t n_nodes; +}; + #pragma pack(pop) +// request and response types of the commands with fixed-size requests, void when there is no response +template struct rpc_msg_types; + +#define RPC_MSG_TYPES(cmd, req_t, rsp_t) \ + template <> struct rpc_msg_types { using req = req_t; using rsp = rsp_t; } + +RPC_MSG_TYPES(RPC_CMD_ALLOC_BUFFER, rpc_msg_alloc_buffer_req, rpc_msg_alloc_buffer_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_ALIGNMENT, rpc_msg_get_alignment_req, rpc_msg_get_alignment_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_MAX_SIZE, rpc_msg_get_max_size_req, rpc_msg_get_max_size_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_ALLOC_SIZE, rpc_msg_get_alloc_size_req, rpc_msg_get_alloc_size_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_DEVICE_MEMORY, rpc_msg_get_device_memory_req, rpc_msg_get_device_memory_rsp); +RPC_MSG_TYPES(RPC_CMD_BUFFER_GET_BASE, rpc_msg_buffer_get_base_req, rpc_msg_buffer_get_base_rsp); +RPC_MSG_TYPES(RPC_CMD_FREE_BUFFER, rpc_msg_free_buffer_req, void); +RPC_MSG_TYPES(RPC_CMD_BUFFER_CLEAR, rpc_msg_buffer_clear_req, void); +RPC_MSG_TYPES(RPC_CMD_INIT_TENSOR, rpc_msg_init_tensor_req, void); +RPC_MSG_TYPES(RPC_CMD_MEMSET_TENSOR, rpc_msg_memset_tensor_req, void); +RPC_MSG_TYPES(RPC_CMD_SET_TENSOR_HASH, rpc_msg_set_tensor_hash_req, rpc_msg_set_tensor_hash_rsp); +RPC_MSG_TYPES(RPC_CMD_GET_TENSOR, rpc_msg_get_tensor_req, std::vector); +RPC_MSG_TYPES(RPC_CMD_GET_TENSOR_2D, rpc_msg_tensor_2d_req, std::vector); +RPC_MSG_TYPES(RPC_CMD_COPY_TENSOR, rpc_msg_copy_tensor_req, rpc_msg_copy_tensor_rsp); +RPC_MSG_TYPES(RPC_CMD_GRAPH_RECOMPUTE, rpc_msg_graph_recompute_req, void); +RPC_MSG_TYPES(RPC_CMD_COMM_INIT, rpc_msg_comm_init_req, rpc_msg_comm_init_rsp); +RPC_MSG_TYPES(RPC_CMD_COMM_ALLREDUCE, rpc_msg_comm_allreduce_req, void); +RPC_MSG_TYPES(RPC_CMD_COMM_FREE, rpc_msg_comm_free_req, void); + +#undef RPC_MSG_TYPES + // RPC data structures static ggml_guid_t ggml_backend_rpc_guid() { @@ -325,6 +368,59 @@ static uint64_t fnv_hash(const uint8_t * data, size_t len, uint64_t hash = 0xcbf return hash; } +// builds a variable-size request; the buffer must not change once queued +struct rpc_writer { + std::shared_ptr> buf = std::make_shared>(); + + explicit rpc_writer(size_t capacity) { buf->reserve(capacity); } + + void write_bytes(const void * data, size_t size) { + const uint8_t * p = (const uint8_t *) data; + buf->insert(buf->end(), p, p + size); + } + + template + void write(const T & value) { + static_assert(std::is_trivially_copyable_v); + write_bytes(&value, sizeof(value)); + } + + std::shared_ptr data() const { return std::shared_ptr(buf, buf->data()); } + size_t size() const { return buf->size(); } +}; + +// bounds-checked cursor over a received request +struct rpc_reader { + const uint8_t * ptr; + size_t left; + + explicit rpc_reader(const std::vector & input) : ptr(input.data()), left(input.size()) {} + + // n elements of elem_size bytes, returned in place: the pointer has no alignment guarantee + bool read_bytes(const uint8_t *& out, size_t n, size_t elem_size = 1) { + if (elem_size != 0 && n > left / elem_size) { + return false; + } + out = ptr; + ptr += n*elem_size; + left -= n*elem_size; + return true; + } + + template + bool read(T & value) { + static_assert(std::is_trivially_copyable_v); + const uint8_t * p; + if (!read_bytes(p, sizeof(T))) { + return false; + } + memcpy(&value, p, sizeof(T)); + return true; + } + + bool empty() const { return left == 0; } +}; + static bool send_msg(socket_ptr sock, const void * msg, size_t msg_size) { if (!sock->send_data(&msg_size, sizeof(msg_size))) { return false; @@ -520,6 +616,36 @@ class rpc_dispatcher { void send(enum rpc_cmd cmd, std::shared_ptr input, size_t input_size, const void * payload, size_t payload_size, void * output, size_t output_size); void send_async(enum rpc_cmd cmd, std::shared_ptr input, size_t input_size, void * output = nullptr, size_t output_size = 0); + // sends the request of `cmd` and waits for the response, if the command has one + template + typename rpc_msg_types::rsp call(const typename rpc_msg_types::req & request) { + using req_t = typename rpc_msg_types::req; + using rsp_t = typename rpc_msg_types::rsp; + auto input = std::make_shared(request); + if constexpr (std::is_void_v) { + send(cmd, input, sizeof(req_t), nullptr, 0, nullptr, 0); + } else { + static_assert(std::is_trivially_copyable_v, "variable-size responses are read into caller memory with send()"); + rsp_t response = {}; + send(cmd, input, sizeof(req_t), nullptr, 0, &response, sizeof(response)); + return response; + } + } + + // queues the request of `cmd`; *response, if given, is written when the command completes + template + void call_async(const typename rpc_msg_types::req & request, typename rpc_msg_types::rsp * response = nullptr) { + using req_t = typename rpc_msg_types::req; + using rsp_t = typename rpc_msg_types::rsp; + auto input = std::make_shared(request); + if constexpr (std::is_void_v) { + send_async(cmd, input, sizeof(req_t)); + } else { + static_assert(std::is_trivially_copyable_v, "variable-size responses are read into caller memory with send_async()"); + send_async(cmd, input, sizeof(req_t), response, sizeof(rsp_t)); + } + } + ggml_backend_event_t event_new(ggml_backend_dev_t dev); void event_free(ggml_backend_event_t event); void event_synchronize(ggml_backend_event_t event); @@ -741,10 +867,8 @@ static std::shared_ptr get_dispatcher(const std::string & endpoi static void ggml_backend_rpc_buffer_free_buffer(ggml_backend_buffer_t buffer) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - auto request = std::make_shared(); - request->remote_ptr = ctx->remote_ptr; - LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request->remote_ptr); - ctx->dispatcher->send(RPC_CMD_FREE_BUFFER, request, sizeof(*request), nullptr, 0, nullptr, 0); + LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, ctx->remote_ptr); + ctx->dispatcher->call({ ctx->remote_ptr }); delete ctx; } @@ -753,11 +877,8 @@ static void * ggml_backend_rpc_buffer_get_base(ggml_backend_buffer_t buffer) { if (ctx->base_ptr != nullptr) { return ctx->base_ptr; } - auto request = std::make_shared(); - request->remote_ptr = ctx->remote_ptr; LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, ctx->remote_ptr); - rpc_msg_buffer_get_base_rsp response; - ctx->dispatcher->send(RPC_CMD_BUFFER_GET_BASE, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = ctx->dispatcher->call({ ctx->remote_ptr }); ctx->base_ptr = reinterpret_cast(response.base_ptr); return ctx->base_ptr; } @@ -821,9 +942,7 @@ static enum ggml_status ggml_backend_rpc_buffer_init_tensor(ggml_backend_buffer_ // In particular, only quantized tensors need padding if (ggml_is_quantized(tensor->type) && (tensor->ne[0] % 512 != 0) && (tensor->view_src == nullptr)) { LOG_DBG2("[%s] tensor: %s\n", __func__, rpc_log_format_tensor(tensor).c_str()); - auto request = std::make_shared(); - request->tensor = serialize_tensor(tensor); - ctx->dispatcher->send(RPC_CMD_INIT_TENSOR, request, sizeof(*request), nullptr, 0, nullptr, 0); + ctx->dispatcher->call({ serialize_tensor(tensor) }); } return GGML_STATUS_SUCCESS; } @@ -831,29 +950,9 @@ static enum ggml_status ggml_backend_rpc_buffer_init_tensor(ggml_backend_buffer_ static void ggml_backend_rpc_buffer_memset_tensor( ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - auto request = std::make_shared(); - request->tensor = serialize_tensor(tensor); - request->offset = offset; - request->size = size; - request->value = value; LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s, value: %u\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str(), value); - ctx->dispatcher->send(RPC_CMD_MEMSET_TENSOR, request, sizeof(*request), nullptr, 0, nullptr, 0); -} - -// input serialization format: | rpc_tensor | cache_flag (1 byte) | offset (8 bytes) | data (size bytes) -// with size == 0 only the header is serialized and data is sent separately as payload -static std::shared_ptr serialize_set_tensor(const rpc_tensor & rpc_tensor, uint8_t cache_flag, uint64_t offset, const void * data, size_t size, size_t & input_size) { - input_size = sizeof(rpc_tensor) + sizeof(cache_flag) + sizeof(offset) + size; - uint8_t * input = new uint8_t[input_size]; - uint8_t * p = input; - memcpy(p, &rpc_tensor, sizeof(rpc_tensor)); p += sizeof(rpc_tensor); - memcpy(p, &cache_flag, sizeof(cache_flag)); p += sizeof(cache_flag); - memcpy(p, &offset, sizeof(offset)); p += sizeof(offset); - if (size > 0) { - memcpy(p, data, size); - } - return std::shared_ptr(input, std::default_delete()); + ctx->dispatcher->call({ serialize_tensor(tensor), offset, size, value }); } // the hash cache is meant for weights, so that a model reload can skip re-sending them. @@ -865,53 +964,48 @@ static bool rpc_use_hash_cache(const rpc_dispatcher & dispatcher, const ggml_ten return dispatcher.get_send_tensor_hash() && size > HASH_THRESHOLD && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS; } +// true if the server loaded the data from its cache; on a miss, cache_flag asks it to cache the data sent next +static bool rpc_set_tensor_from_cache(rpc_dispatcher & dispatcher, const ggml_tensor * tensor, const rpc_tensor & wire, + const void * data, size_t offset, size_t size, uint8_t & cache_flag) { + cache_flag = 0; + if (!rpc_use_hash_cache(dispatcher, tensor, size)) { + return false; + } + // TODO: make this async + const rpc_msg_set_tensor_hash_req request = { wire, offset, fnv_hash((const uint8_t *) data, size) }; + const auto response = dispatcher.call(request); + LOG_DBG2("[%s] tensor: %s, hash: 0x%" PRIx64 ", cache: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), + request.hash, response.result ? "hit" : "miss"); + cache_flag = response.result ? 0 : 1; + return response.result != 0; +} + static void ggml_backend_rpc_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - rpc_tensor rpc_tensor = serialize_tensor(tensor); - uint8_t cache_flag = 0; + const rpc_tensor wire = serialize_tensor(tensor); LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str()); - if (rpc_use_hash_cache(*ctx->dispatcher, tensor, size)) { - auto request = std::make_shared(); - request->tensor = rpc_tensor; - request->offset = offset; - request->hash = fnv_hash((const uint8_t*)data, size); - rpc_msg_set_tensor_hash_rsp response; - ctx->dispatcher->send(RPC_CMD_SET_TENSOR_HASH, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); - LOG_DBG2("[%s] tensor: %s, hash: 0x%" PRIx64 ", cache: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), - request->hash, response.result ? "hit" : "miss"); - if (response.result) { - // the server has the same data, no need to send it - return; - } - // the server has no cache entry for this tensor - ask it to save one - cache_flag = 1; + uint8_t cache_flag; + if (rpc_set_tensor_from_cache(*ctx->dispatcher, tensor, wire, data, offset, size, cache_flag)) { + return; } - size_t header_size; - auto header = serialize_set_tensor(rpc_tensor, cache_flag, offset, nullptr, 0, header_size); - ctx->dispatcher->send(RPC_CMD_SET_TENSOR, header, header_size, data, size, nullptr, 0); + // | rpc_msg_set_tensor_req | data (size bytes) | + auto request = std::make_shared(rpc_msg_set_tensor_req{ wire, cache_flag, offset }); + ctx->dispatcher->send(RPC_CMD_SET_TENSOR, request, sizeof(*request), data, size, nullptr, 0); } static void ggml_backend_rpc_buffer_set_tensor_2d(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - rpc_tensor rpc_tensor = serialize_tensor(tensor); LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s, n_copies: %zu, stride: %zu\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str(), n_copies, stride_tensor); - // input serialization format: | rpc_tensor | offset (8 bytes) | size (8 bytes) | n_copies (8 bytes) | stride (8 bytes) | data (size * n_copies bytes) | - size_t input_size = sizeof(rpc_tensor) + 4*sizeof(uint64_t) + size*n_copies; - uint8_t * input = new uint8_t[input_size](); - uint8_t * dest = input; - memcpy(dest, &rpc_tensor, sizeof(rpc_tensor)); - dest += sizeof(rpc_tensor); - uint64_t header[4] = { offset, size, n_copies, stride_tensor }; - memcpy(dest, header, sizeof(header)); - dest += sizeof(header); + // | rpc_msg_tensor_2d_req | data (size * n_copies bytes) | + rpc_writer writer(sizeof(rpc_msg_tensor_2d_req) + size*n_copies); + writer.write(rpc_msg_tensor_2d_req{ serialize_tensor(tensor), offset, size, n_copies, stride_tensor }); for (size_t i = 0; i < n_copies; i++) { - memcpy(dest + i*size, (const char *)data + i*stride_data, size); + writer.write_bytes((const char *) data + i*stride_data, size); } - std::shared_ptr input_ptr(input, std::default_delete()); - ctx->dispatcher->send(RPC_CMD_SET_TENSOR_2D, input_ptr, input_size, nullptr, 0, nullptr, 0); + ctx->dispatcher->send(RPC_CMD_SET_TENSOR_2D, writer.data(), writer.size(), nullptr, 0, nullptr, 0); } static void ggml_backend_rpc_buffer_get_tensor_2d(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, @@ -919,7 +1013,7 @@ static void ggml_backend_rpc_buffer_get_tensor_2d(ggml_backend_buffer_t buffer, ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s, n_copies: %zu, stride: %zu\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str(), n_copies, stride_tensor); - auto request = std::make_shared(); + auto request = std::make_shared(); request->tensor = serialize_tensor(tensor); request->offset = offset; request->size = size; @@ -960,23 +1054,15 @@ static bool ggml_backend_rpc_buffer_cpy_tensor(ggml_backend_buffer_t buffer, con } ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; LOG_DBG2("[%s] src: %s -> dst: %s\n", __func__, rpc_log_format_tensor(src).c_str(), rpc_log_format_tensor(dst).c_str()); - auto request = std::make_shared(); - request->src = serialize_tensor(src); - request->dst = serialize_tensor(dst); - rpc_msg_copy_tensor_rsp response; - ctx->dispatcher->send(RPC_CMD_COPY_TENSOR, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); - return response.result; + return ctx->dispatcher->call({ serialize_tensor(src), serialize_tensor(dst) }).result; } return false; } static void ggml_backend_rpc_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { ggml_backend_rpc_buffer_context * ctx = (ggml_backend_rpc_buffer_context *)buffer->context; - auto request = std::make_shared(); - request->remote_ptr = ctx->remote_ptr; - request->value = value; - LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, request->remote_ptr, request->value); - ctx->dispatcher->send(RPC_CMD_BUFFER_CLEAR, request, sizeof(*request), nullptr, 0, nullptr, 0); + LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, ctx->remote_ptr, value); + ctx->dispatcher->call({ ctx->remote_ptr, value }); } static ggml_backend_buffer_i ggml_backend_rpc_buffer_interface = { @@ -1003,19 +1089,14 @@ static const char * ggml_backend_rpc_buffer_type_name(ggml_backend_buffer_type_t static ggml_backend_buffer_t ggml_backend_rpc_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { ggml_backend_rpc_buffer_type_context * buft_ctx = (ggml_backend_rpc_buffer_type_context *)buft->context; - auto request = std::make_shared(); - request->device = buft_ctx->device; - request->size = size; - rpc_msg_alloc_buffer_rsp response; - auto dispatcher = get_dispatcher(buft_ctx->endpoint); if (dispatcher == nullptr) { return nullptr; } - dispatcher->send(RPC_CMD_ALLOC_BUFFER, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ buft_ctx->device, size }); if (response.remote_ptr != 0) { LOG_DBG("[%s] endpoint: %s, device: %u, size: %s -> remote_ptr: 0x%" PRIx64 ", remote_size: %s\n", - __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(request->size).c_str(), + __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(size).c_str(), response.remote_ptr, rpc_log_format_size(response.remote_size).c_str()); ggml_backend_buffer_t buffer = ggml_backend_buffer_init(buft, ggml_backend_rpc_buffer_interface, @@ -1024,16 +1105,13 @@ static ggml_backend_buffer_t ggml_backend_rpc_buffer_type_alloc_buffer(ggml_back return buffer; } else { LOG_WARN("[%s] endpoint: %s, device: %u, size: %s -> failed\n", - __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(request->size).c_str()); + __func__, buft_ctx->endpoint.c_str(), buft_ctx->device, rpc_log_format_size(size).c_str()); return nullptr; } } static size_t get_alignment(const std::shared_ptr & dispatcher, uint32_t device) { - auto request = std::make_shared(); - request->device = device; - rpc_msg_get_alignment_rsp response; - dispatcher->send(RPC_CMD_GET_ALIGNMENT, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ device }); LOG_DBG2("[%s] device: %u, alignment: %s\n", __func__, device, rpc_log_format_size(response.alignment).c_str()); return response.alignment; } @@ -1044,10 +1122,7 @@ static size_t ggml_backend_rpc_buffer_type_get_alignment(ggml_backend_buffer_typ } static size_t get_max_size(const std::shared_ptr & dispatcher, uint32_t device) { - auto request = std::make_shared(); - request->device = device; - rpc_msg_get_max_size_rsp response; - dispatcher->send(RPC_CMD_GET_MAX_SIZE, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ device }); LOG_DBG2("[%s] device: %u, max_size: %s\n", __func__, device, rpc_log_format_size(response.max_size).c_str()); return response.max_size; } @@ -1120,22 +1195,21 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty } } - auto request = std::make_shared(); - request->device = buft_ctx->device; - request->tensor = serialize_tensor(tensor); + rpc_msg_get_alloc_size_req request = {}; + request.device = buft_ctx->device; + request.tensor = serialize_tensor(tensor); // .get_alloc_size could be a function of the tensor's srcs, so we must serialize them as well for (int i = 0; i < GGML_MAX_SRC; i++) { - request->srcs[i] = serialize_tensor(tensor->src[i]); + request.srcs[i] = serialize_tensor(tensor->src[i]); } LOG_DBG2("[%s] cache miss: %s, querying server\n", __func__, rpc_log_format_tensor(tensor).c_str()); - rpc_msg_get_alloc_size_rsp response; auto dispatcher = get_dispatcher(buft_ctx->endpoint); if (dispatcher == nullptr) { return min_size; } - dispatcher->send(RPC_CMD_GET_ALLOC_SIZE, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call(request); { std::lock_guard lock(cache_mutex); @@ -1176,30 +1250,18 @@ static void ggml_backend_rpc_free(ggml_backend_t backend) { static void ggml_backend_rpc_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { ggml_backend_rpc_context * ctx = (ggml_backend_rpc_context *)backend->context; - rpc_tensor rpc_tensor = serialize_tensor(tensor); - uint8_t cache_flag = 0; + const rpc_tensor wire = serialize_tensor(tensor); LOG_DBG2("[%s] tensor: %s, offset: %zu, size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), offset, rpc_log_format_size(size).c_str()); - if (rpc_use_hash_cache(*ctx->dispatcher, tensor, size)) { - auto request = std::make_shared(); - request->tensor = rpc_tensor; - request->offset = offset; - request->hash = fnv_hash((const uint8_t*)data, size); - rpc_msg_set_tensor_hash_rsp response; - // TODO: make this async - ctx->dispatcher->send(RPC_CMD_SET_TENSOR_HASH, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); - LOG_DBG2("[%s] tensor: %s, hash: 0x%" PRIx64 ", cache: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), - request->hash, response.result ? "hit" : "miss"); - if (response.result) { - // the server has the same data, no need to send it - return; - } - // the server has no cache entry for this tensor - ask it to save one - cache_flag = 1; + uint8_t cache_flag; + if (rpc_set_tensor_from_cache(*ctx->dispatcher, tensor, wire, data, offset, size, cache_flag)) { + return; } - size_t input_size; - auto input = serialize_set_tensor(rpc_tensor, cache_flag, offset, data, size, input_size); - ctx->dispatcher->send_async(RPC_CMD_SET_TENSOR, input, input_size); + // the caller may reuse data once this returns, so it is copied into the request + rpc_writer writer(sizeof(rpc_msg_set_tensor_req) + size); + writer.write(rpc_msg_set_tensor_req{ wire, cache_flag, offset }); + writer.write_bytes(data, size); + ctx->dispatcher->send_async(RPC_CMD_SET_TENSOR, writer.data(), writer.size()); } static void ggml_backend_rpc_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { @@ -1218,6 +1280,7 @@ static void ggml_backend_rpc_synchronize(ggml_backend_t backend) { rpc_ctx->dispatcher->synchronize(); } +// adds the tensor after its sources and view_src, so that the server can build the graph in one pass static void add_tensor(ggml_tensor * tensor, const ggml_cgraph * cgraph, const rpc_dispatcher * dispatcher, std::vector & tensors, std::unordered_set & visited) { if (tensor == nullptr) { return; @@ -1238,34 +1301,23 @@ static void add_tensor(ggml_tensor * tensor, const ggml_cgraph * cgraph, const r tensors.push_back(result); } -static uint8_t * serialize_graph(uint32_t device, const ggml_cgraph * cgraph, const rpc_dispatcher * dispatcher, size_t * output_size) { - uint32_t n_nodes = cgraph->n_nodes; +// | rpc_msg_graph_compute_req | nodes (n_nodes * uint64_t) | n_tensors (uint32_t) | tensors (n_tensors * rpc_tensor) | +static rpc_writer serialize_graph(uint32_t device, const ggml_cgraph * cgraph, const rpc_dispatcher * dispatcher) { + const uint32_t n_nodes = cgraph->n_nodes; std::vector tensors; std::unordered_set visited; for (uint32_t i = 0; i < n_nodes; i++) { add_tensor(cgraph->nodes[i], cgraph, dispatcher, tensors, visited); } - // serialization format: - // | device (4 bytes) | uid (8 bytes) | n_nodes (4 bytes) | nodes (n_nodes * sizeof(uint64_t) | n_tensors (4 bytes) | tensors (n_tensors * sizeof(rpc_tensor)) | - uint32_t n_tensors = tensors.size(); - *output_size = 2*sizeof(uint32_t) + sizeof(uint64_t) + n_nodes * sizeof(uint64_t) + sizeof(uint32_t) + n_tensors * sizeof(rpc_tensor); - uint8_t * output = new uint8_t[*output_size](); - uint8_t * dest = output; - memcpy(dest, &device, sizeof(device)); - dest += sizeof(device); - memcpy(dest, &cgraph->uid, sizeof(cgraph->uid)); - dest += sizeof(cgraph->uid); - memcpy(dest, &n_nodes, sizeof(n_nodes)); - dest += sizeof(n_nodes); + const uint32_t n_tensors = tensors.size(); + rpc_writer writer(sizeof(rpc_msg_graph_compute_req) + n_nodes*sizeof(uint64_t) + sizeof(n_tensors) + n_tensors*sizeof(rpc_tensor)); + writer.write(rpc_msg_graph_compute_req{ device, cgraph->uid, n_nodes }); for (uint32_t i = 0; i < n_nodes; i++) { - memcpy(dest + i * sizeof(uint64_t), &cgraph->nodes[i], sizeof(uint64_t)); + writer.write(reinterpret_cast(cgraph->nodes[i])); } - dest += n_nodes * sizeof(uint64_t); - memcpy(dest, &n_tensors, sizeof(n_tensors)); - dest += sizeof(n_tensors); - rpc_tensor * out_tensors = (rpc_tensor *)dest; - memcpy(out_tensors, tensors.data(), n_tensors * sizeof(rpc_tensor)); - return output; + writer.write(n_tensors); + writer.write_bytes(tensors.data(), n_tensors*sizeof(rpc_tensor)); + return writer; } void rpc_dispatcher::graph_compute(uint32_t device, const ggml_cgraph * cgraph) { @@ -1275,10 +1327,7 @@ void rpc_dispatcher::graph_compute(uint32_t device, const ggml_cgraph * cgraph) bool reuse = cgraph->uid != 0 && device_graph_uids.count(cgraph->uid) > 0; LOG_DBG("[%s] device: %u, uid: %" PRIu64 ", n_nodes: %u, reuse: %s\n", __func__, device, cgraph->uid, cgraph->n_nodes, reuse ? "yes" : "no"); if (reuse) { - auto request = std::make_shared(); - request->device = device; - request->uid = cgraph->uid; - send_async(RPC_CMD_GRAPH_RECOMPUTE, request, sizeof(*request)); + call_async({ device, cgraph->uid }); } else { if (cgraph->uid != 0) { if (device_graph_uids.size() >= GRAPH_CACHE_MAX) { @@ -1288,11 +1337,9 @@ void rpc_dispatcher::graph_compute(uint32_t device, const ggml_cgraph * cgraph) } device_graph_uids.insert(cgraph->uid); } - size_t input_size = 0; - uint8_t * input = serialize_graph(device, cgraph, this, &input_size); - LOG_DBG2("[%s] serialized graph: %s\n", __func__, rpc_log_format_size(input_size).c_str()); - std::shared_ptr input_ptr(input, std::default_delete()); - send_async(RPC_CMD_GRAPH_COMPUTE, input_ptr, input_size); + rpc_writer writer = serialize_graph(device, cgraph, this); + LOG_DBG2("[%s] serialized graph: %s\n", __func__, rpc_log_format_size(writer.size()).c_str()); + send_async(RPC_CMD_GRAPH_COMPUTE, writer.data(), writer.size()); } } @@ -1413,10 +1460,7 @@ void ggml_backend_rpc_get_device_memory(const char * endpoint, uint32_t device, *total = 0; return; } - auto request = std::make_shared(); - request->device = device; - rpc_msg_get_device_memory_rsp response; - dispatcher->send(RPC_CMD_GET_DEVICE_MEMORY, request, sizeof(*request), nullptr, 0, &response, sizeof(response)); + const auto response = dispatcher->call({ device }); LOG_DBG2("[%s] device: %u, free: %s, total: %s\n", __func__, device, rpc_log_format_size(response.free_mem).c_str(), rpc_log_format_size(response.total_mem).c_str()); *free = response.free_mem; @@ -1425,6 +1469,92 @@ void ggml_backend_rpc_get_device_memory(const char * endpoint, uint32_t device, // RPC server-side implementation +// ggml_nbytes on the wire values, false if it overflows +static bool rpc_tensor_nbytes(const rpc_tensor & tensor, uint64_t & nbytes) { + nbytes = 0; + for (int i = 0; i < GGML_MAX_DIMS; i++) { + if (tensor.ne[i] == 0) { + return true; + } + } + // ne and nb are 32-bit on the wire, so every product fits in 64 bits and only the sums can overflow + const ggml_type type = (ggml_type) tensor.type; + const uint64_t blck_size = ggml_blck_size(type); + uint64_t n = blck_size == 1 ? ggml_type_size(type) + (uint64_t) (tensor.ne[0] - 1)*tensor.nb[0] + : (uint64_t) tensor.ne[0]*tensor.nb[0]/blck_size; + for (int i = 1; i < GGML_MAX_DIMS; i++) { + const uint64_t term = (uint64_t) (tensor.ne[i] - 1)*tensor.nb[i]; + if (term > UINT64_MAX - n) { + return false; + } + n += term; + } + if (n != (size_t) n) { + return false; + } + nbytes = n; + return true; +} + +static bool rpc_in_buffer(ggml_backend_buffer_t buffer, uint64_t addr, uint64_t size) { + const uint64_t base = (uint64_t) ggml_backend_buffer_get_base(buffer); + const uint64_t buf_size = (uint64_t) ggml_backend_buffer_get_size(buffer); + return addr >= base && addr - base <= buf_size && size <= buf_size - (addr - base); +} + +// checks [offset, offset + (n_copies - 1)*stride + size) against the tensor size, which ggml_backend_tensor_set/get assert on +static bool rpc_check_region(const char * func, const ggml_tensor * tensor, uint64_t offset, uint64_t size, + uint64_t n_copies = 1, uint64_t stride = 0) { + if (tensor == nullptr || tensor->buffer == nullptr || tensor->data == nullptr) { + LOG_ERROR("[%s] invalid or unallocated tensor\n", func); + return false; + } + // rows must not overlap, so size * n_copies <= span + if (n_copies == 0 || (n_copies > 1 && stride < size) || + (n_copies > 1 && stride != 0 && n_copies - 1 > (UINT64_MAX - size) / stride)) { + LOG_ERROR("[%s] invalid region: size=%" PRIu64 ", n_copies=%" PRIu64 ", stride=%" PRIu64 "\n", func, size, n_copies, stride); + return false; + } + const uint64_t span = (n_copies - 1)*stride + size; + const uint64_t nbytes = ggml_nbytes(tensor); + if (offset > nbytes || span > nbytes - offset) { + LOG_ERROR("[%s] region (offset=%" PRIu64 ", span=%" PRIu64 ") out of tensor '%s' bounds (%" PRIu64 ")\n", + func, offset, span, tensor->name, nbytes); + return false; + } + return true; +} + +// some backends address a view through view_src->data + view_offs, so that range must lie inside view_src's buffer +static bool rpc_check_view(const ggml_tensor * tensor) { + const ggml_tensor * view_src = tensor->view_src; + if (view_src == nullptr || tensor->buffer == nullptr || ggml_nbytes(tensor) == 0) { + return true; + } + if (view_src->buffer == nullptr) { + return false; + } + const uint64_t addr = (uint64_t) view_src->data; + return tensor->view_offs <= UINT64_MAX - addr && rpc_in_buffer(view_src->buffer, addr + tensor->view_offs, ggml_nbytes(tensor)); +} + +// a computed node and its sources must be allocated on this server +static bool rpc_check_node(const ggml_tensor * node) { + if (ggml_op_is_empty(node->op)) { + return true; + } + if (ggml_nelements(node) > 0 && node->buffer == nullptr) { + return false; + } + for (int i = 0; i < GGML_MAX_SRC; i++) { + const ggml_tensor * src = node->src[i]; + if (src != nullptr && ggml_nelements(src) > 0 && src->buffer == nullptr) { + return false; + } + } + return true; +} + class rpc_server { public: rpc_server(std::vector all_backends, const char * cache_dir) @@ -1446,7 +1576,7 @@ class rpc_server { bool set_tensor_2d(const std::vector & input); bool set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rpc_msg_set_tensor_hash_rsp & response); bool get_tensor(const rpc_msg_get_tensor_req & request, std::vector & response); - bool get_tensor_2d(const rpc_msg_get_tensor_2d_req & request, std::vector & response); + bool get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector & response); bool copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_copy_tensor_rsp & response); bool graph_compute(const std::vector & input); bool graph_recompute(const rpc_msg_graph_recompute_req & request); @@ -1469,10 +1599,6 @@ class rpc_server { static bool comm_bootstrap_exchange(void * user_data, const void * send_buf, void * recv_buf, size_t size); bool get_cached_file(uint64_t hash, std::vector & data); ggml_tensor * deserialize_tensor(struct ggml_context * ctx, const rpc_tensor * tensor); - ggml_tensor * create_node(uint64_t id, - struct ggml_context * ctx, - const std::unordered_map & tensor_ptrs, - std::unordered_map & tensor_map); // Per-device state for one communicator. @@ -1539,6 +1665,9 @@ bool rpc_server::get_alloc_size(const rpc_msg_get_alloc_size_req & request, rpc_ for (int i = 0; i < GGML_MAX_SRC; i++) { if (request.srcs[i].id != 0) { tensor->src[i] = deserialize_tensor(ctx, &request.srcs[i]); + if (tensor->src[i] == nullptr) { + return false; + } } } @@ -1658,29 +1787,7 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); - return false; - } - - const uint64_t tensor_size = ggml_nbytes(tensor); - if (request.offset > tensor_size || request.size > tensor_size - request.offset) { - LOG_ERROR("[%s] tensor region (offset=%" PRIu64 ", size=%" PRIu64 ") out of tensor bounds [0, %" PRIu64 ")\n", - __func__, request.offset, request.size, tensor_size); - return false; - } - - const uint64_t buffer_start = (uint64_t) ggml_backend_buffer_get_base(tensor->buffer); - const uint64_t buffer_size = ggml_backend_buffer_get_size(tensor->buffer); - if (request.tensor.data < buffer_start) { - LOG_ERROR("[%s] tensor data before buffer start\n", __func__); - return false; - } - const uint64_t data_offset = request.tensor.data - buffer_start; - if (data_offset > buffer_size || - request.offset > buffer_size - data_offset || - request.size > buffer_size - data_offset - request.offset) { - LOG_ERROR("[%s] tensor region out of buffer bounds\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } @@ -1691,52 +1798,54 @@ bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { return true; } +// rejects the values that ggml_new_tensor or the backends would assert on ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rpc_tensor * tensor) { - // Validate tensor type before using it - if (tensor->type >= GGML_TYPE_COUNT) { - LOG_ERROR("[%s] invalid tensor type received: %u\n", __func__, tensor->type); + if (tensor->type >= GGML_TYPE_COUNT || ggml_blck_size((ggml_type) tensor->type) == 0) { + LOG_ERROR("[%s] invalid tensor type: %u\n", __func__, tensor->type); return nullptr; } - - // Fix: Prevent division by zero if blck_size is 0 (e.g., deprecated types) - if (ggml_blck_size((enum ggml_type)tensor->type) == 0) { - LOG_ERROR("[%s] invalid tensor type received (blck_size is 0): %u\n", __func__, tensor->type); + const ggml_type type = (ggml_type) tensor->type; + if (tensor->op >= GGML_OP_COUNT) { + LOG_ERROR("[%s] invalid tensor op: %u\n", __func__, tensor->op); + return nullptr; + } + if (tensor->ne[0] % ggml_blck_size(type) != 0) { + LOG_ERROR("[%s] ne[0] = %u is not a multiple of the %s block size\n", __func__, tensor->ne[0], ggml_type_name(type)); + return nullptr; + } + // same element count check as ggml_new_tensor + uint64_t nelements = tensor->ne[0]; + for (int i = 1; i < GGML_MAX_DIMS; i++) { + if (tensor->ne[i] > 1) { + if ((uint64_t) INT64_MAX / tensor->ne[i] <= nelements) { + LOG_ERROR("[%s] element count overflows int64_t\n", __func__); + return nullptr; + } + nelements *= tensor->ne[i]; + } + } + uint64_t nbytes; + if (!rpc_tensor_nbytes(*tensor, nbytes)) { + LOG_ERROR("[%s] tensor size overflows\n", __func__); return nullptr; } - ggml_tensor * result = ggml_new_tensor_4d(ctx, (ggml_type) tensor->type, - tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]); - - // ggml_new_tensor_4d might fail if dimensions are invalid, although less likely to crash than invalid type - if (result == nullptr) { - LOG_ERROR("[%s] ggml_new_tensor_4d failed for type %u\n", __func__, tensor->type); + ggml_backend_buffer_t buffer = reinterpret_cast(tensor->buffer); + if (buffer && buffers.find(buffer) == buffers.end()) { + buffer = nullptr; + } + if (buffer && nbytes > 0 && !rpc_in_buffer(buffer, tensor->data, nbytes)) { + LOG_ERROR("[%s] tensor '%.*s' (op %s, type %s) data 0x%" PRIx64 " with size %" PRIu64 " out of buffer bounds " + "(base %p, size %zu)\n", __func__, (int) sizeof(tensor->name), tensor->name, ggml_op_name((ggml_op) tensor->op), + ggml_type_name(type), tensor->data, nbytes, ggml_backend_buffer_get_base(buffer), ggml_backend_buffer_get_size(buffer)); return nullptr; } + ggml_tensor * result = ggml_new_tensor_4d(ctx, type, tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->ne[3]); for (uint32_t i = 0; i < GGML_MAX_DIMS; i++) { result->nb[i] = tensor->nb[i]; } - result->buffer = reinterpret_cast(tensor->buffer); - if (result->buffer && buffers.find(result->buffer) == buffers.end()) { - result->buffer = nullptr; - } - - if (result->buffer && ggml_nelements(result) > 0) { - // require that the tensor data does not go beyond the buffer end - uint64_t tensor_size = (uint64_t) ggml_nbytes(result); - uint64_t buffer_start = (uint64_t) ggml_backend_buffer_get_base(result->buffer); - uint64_t buffer_size = (uint64_t) ggml_backend_buffer_get_size(result->buffer); - if (tensor->data + tensor_size < tensor->data || - tensor->data < buffer_start || tensor->data + tensor_size > buffer_start + buffer_size) { - LOG_ERROR("[%s] tensor '%s' (op %s, type %s, ne [%" PRId64 ", %" PRId64 ", %" PRId64 ", %" PRId64 "]) " - "data [0x%" PRIx64 ", 0x%" PRIx64 ") out of buffer bounds [0x%" PRIx64 ", 0x%" PRIx64 ")\n", - __func__, tensor->name, ggml_op_name((ggml_op) tensor->op), ggml_type_name(result->type), - result->ne[0], result->ne[1], result->ne[2], result->ne[3], - tensor->data, tensor->data + tensor_size, buffer_start, buffer_start + buffer_size); - return nullptr; - } - } - + result->buffer = buffer; result->op = (ggml_op) tensor->op; for (uint32_t i = 0; i < GGML_MAX_OP_PARAMS / sizeof(int32_t); i++) { result->op_params[i] = tensor->op_params[i]; @@ -1750,19 +1859,14 @@ ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rp bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { sync_all_backends(); - // serialization format: | rpc_tensor | cache_flag (1 byte) | offset (8 bytes) | data (size bytes) | - // only the header is read here, the data is streamed from the socket below - uint8_t cache_flag; - uint64_t offset; - uint8_t header[sizeof(rpc_tensor) + sizeof(cache_flag) + sizeof(offset)]; - const size_t header_size = sizeof(header); - if (input_size < header_size || !sock->recv_data(header, header_size)) { + // | rpc_msg_set_tensor_req | data (size bytes) | + rpc_msg_set_tensor_req request; + if (input_size < sizeof(request) || !sock->recv_data(&request, sizeof(request))) { return false; } - const rpc_tensor * in_tensor = (const rpc_tensor *)header; - memcpy(&cache_flag, header + sizeof(rpc_tensor), sizeof(cache_flag)); - memcpy(&offset, header + sizeof(rpc_tensor) + sizeof(cache_flag), sizeof(offset)); - const size_t size = input_size - header_size; + const uint8_t cache_flag = request.cache_flag; + const uint64_t offset = request.offset; + const size_t size = input_size - sizeof(request); struct ggml_init_params params { /*.mem_size =*/ ggml_tensor_overhead(), @@ -1772,27 +1876,14 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { ggml_context_ptr ctx_ptr { ggml_init(params) }; GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, in_tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + if (!rpc_check_region(__func__, tensor, offset, size)) { return false; } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, offset, rpc_log_format_size(size).c_str()); - // sanitize tensor->data - { - const size_t p0 = (size_t) ggml_backend_buffer_get_base(tensor->buffer); - const size_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (in_tensor->data + offset < p0 || in_tensor->data + offset >= p1 || size > (p1 - in_tensor->data - offset)) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", size=%zu) out of buffer bounds [0x%zx, 0x%zx)\n", - __func__, in_tensor->data, offset, size, p0, p1); - return false; - } - } - if (cache_dir && cache_flag) { // the whole data is needed to compute the hash std::vector data(size); @@ -1829,20 +1920,10 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { bool rpc_server::set_tensor_2d(const std::vector & input) { sync_all_backends(); - // serialization format: | rpc_tensor | offset (8 bytes) | size (8 bytes) | n_copies (8 bytes) | stride (8 bytes) | data (size * n_copies bytes) | - if (input.size() < sizeof(rpc_tensor) + 4*sizeof(uint64_t)) { - return false; - } - const rpc_tensor * in_tensor = (const rpc_tensor *)input.data(); - uint64_t header[4]; - memcpy(header, input.data() + sizeof(rpc_tensor), sizeof(header)); - const uint64_t offset = header[0]; - const uint64_t size = header[1]; - const uint64_t n_copies = header[2]; - const uint64_t stride = header[3]; - - const uint64_t data_size = input.size() - sizeof(rpc_tensor) - 4*sizeof(uint64_t); - if (n_copies == 0 || size == 0 || size > data_size / n_copies || size * n_copies != data_size) { + // | rpc_msg_tensor_2d_req | data (size * n_copies bytes) | + rpc_reader reader(input); + rpc_msg_tensor_2d_req request; + if (!reader.read(request)) { return false; } @@ -1854,38 +1935,20 @@ bool rpc_server::set_tensor_2d(const std::vector & input) { ggml_context_ptr ctx_ptr { ggml_init(params) }; GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, in_tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } - LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, n_copies: %" PRIu64 ", stride: %" PRIu64 "\n", - __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, offset, - rpc_log_format_size(size).c_str(), n_copies, stride); - - // sanitize tensor->data - { - if (stride != 0 && n_copies - 1 > (UINT64_MAX - size) / stride) { - return false; - } - const uint64_t span = (n_copies - 1)*stride + size; - const uint64_t p0 = (uint64_t) ggml_backend_buffer_get_base(tensor->buffer); - const uint64_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (in_tensor->data < p0 || in_tensor->data > p1 || offset > p1 - in_tensor->data || span > p1 - in_tensor->data - offset) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", span=%" PRIu64 ") out of buffer bounds [0x%" PRIx64 ", 0x%" PRIx64 ")\n", - __func__, in_tensor->data, offset, span, p0, p1); - return false; - } - if (offset > ggml_nbytes(tensor) || span > ggml_nbytes(tensor) - offset) { - LOG_ERROR("[%s] tensor write region (offset=%" PRIu64 ", span=%" PRIu64 ") out of tensor bounds (%zu)\n", - __func__, offset, span, ggml_nbytes(tensor)); - return false; - } + const uint8_t * data; + if (!reader.read_bytes(data, request.n_copies, request.size) || !reader.empty()) { + LOG_ERROR("[%s] data size does not match size * n_copies\n", __func__); + return false; } + LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, n_copies: %" PRIu64 ", stride: %" PRIu64 "\n", + __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, + rpc_log_format_size(request.size).c_str(), request.n_copies, request.stride); - const void * data = input.data() + sizeof(rpc_tensor) + 4*sizeof(uint64_t); - ggml_backend_tensor_set_2d(tensor, data, offset, size, n_copies, stride, size); + ggml_backend_tensor_set_2d(tensor, data, request.offset, request.size, request.n_copies, request.stride, request.size); return true; } @@ -1921,8 +1984,7 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, 0)) { return false; } @@ -1938,18 +2000,8 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, rpc_log_format_size(size).c_str(), request.hash); - // sanitize tensor->data - { - const size_t p0 = (size_t) ggml_backend_buffer_get_base(tensor->buffer); - const size_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (request.tensor.data + request.offset < p0 - || request.tensor.data + request.offset >= p1 - || size > (p1 - request.tensor.data - request.offset)) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", size=%zu, hash=0x%" PRIx64 ") out of buffer bounds [0x%zx, 0x%zx)\n", - __func__, request.tensor.data, request.offset, size, request.hash, p0, p1); - return false; - } + if (!rpc_check_region(__func__, tensor, request.offset, size)) { + return false; } ggml_backend_tensor_set(tensor, cached_file.data(), request.offset, size); response.result = 1; @@ -2004,34 +2056,19 @@ bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector< GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, rpc_log_format_size(request.size).c_str()); - // sanitize tensor->data - { - const size_t p0 = (size_t) ggml_backend_buffer_get_base(tensor->buffer); - const size_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (request.tensor.data + request.offset < p0 || - request.tensor.data + request.offset >= p1 || - request.size > (p1 - request.tensor.data - request.offset)) { - LOG_ERROR("[%s] requested tensor region (data=0x%" PRIx64 ", offset=%" PRIu64 ", size=%" PRIu64 ") out of buffer bounds [0x%zx, 0x%zx)\n", - __func__, request.tensor.data, request.offset, request.size, p0, p1); - return false; - } - } - response.resize(request.size, 0); ggml_backend_tensor_get(tensor, response.data(), request.offset, request.size); return true; } -bool rpc_server::get_tensor_2d(const rpc_msg_get_tensor_2d_req & request, std::vector & response) { +bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector & response) { sync_all_backends(); struct ggml_init_params params { /*.mem_size =*/ ggml_tensor_overhead(), @@ -2042,39 +2079,13 @@ bool rpc_server::get_tensor_2d(const rpc_msg_get_tensor_2d_req & request, std::v GGML_ASSERT(ctx_ptr != nullptr); ggml_context * ctx = ctx_ptr.get(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); - if (tensor == nullptr || tensor->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensor\n", __func__); + if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } LOG_DBG2("[%s] tensor: %s, buffer: %p, data: %p, offset: %" PRIu64 ", size: %s, n_copies: %" PRIu64 ", stride: %" PRIu64 "\n", __func__, rpc_log_format_tensor(tensor).c_str(), (void*)tensor->buffer, tensor->data, request.offset, rpc_log_format_size(request.size).c_str(), request.n_copies, request.stride); - // sanitize tensor->data - { - if (request.n_copies == 0 || request.size == 0 || request.size > UINT64_MAX / request.n_copies) { - return false; - } - if (request.stride != 0 && request.n_copies - 1 > (UINT64_MAX - request.size) / request.stride) { - return false; - } - const uint64_t span = (request.n_copies - 1)*request.stride + request.size; - const uint64_t p0 = (uint64_t) ggml_backend_buffer_get_base(tensor->buffer); - const uint64_t p1 = p0 + ggml_backend_buffer_get_size(tensor->buffer); - - if (request.tensor.data < p0 || request.tensor.data > p1 || request.offset > p1 - request.tensor.data || - span > p1 - request.tensor.data - request.offset) { - LOG_ERROR("[%s] tensor data region (data=0x%" PRIx64 ", offset=%" PRIu64 ", span=%" PRIu64 ") out of buffer bounds [0x%" PRIx64 ", 0x%" PRIx64 ")\n", - __func__, request.tensor.data, request.offset, span, p0, p1); - return false; - } - if (request.offset > ggml_nbytes(tensor) || span > ggml_nbytes(tensor) - request.offset) { - LOG_ERROR("[%s] tensor read region (offset=%" PRIu64 ", span=%" PRIu64 ") out of tensor bounds (%zu)\n", - __func__, request.offset, span, ggml_nbytes(tensor)); - return false; - } - } - response.resize(request.size * request.n_copies, 0); ggml_backend_tensor_get_2d(tensor, response.data(), request.offset, request.size, request.n_copies, request.stride, request.size); return true; @@ -2093,25 +2104,8 @@ bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_co ggml_tensor * src = deserialize_tensor(ctx, &request.src); ggml_tensor * dst = deserialize_tensor(ctx, &request.dst); - if (src == nullptr || dst == nullptr || src->buffer == nullptr || dst->buffer == nullptr) { - LOG_ERROR("[%s] error deserializing tensors\n", __func__); - return false; - } - - uint64_t src_size = (uint64_t) ggml_nbytes(src); - uint64_t dst_data = (uint64_t) dst->data; - uint64_t dst_base = (uint64_t) ggml_backend_buffer_get_base(dst->buffer); - uint64_t dst_buf_sz = (uint64_t) ggml_backend_buffer_get_size(dst->buffer); - - if (dst_data + src_size > dst_base + dst_buf_sz) { - LOG_ERROR("[%s] out-of-bounds write in rpc_server::copy_tensor:\n" - " write range : [0x%" PRIx64 ", 0x%" PRIx64 "]\n" - " buffer base: [0x%" PRIx64 ", 0x%" PRIx64 "]\n", - __func__, - dst_data, - dst_data + src_size, - dst_base, - dst_base + dst_buf_sz); + if (src == nullptr || src->buffer == nullptr || !rpc_check_region(__func__, dst, 0, ggml_nbytes(src))) { + LOG_ERROR("[%s] invalid tensors\n", __func__); return false; } @@ -2121,93 +2115,25 @@ bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_co return true; } -ggml_tensor * rpc_server::create_node(uint64_t id, - struct ggml_context * ctx, - const std::unordered_map & tensor_ptrs, - std::unordered_map & tensor_map) { - if (tensor_map.find(id) != tensor_map.end()) { - return tensor_map[id]; - } - // Safely find the tensor pointer - auto it_ptr = tensor_ptrs.find(id); - if (it_ptr == tensor_ptrs.end()) { - return nullptr; - } - const rpc_tensor * tensor = it_ptr->second; - - struct ggml_tensor * result = deserialize_tensor(ctx, tensor); - if (result == nullptr) { - return nullptr; - } - if (result->buffer == nullptr && result->data != nullptr) { - LOG_ERROR("[%s] invalid data ptr\n", __func__); - return nullptr; - } - tensor_map[id] = result; - for (int i = 0; i < GGML_MAX_SRC; i++) { - // Check if the source ID is 0 before calling create_node recursively - if (tensor->src[i] == 0) { - result->src[i] = nullptr; - } else { - result->src[i] = create_node(tensor->src[i], ctx, tensor_ptrs, tensor_map); - // If the recursive call failed for a non-zero ID, propagate the error - if (result->src[i] == nullptr) { - LOG_ERROR("[%s] failed to create source node %d (src_id=%" PRIu64 ") for node id %" PRIu64 "\n", - __func__, i, tensor->src[i], id); - // Must return nullptr to signal failure up the call stack - return nullptr; - } - } - } - - // Handle view_src similarly - if (tensor->view_src == 0) { - result->view_src = nullptr; - } else { - result->view_src = create_node(tensor->view_src, ctx, tensor_ptrs, tensor_map); - // If the recursive call failed for a non-zero ID, propagate the error - if (result->view_src == nullptr) { - LOG_ERROR("[%s] failed to create view_src node (view_src_id=%" PRIu64 ") for node id %" PRIu64 "\n", - __func__, tensor->view_src, id); - // Must return nullptr to signal failure up the call stack - return nullptr; - } - } - result->view_offs = tensor->view_offs; - return result; -} - bool rpc_server::graph_compute(const std::vector & input) { - // serialization format: - // | device (4 bytes) | uid (8 bytes) | n_nodes (4 bytes) | nodes (n_nodes * sizeof(uint64_t) | n_tensors (4 bytes) | tensors (n_tensors * sizeof(rpc_tensor)) | - if (input.size() < 2*sizeof(uint32_t) + sizeof(uint64_t)) { + // | rpc_msg_graph_compute_req | nodes (n_nodes * uint64_t) | n_tensors (uint32_t) | tensors (n_tensors * rpc_tensor) | + rpc_reader reader(input); + rpc_msg_graph_compute_req request; + const uint8_t * node_ids; + uint32_t n_tensors; + const uint8_t * tensor_data; + if (!reader.read(request) || !reader.read_bytes(node_ids, request.n_nodes, sizeof(uint64_t)) || + !reader.read(n_tensors) || !reader.read_bytes(tensor_data, n_tensors, sizeof(rpc_tensor)) || !reader.empty()) { + LOG_ERROR("[%s] malformed request\n", __func__); return false; } - const uint8_t * src = input.data(); - uint32_t device; - memcpy(&device, src, sizeof(device)); - src += sizeof(device); + const uint32_t device = request.device; + const uint64_t uid = request.uid; + const uint32_t n_nodes = request.n_nodes; if (device >= backends.size()) { return false; } - uint64_t uid; - memcpy(&uid, src, sizeof(uid)); - src += sizeof(uid); - uint32_t n_nodes; - memcpy(&n_nodes, src, sizeof(n_nodes)); - src += sizeof(n_nodes); - if (input.size() < 2*sizeof(uint32_t) + sizeof(uint64_t) + n_nodes*sizeof(uint64_t) + sizeof(uint32_t)) { - return false; - } - const uint64_t * nodes = (const uint64_t *)src; - src += n_nodes*sizeof(uint64_t); - uint32_t n_tensors; - memcpy(&n_tensors, src, sizeof(n_tensors)); - src += sizeof(n_tensors); - if (input.size() < 2*sizeof(uint32_t) + sizeof(uint64_t) + n_nodes*sizeof(uint64_t) + sizeof(uint32_t) + n_tensors*sizeof(rpc_tensor)) { - return false; - } - const rpc_tensor * tensors = (const rpc_tensor *)src; + const rpc_tensor * tensors = (const rpc_tensor *) tensor_data; LOG_DBG("[%s] device: %u, uid: %" PRIu64 ", n_nodes: %u, n_tensors: %u\n", __func__, device, uid, n_nodes, n_tensors); // graphs with uid == 0 are not cached, see GRAPH_CACHE_MAX for the eviction policy @@ -2233,32 +2159,78 @@ bool rpc_server::graph_compute(const std::vector & input) { ggml_context * ctx = ctx_ptr.get(); struct ggml_cgraph * graph = ggml_new_graph_custom(ctx, n_nodes, false); graph->n_nodes = n_nodes; - std::unordered_map tensor_ptrs; - tensor_ptrs.reserve(n_tensors); - for (uint32_t i = 0; i < n_tensors; i++) { - tensor_ptrs.emplace(tensors[i].id, &tensors[i]); - } - std::unordered_map tensor_map; - tensor_map.reserve(n_nodes); + // the compute itself is asynchronous, so building the graph is the only server-side cost // observable here - the round trip is timed on the client const auto t_deserialize = std::chrono::steady_clock::now(); + + // tensors come in topological order (see add_tensor), so the graph is built in one pass and a source sent + // after its user is rejected; a tensor may be its own source (ggml_cast) + std::unordered_map tensor_idx; + tensor_idx.reserve(n_tensors); + std::vector created(n_tensors); + auto lookup = [&](uint64_t id, ggml_tensor ** out) { + if (id == 0) { + *out = nullptr; + return true; + } + auto it = tensor_idx.find(id); + if (it == tensor_idx.end()) { + return false; + } + *out = created[it->second]; + return true; + }; + for (uint32_t i = 0; i < n_tensors; i++) { + const rpc_tensor & wire = tensors[i]; + ggml_tensor * result = deserialize_tensor(ctx, &wire); + if (result == nullptr) { + return false; + } + if (result->buffer == nullptr && result->data != nullptr) { + LOG_ERROR("[%s] tensor %u (id=%" PRIu64 ") has a data pointer but no buffer\n", __func__, i, wire.id); + return false; + } + if (wire.id == 0 || !tensor_idx.emplace(wire.id, i).second) { + LOG_ERROR("[%s] tensor %u has a zero or duplicate id %" PRIu64 "\n", __func__, i, wire.id); + return false; + } + created[i] = result; + bool found = lookup(wire.view_src, &result->view_src); + for (int s = 0; s < GGML_MAX_SRC; s++) { + found = found && lookup(wire.src[s], &result->src[s]); + } + if (!found) { + LOG_ERROR("[%s] tensor %u (id=%" PRIu64 ") references a tensor that was not sent before it\n", __func__, i, wire.id); + return false; + } + result->view_offs = wire.view_offs; + if (!rpc_check_view(result)) { + LOG_ERROR("[%s] view %u (id=%" PRIu64 ", view_offs=%" PRIu64 ") out of view_src bounds\n", __func__, i, wire.id, wire.view_offs); + return false; + } + } for (uint32_t i = 0; i < n_nodes; i++) { - int64_t id; - memcpy(&id, &nodes[i], sizeof(id)); - graph->nodes[i] = create_node(id, ctx, tensor_ptrs, tensor_map); - // Check if create_node failed for a *non-zero* ID. - // If id was 0, create_node returning nullptr is expected. - // If id was non-zero and create_node returned nullptr, it indicates a deserialization error. - if (graph->nodes[i] == nullptr && id != 0) { - LOG_ERROR("[%s] failed to create graph node %d (id=%" PRId64 ")\n", __func__, i, id); + uint64_t id; + memcpy(&id, node_ids + i*sizeof(id), sizeof(id)); + auto it = tensor_idx.find(id); + if (it == tensor_idx.end()) { + LOG_ERROR("[%s] graph node %u (id=%" PRIu64 ") is not in the tensor list\n", __func__, i, id); return false; } - if (graph->nodes[i] != nullptr) { - LOG_DBG3("[%s] node %u: id=%" PRId64 ", %s\n", __func__, i, id, rpc_log_format_tensor(graph->nodes[i]).c_str()); - const size_t hash_pos = ggml_hash_insert(&graph->visited_hash_set, graph->nodes[i]); - graph->use_counts[hash_pos] = tensor_ptrs.at(id)->use_count; + ggml_tensor * node = created[it->second]; + if (!rpc_check_node(node)) { + LOG_ERROR("[%s] graph node %u (%s) or one of its sources is not allocated on this server\n", __func__, i, node->name); + return false; + } + const size_t hash_pos = ggml_hash_insert(&graph->visited_hash_set, node); + if (hash_pos == GGML_HASHSET_ALREADY_EXISTS) { + LOG_ERROR("[%s] graph node %u (id=%" PRIu64 ") is a duplicate\n", __func__, i, id); + return false; } + graph->nodes[i] = node; + graph->use_counts[hash_pos] = tensors[it->second].use_count; + LOG_DBG3("[%s] node %u: id=%" PRIu64 ", %s\n", __func__, i, id, rpc_log_format_tensor(node).c_str()); } const std::chrono::duration deserialize_ms = std::chrono::steady_clock::now() - t_deserialize; @@ -2653,6 +2625,32 @@ rpc_server::~rpc_server() { } } +template +static bool rpc_send_rsp(const socket_ptr & sock, const T & response) { + return send_msg(sock, &response, sizeof(response)); +} + +static bool rpc_send_rsp(const socket_ptr & sock, const std::vector & response) { + return send_msg(sock, response.data(), response.size()); +} + +// receives the request of `cmd`, runs the handler and sends the response, if the command has one +template +static bool rpc_serve(const socket_ptr & sock, rpc_server & server, handler_t handler) { + using req_t = typename rpc_msg_types::req; + using rsp_t = typename rpc_msg_types::rsp; + req_t request; + if (!recv_msg(sock, &request, sizeof(request))) { + return false; + } + if constexpr (std::is_void_v) { + return (server.*handler)(request); + } else { + rsp_t response = {}; + return (server.*handler)(request, response) && rpc_send_rsp(sock, response); + } +} + static void rpc_serve_client(const std::vector & backends, const char * cache_dir, socket_ptr sock) { rpc_server server(backends, cache_dir); @@ -2693,6 +2691,7 @@ static void rpc_serve_client(const std::vector & backends, const // Activate transport upgrade using client's caps sock->update_caps(req.conn_caps); LOG_DBG("[%s] client connected, transport: %s\n", __func__, sock->transport_name()); + std::vector input; while (true) { if (!sock->recv_data(&cmd, 1)) { break; @@ -2703,280 +2702,52 @@ static void rpc_serve_client(const std::vector & backends, const break; } LOG_DBG2("[%s] %s\n", __func__, rpc_cmd_name((enum rpc_cmd)cmd)); - switch (cmd) { - case RPC_CMD_HELLO: { - // HELLO command is handled above - return; - } - case RPC_CMD_DEVICE_COUNT: { - if (!recv_msg(sock, nullptr, 0)) { - return; - } - rpc_msg_device_count_rsp response; - response.device_count = backends.size(); - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_ALLOC_BUFFER: { - rpc_msg_alloc_buffer_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_alloc_buffer_rsp response; - if (!server.alloc_buffer(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GET_ALLOC_SIZE: { - rpc_msg_get_alloc_size_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_alloc_size_rsp response; - if (!server.get_alloc_size(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GET_ALIGNMENT: { - rpc_msg_get_alignment_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_alignment_rsp response; - if (!server.get_alignment(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GET_MAX_SIZE: { - rpc_msg_get_max_size_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_max_size_rsp response; - if (!server.get_max_size(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_BUFFER_GET_BASE: { - rpc_msg_buffer_get_base_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_buffer_get_base_rsp response; - if (!server.buffer_get_base(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_FREE_BUFFER: { - rpc_msg_free_buffer_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.free_buffer(request)) { - return; - } - break; - } - case RPC_CMD_BUFFER_CLEAR: { - rpc_msg_buffer_clear_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.buffer_clear(request)) { - return; - } - break; - } - case RPC_CMD_MEMSET_TENSOR: { - rpc_msg_memset_tensor_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.memset_tensor(request)) { - return; - } - break; - } - case RPC_CMD_SET_TENSOR: { - uint64_t input_size; - if (!sock->recv_data(&input_size, sizeof(input_size))) { - return; - } - if (!server.set_tensor(sock, input_size)) { - return; - } - break; - } - case RPC_CMD_SET_TENSOR_2D: { - std::vector input; - if (!recv_msg(sock, input)) { - return; - } - if (!server.set_tensor_2d(input)) { - return; - } - break; - } - case RPC_CMD_GET_TENSOR_2D: { - rpc_msg_get_tensor_2d_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; + bool ok = false; + try { + switch (cmd) { + case RPC_CMD_DEVICE_COUNT: { + const rpc_msg_device_count_rsp response = { (uint32_t) backends.size() }; + ok = recv_msg(sock, nullptr, 0) && send_msg(sock, &response, sizeof(response)); + break; } - std::vector response; - if (!server.get_tensor_2d(request, response)) { - return; + case RPC_CMD_SET_TENSOR: { + // the handler streams the data from the socket + uint64_t input_size; + ok = sock->recv_data(&input_size, sizeof(input_size)) && server.set_tensor(sock, input_size); + break; } - if (!send_msg(sock, response.data(), response.size())) { - return; - } - break; - } - case RPC_CMD_SET_TENSOR_HASH: { - rpc_msg_set_tensor_hash_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_set_tensor_hash_rsp response; - if (!server.set_tensor_hash(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_INIT_TENSOR: { - rpc_msg_init_tensor_req request; - if (!recv_msg(sock, &request,sizeof(request))) { - return; - } - if (!server.init_tensor(request)) { - return; - } - break; - } - case RPC_CMD_GET_TENSOR: { - rpc_msg_get_tensor_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - std::vector response; - if (!server.get_tensor(request, response)) { - return; - } - if (!send_msg(sock, response.data(), response.size())) { - return; - } - break; - } - case RPC_CMD_COPY_TENSOR: { - rpc_msg_copy_tensor_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_copy_tensor_rsp response; - if (!server.copy_tensor(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_GRAPH_COMPUTE: { - std::vector input; - if (!recv_msg(sock, input)) { - return; - } - if (!server.graph_compute(input)) { - return; - } - break; - } - case RPC_CMD_GRAPH_RECOMPUTE: { - rpc_msg_graph_recompute_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.graph_recompute(request)) { - return; - } - break; - } - case RPC_CMD_COMM_INIT: { - rpc_msg_comm_init_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_comm_init_rsp response; - if (!server.comm_init(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - case RPC_CMD_COMM_ALLREDUCE: { - rpc_msg_comm_allreduce_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.comm_allreduce(request)) { - return; - } - break; - } - case RPC_CMD_COMM_FREE: { - rpc_msg_comm_free_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - if (!server.comm_free(request)) { - return; - } - break; - } - case RPC_CMD_GET_DEVICE_MEMORY: { - rpc_msg_get_device_memory_req request; - if (!recv_msg(sock, &request, sizeof(request))) { - return; - } - rpc_msg_get_device_memory_rsp response; - if (!server.get_device_memory(request, response)) { - return; - } - if (!send_msg(sock, &response, sizeof(response))) { - return; - } - break; - } - default: { - LOG_ERROR("Unhandled command: %s\n", rpc_cmd_name((enum rpc_cmd)cmd)); - return; + case RPC_CMD_SET_TENSOR_2D: ok = recv_msg(sock, input) && server.set_tensor_2d(input); break; + case RPC_CMD_GRAPH_COMPUTE: ok = recv_msg(sock, input) && server.graph_compute(input); break; + case RPC_CMD_ALLOC_BUFFER: ok = rpc_serve (sock, server, &rpc_server::alloc_buffer); break; + case RPC_CMD_GET_ALIGNMENT: ok = rpc_serve (sock, server, &rpc_server::get_alignment); break; + case RPC_CMD_GET_MAX_SIZE: ok = rpc_serve (sock, server, &rpc_server::get_max_size); break; + case RPC_CMD_GET_ALLOC_SIZE: ok = rpc_serve (sock, server, &rpc_server::get_alloc_size); break; + case RPC_CMD_GET_DEVICE_MEMORY: ok = rpc_serve(sock, server, &rpc_server::get_device_memory); break; + case RPC_CMD_BUFFER_GET_BASE: ok = rpc_serve (sock, server, &rpc_server::buffer_get_base); break; + case RPC_CMD_FREE_BUFFER: ok = rpc_serve (sock, server, &rpc_server::free_buffer); break; + case RPC_CMD_BUFFER_CLEAR: ok = rpc_serve (sock, server, &rpc_server::buffer_clear); break; + case RPC_CMD_INIT_TENSOR: ok = rpc_serve (sock, server, &rpc_server::init_tensor); break; + case RPC_CMD_MEMSET_TENSOR: ok = rpc_serve (sock, server, &rpc_server::memset_tensor); break; + case RPC_CMD_SET_TENSOR_HASH: ok = rpc_serve (sock, server, &rpc_server::set_tensor_hash); break; + case RPC_CMD_GET_TENSOR: ok = rpc_serve (sock, server, &rpc_server::get_tensor); break; + case RPC_CMD_GET_TENSOR_2D: ok = rpc_serve (sock, server, &rpc_server::get_tensor_2d); break; + case RPC_CMD_COPY_TENSOR: ok = rpc_serve (sock, server, &rpc_server::copy_tensor); break; + case RPC_CMD_GRAPH_RECOMPUTE: ok = rpc_serve (sock, server, &rpc_server::graph_recompute); break; + case RPC_CMD_COMM_INIT: ok = rpc_serve (sock, server, &rpc_server::comm_init); break; + case RPC_CMD_COMM_ALLREDUCE: ok = rpc_serve (sock, server, &rpc_server::comm_allreduce); break; + case RPC_CMD_COMM_FREE: ok = rpc_serve (sock, server, &rpc_server::comm_free); break; + default: + // HELLO is only valid as the first command + LOG_ERROR("Unhandled command: %s\n", rpc_cmd_name((enum rpc_cmd)cmd)); + break; } + } catch (const std::bad_alloc &) { + // allocation sizes come from the client, e.g. a large GET_TENSOR response + LOG_ERROR("[%s] %s: out of memory\n", __func__, rpc_cmd_name((enum rpc_cmd)cmd)); + ok = false; + } + if (!ok) { + return; } } } @@ -3213,9 +2984,7 @@ static void ggml_backend_rpc_comm_free(void * comm_ctx_v) { return; } for (const auto & rank : comm_ctx->ranks) { - auto request = std::make_shared(); - request->device = rank.device; - rank.dispatcher->send(RPC_CMD_COMM_FREE, request, sizeof(*request), nullptr, 0, nullptr, 0); + rank.dispatcher->call({ rank.device }); rank.dispatcher->busy_spin_release(); } delete comm_ctx; @@ -3264,15 +3033,15 @@ static void * ggml_backend_rpc_comm_init(ggml_backend_t * backends, size_t n_bac // until rank 1 has connected. std::vector responses(n_backends); for (size_t i = 0; i < n_backends; i++) { - auto request = std::make_shared(); - request->device = ranks[i].device; - request->rank = (uint32_t) i; - request->world = (uint32_t) n_backends; - request->port = comm_port; + rpc_msg_comm_init_req request = {}; + request.device = ranks[i].device; + request.rank = (uint32_t) i; + request.world = (uint32_t) n_backends; + request.port = comm_port; if (i > 0) { - memcpy(request->host, host0.c_str(), host0.size()); + memcpy(request.host, host0.c_str(), host0.size()); } - ranks[i].dispatcher->send_async(RPC_CMD_COMM_INIT, request, sizeof(*request), &responses[i], sizeof(responses[i])); + ranks[i].dispatcher->call_async(request, &responses[i]); } for (size_t i = 0; i < n_backends; i++) { ranks[i].dispatcher->synchronize(); @@ -3318,10 +3087,7 @@ static bool ggml_backend_rpc_comm_allreduce_tensor(void * comm_ctx_v, ggml_tenso } } for (size_t i = 0; i < n_ranks; i++) { - auto request = std::make_shared(); - request->device = comm_ctx->ranks[i].device; - request->tensor = serialize_tensor(tensors[i]); - comm_ctx->ranks[i].dispatcher->send_async(RPC_CMD_COMM_ALLREDUCE, request, sizeof(*request)); + comm_ctx->ranks[i].dispatcher->call_async({ comm_ctx->ranks[i].device, serialize_tensor(tensors[i]) }); } return true; } From 51fc2f90e23d4faf0f726f476a5452652b535145 Mon Sep 17 00:00:00 2001 From: Ravi Panchumarthy Date: Mon, 23 Nov 2026 06:29:20 -0800 Subject: [PATCH 064/401] ggml-openvino: CI fixes, new model support, fixes and improvements. (#32861) * ggml-openvino: keep the rope angle in f32 under the f16 inference hint * ggml-openvino: add a GGML_OP_ARGMAX translator * ggml-openvino: keep the token dim dynamic for a 2-D activation graph input * ggml-openvino: tolerate graph inputs and outputs with no backing storage * ggml-openvino: invalidate a cached graph when its output set changes * ggml-openvino: bound the compiled-model cache to N shapes instead of 1 * ggml-openvino: add GGML_OPENVINO_LOG_SUPPORTS_OP diagnostic * ggml-openvino: honour a node's dynamic-dim classification on non-split graphs too * ggml-openvino: fold consecutive SET_ROWS column writes into one scatter * ggml-openvino: keep the speculative decoding feature buffers in device memory * ggml-openvino: keep the fixed token count of static graph inputs for npu GDN In a static (NPU) graph that overwrites the fixed token count that get_graph_input_shape set just before, for example of inp_tokens, so the NPU graph got a dynamic token dimension. GATED_DELTA_NET models (Qwen3.5, Qwen3.6) then fail to translate: "GATED_DELTA_NET pad masking requires a static token dimension". Keep the change for dynamic graphs and the previous behaviour for static ones. * ggml-openvino: one output in the decode model of a static NPU pair The decode model of a static prefill/decode pair copied the compute params of the prefill graph, including output_len. With llama-perplexity the prefill graph has many outputs (128 at -c 256), so the decode model gathered 128 rows from its one token in the last layer. For a MoE model that layer then differs from the others and NPUW fails to lower its experts ("could not lower the isolated expert partition"). A decode step outputs one token; the model cache key already assumes it (decode_signature out=1). * ggml-openvino: fix gated delta net when v is a view with padded heads The GDN translator assumed v is a view of the fused qkv conv output with the heads packed in each row, and sliced H_v * S_v elements off that row. test-backend-ops now has padded_v cases, where v views a wider tensor and each head row is padded (nb[1] > S_v * nb[0]). The slice then read the padding, and the results were wrong on CPU and GPU. Take the packed path only when nb[1] == S_v * nb[0]. Any other view goes through the generic view resolution, which already returns [B, T, H_v, S_v], so the reshape of the packed case is skipped too. Model graphs build v with packed heads and keep the packed path. * ggml-openvino: make the f32 rope angle opt-in GGML_OPENVINO_ROPE_F32_ANGLE was on by default. It changes the RoPE of every model on every device, and it was validated on one model on the GPU only. On the CPU device, which computes in f32, its f16 round trip rounds cos and sin, and ROPE cases of test-backend-ops fail against the CPU backend. Turn it off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. Fix the comment that called the round trip a no-op on f32 paths. Document the variable, and the two diagnostics added with it (GGML_OPENVINO_LOG_SUPPORTS_OP, GGML_OPENVINO_DIAG_GRAPH_IO), in the dev_doc. * docs : add the Muse-Glimmer-30B DFlash memory limit and env var samples Muse-Glimmer-30B with a DFlash draft peaks at about 45 GB of RAM on an integrated GPU. Add it to the GPU limitations as a runnable sample, and add samples for GGML_OPENVINO_LOG_SUPPORTS_OP and GGML_OPENVINO_DIAG_GRAPH_IO to the dev_doc. * ggml-openvino: fix weight zero points, buffer extras and cache-key gaps A code review of ggml/src/ggml-openvino found these bugs: - Q4_1 weights: `extract_q4_1_data` packs two zero points per byte from a `parallel_for` over blocks, so two threads can write the same byte. - Zero points out of the u4/u8 range wrap around instead of saturating. gemma-4-E2B has 6 Q4_K sub-blocks with a zero point of 16 or more; 16 wrapped to 0. - `set_tensor` overwrote the extra that `init_tensor` created for a weight without deleting it. - The two buffer constructors had separate id counters, and the buffer id is part of the shared graph key. - A freed weight buffer stayed in the release registry, so a later release could madvise memory it no longer owned. - `GGML_OPENVINO_ROPE_F32_ANGLE` changes the graph but was not in the compiled-model cache key. - On NPU, group-128 requantization ignored the row width. A model whose rows are not a multiple of 128 failed to load its weights (SmolLM2-360M). - The static Split cache held a strong reference to the Split on its own input (a reference cycle) and ignored the output port. - `rms_norm` took op_case 3 for both a direct and a packed pre-scaled GDN output, so the packed one was not sliced. - Smaller items: static decode read `out_ids` even when it is empty; the static path aborted where the dynamic path returns an error; a damaged weights `.meta` hash threw from `std::stoull`; `extract_layer_from_name` threw on a non-numeric suffix; `GGML_OP_FILL` was registered twice. - ggml-quants.cpp: one `parallel_for` iteration per zero point byte for Q4_1; clamp zero points to [0, 15] (u4) and [0, 255] (u8). - ggml-openvino.cpp: `ggml_openvino_set_extra` replaces and deletes the old extra at every site; one id counter; `ggml_openvino_unregister_weight_buffer` in the buffer destructor; a failed KV re-allocation returns `GGML_STATUS_ALLOC_FAILED`. - model-cache.cpp: hash `GGML_OPENVINO_ROPE_F32_ANGLE`, cache version 9; `strtoull` for the `.meta` hash. - npu_quant_policy.cpp: Q4_0_128 falls back to Q4_0_C when `ne[0] % 128 != 0`. ggml-openvino-extra.cpp: the group-64 requant targets fall back to Q8_0_C when `ne[0] % 64 != 0`. - openvino/utils.cpp: the static Split cache uses a weak reference and the output port in its key, like the dynamic one. - rms_norm.cpp, ggml-decoder.cpp: op_case 5 for a packed pre-scaled GDN output. - utils.cpp: static decode writes 0 to `out_ids`; a compile after a weight release returns `GGML_STATUS_FAILED`. - ggml-decoder.cpp: `extract_layer_from_name` returns nullopt for a non-numeric suffix. - op_table.cpp/.h: remove the duplicate `GGML_OP_FILL`. * ggml-openvino: copy the decoder once per graph conversion `GgmlOvDecoder::visit_subgraph` made a full copy of the decoder for every node it visited. Translators only read the decoder, so one copy per walk is enough. Graph conversion time drops 12-24x (Qwen3.5-0.8B: 4.1 s to 0.17 s over the six graphs of a short run). - ggml-decoder.cpp: make one decoder copy before the node loop. - utils.cpp: `get_static_attention_size` takes the decoder by const reference and does not copy the compute params. * ggml-openvino: remove dead code and fix stale comments Code that nothing calls or registers, and comments that no longer match the code. No behavior change. - Remove `translate_gated_delta_net_ref`, `translate_solve_tri` (not registered), the unused `FuseToSDPA` pass, `add_rope_sin_cos`, `checksum`, `save_ggml_tensor_data_to_txt`, `non_cont_dim`, the unused templates in openvino/utils.h and the undefined `getCurrentTime` declaration. - ggml-decoder.cpp: drop the VIEW op_case tail that only ever set 0. - utils.cpp: drop a duplicate `entry->ptr` store and the always-false `!model_leafs.empty() == false` term. - `ggml_openvino_manual_gqa_enabled()` replaces two copies of the GGML_OPENVINO_MANUAL_GQA_ATTN default (flash_attn_ext.cpp and the cache key). - ggml-openvino.cpp: remove the SSM_CONV case whose comment said it stays on CPU (it runs on OpenVINO); fix the gemma3n reason text (not GPU-only) and two typos. * ggml-openvino: track dynamic dims through bailingmoe3's GDN views and conv state bailingmoe3 uses GATED_DELTA_NET views to expose its attention and state outputs. Preserve their dynamic dimensions in the decoder. - Assign the dynamic dimensions of the translated attention and state outputs to the corresponding GATED_DELTA_NET result VIEWs. - Count the convolution state slots using the rows spanned by the destination view. bailingmoe3 packs the q/k/v convolution states into a single row. - Preserve the tracked dynamic dimension in RESHAPE op case 0 when the reshape only adds a trailing size-1 dimension. * ggml-openvino: translate the per-key gate of GATED_DELTA_NET Ling-3.0-tiny (bailingmoe3) uses a gate per key dimension (kda), which the backend previously rejected, causing these layers to fall back to the CPU. - Use the fused GatedDeltaNet when the OpenVINO runtime and target device support a rank-4 gate. - Detect support once by compiling a one-node GatedDeltaNet with a rank-4 gate and checking the target device with query_model. Older runtimes reject this gate, and the CPU plugin does not support it. - Fall back to the reference loop when the fused path is unavailable. - Support a dynamic token count in the reference loop by using dynamic reshapes and deriving the trip count from the input shape. - Reject unsupported cases with a reason: padded chunks, recurrent caches, state snapshots, and the native state layout. The loop currently handles one state in the ggml layout. * ggml-openvino: Fix issue highlighted by tests * ggml-openvino: reject a padded permuted v in gated delta net supports_op rejected a permuted v only when src2 was the PERMUTE itself. With padded heads, v is a VIEW of the PERMUTE, so the check missed it and the per-key gate reference loop ran on a v layout it does not handle. Look through the VIEW so this case falls back like the other permuted v inputs. * ggml-openvino: write back intermediate nodes of op-test graphs The ADD_RMS_NORM_MUL op test checks the intermediate sum of its graph as well as the final output. compute_model_outputs() made a node a model output only when the graph does not consume all of it, so the sum was never written back and the test read uninitialised memory (28 failures on GPU and CPU). MUL_MAT_ID_SHARED, which checks its routed and shared results, failed the same way on CPU. Op-test graphs (the naive path) can read any node, so make every non-in-place node a model output there. Model graphs are unchanged. --------- Co-authored-by: Mustafa Cavus Co-authored-by: yzhou51 Co-authored-by: Sabnis, Omkar --- docs/backend/OPENVINO.md | 10 + .../dev_doc/OpenVINO-ENV-VARS.md | 9 + .../ggml-openvino/device/npu_quant_policy.cpp | 8 +- ggml/src/ggml-openvino/ggml-decoder.cpp | 115 ++++---- ggml/src/ggml-openvino/ggml-decoder.h | 17 ++ .../src/ggml-openvino/ggml-openvino-extra.cpp | 24 +- ggml/src/ggml-openvino/ggml-openvino-extra.h | 4 + ggml/src/ggml-openvino/ggml-openvino.cpp | 266 +++++++++++++----- ggml/src/ggml-openvino/ggml-quants.cpp | 33 ++- ggml/src/ggml-openvino/model-cache.cpp | 10 +- ggml/src/ggml-openvino/openvino/op/argmax.cpp | 51 ++++ .../openvino/op/flash_attn_ext.cpp | 8 +- .../openvino/op/gated_delta_net.cpp | 88 ++++-- .../src/ggml-openvino/openvino/op/reshape.cpp | 4 + .../ggml-openvino/openvino/op/rms_norm.cpp | 4 +- .../ggml-openvino/openvino/op/set_rows.cpp | 33 ++- .../ggml-openvino/openvino/op/solve_tri.cpp | 108 ------- ggml/src/ggml-openvino/openvino/op_table.cpp | 4 +- ggml/src/ggml-openvino/openvino/op_table.h | 5 +- .../openvino/pass/fuse_to_sdpa.cpp | 60 ---- .../openvino/pass/fuse_to_sdpa.h | 17 -- .../openvino/translate_session.cpp | 30 -- ggml/src/ggml-openvino/openvino/utils.cpp | 101 +++++-- ggml/src/ggml-openvino/openvino/utils.h | 34 --- ggml/src/ggml-openvino/utils.cpp | 188 +++++++------ ggml/src/ggml-openvino/utils.h | 45 ++- 26 files changed, 721 insertions(+), 555 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/op/argmax.cpp delete mode 100644 ggml/src/ggml-openvino/openvino/op/solve_tri.cpp delete mode 100644 ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp delete mode 100644 ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index a3a94aa16fb6..27c17c3eff8b 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -995,6 +995,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. **GPU-specific** +- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM): + + ```bash + export GGML_OPENVINO_DEVICE=GPU + export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs + export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts + mkdir -p $GGML_OPENVINO_SPILL_DIR + ./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md .gguf \ + --spec-type draft-dflash --spec-draft-n-max 4 + ``` - Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`): - `-sm tensor` is not supported. - Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy. diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index a43ac1d6af38..9d72ceacb912 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -13,6 +13,8 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO | `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. | | `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. | | `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. | +| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). | +| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When binding a tensor or `infer()` throws, log the graph key and the shapes of the model and the bound tensors. | | `GGML_OPENVINO_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. | | `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key is the node count and the names of the first and last nodes. Use it when two different graphs could share that key. | | `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and which layers use sliding-window attention, on an `ov-swa:` line at the WARN level. | @@ -29,6 +31,12 @@ GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \ # Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher). GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 +# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call +GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op + +# Graph key and tensor shapes when an inference throws +GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG + # NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD). export GGML_OPENVINO_DEVICE=NPU export GGML_OPENVINO_NPUW_DUMP_SUBS=YES @@ -74,6 +82,7 @@ These options are off by default. They are not validated for general use: some h | `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. | | `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | | `GGML_OPENVINO_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs that the scheduler splits between OpenVINO and another backend, and translate them as partial graphs, without the compiled model cache. By default every graph is treated as a complete model graph. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | +| `GGML_OPENVINO_ROPE_F32_ANGLE` | GPU | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model. On CPU, `test-backend-ops -o ROPE` fails with it. | | `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. | | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. | | `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. | diff --git a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp index 1f7343bba4c2..d29175ab0524 100644 --- a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp +++ b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp @@ -45,6 +45,10 @@ std::optional ggml_openvino_npu_token_embd_requant_type(const gg } std::optional ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor) { - GGML_UNUSED(tensor); - return ggml_openvino_get_npu_requant_type(); + const ExtraQuantType type = ggml_openvino_get_npu_requant_type(); + // a group must fit within a row + if (type == ExtraQuantType::Q4_0_128 && tensor->ne[0] % 128 != 0) { + return ExtraQuantType::Q4_0_C; + } + return type; } diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 519c35bc21a1..a9fac74b1ea1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -9,9 +9,11 @@ #include #include +#include #include #include #include +#include #include #include #include @@ -31,10 +33,27 @@ #include #include #include -#include #include #include +static std::set collect_graph_output_names(const ggml_cgraph * cgraph) { + std::set outputs; + for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) { + auto * node = cgraph->nodes[node_n]; + if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { + outputs.insert(node->name); + } + } + return outputs; +} + +bool GgmlOvDecoder::has_same_graph_io(const ggml_cgraph * cgraph) const { + if (m_built_output_names.empty()) { + return true; // no snapshot (naive / test decoders): nothing to compare against + } + return collect_graph_output_names(cgraph) == m_built_output_names; +} + GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, ModelParams & model_params, ComputeParams & compute_params, @@ -64,6 +83,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, validate_cgraph(); + m_built_output_names = collect_graph_output_names(cgraph); + set_input_output(); compute_node_dynamic_dims(); compute_model_inputs(); @@ -79,6 +100,7 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) { m_cgraph = cgraph; + m_built_output_names = collect_graph_output_names(cgraph); m_model_inputs.clear(); m_model_outputs.clear(); m_node_info_list.clear(); @@ -694,45 +716,6 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { op_case = 1; break; } - if (node->src[0]->op == GGML_OP_VIEW) { - auto * src = node->src[0]; - if (ggml_nelements(node) != ggml_nelements(src)) { - // throw std::runtime_error("Unsupported VIEW case"); - } - op_case = 0; - if (m_model_is_splitted && m_model_inputs.find(get_tensor_ov_name(m_cgraph, src)) != m_model_inputs.end()) { - op_case = 0; - } - } - { - auto * src = node->src[0]; - if (ggml_nelements(node) != ggml_nelements(src)) { - // Case 4: select one slice on src dim1 (via view offset), keep src dim2 as output dim1. - // Typical pattern: - // src: ne=[N, M, K, 1], nb=[b0, b1, b2, b3] - // dst: ne=[N, K, 1, 1], nb=[b0, b2, b3, b3] - if (node->ne[0] == src->ne[0] && node->ne[1] == src->ne[2] && node->ne[2] == 1 && - node->nb[0] == src->nb[0] && node->nb[1] == src->nb[2] && src->ne[1] > 1) { - op_case = 0; - break; - } - - // General case 3: shape differs from source (one or more dims) and is handled as VIEW slicing. - int diff_count = 0; - for (int i = 0; i < GGML_MAX_DIMS; i++) { - if (node->ne[i] != src->ne[i]) { - diff_count++; - } - // if node ne[i] > src ne[i], case = 0 - if (node->ne[i] > src->ne[i]) { - return 0; - } - } - if (diff_count >= 1) { - op_case = 0; - } - } - } break; } case GGML_OP_RMS_NORM: { @@ -744,7 +727,8 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { // pre-scaled, and the norm then scales its eps to match; 4: it is not. op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 4; } else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { - op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 2; + // packed [attn | state] output, sliced by the norm. 5: pre-scaled, as in 3; 2: not. + op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 5 : 2; } } break; @@ -897,13 +881,10 @@ std::optional extract_layer_from_name(const std::string & name) { return std::nullopt; } pos1 += 2; - size_t pos2 = name.find(' ', pos1); - if (pos2 == std::string::npos) { - pos2 = name.length(); + if (pos1 >= name.size() || !std::isdigit(static_cast(name[pos1]))) { + return std::nullopt; } - std::string layer_str = name.substr(pos1, pos2 - pos1); - int layer = std::stoi(layer_str); - return layer; + return std::stoi(name.substr(pos1)); } // Recover the sliding window width from ggml's own SWA mask. llama.cpp never passes n_swa to a @@ -1202,7 +1183,11 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr } ggml_tensor * cache_k = cache_k_view->src[0]; - int layer = extract_layer_from_name(cache_k->name).value(); + const auto layer_opt = extract_layer_from_name(cache_k->name); + if (!layer_opt) { + continue; + } + const int layer = *layer_opt; // Classified by the pre-pass above, which groups layers by mask tensor identity. The // mask NAME cannot be used: build_attn_inp_kq_mask() gives both masks the same name. @@ -1372,7 +1357,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback; } if (is_conv || is_gdn) { - compute_params.s_copy_active_slot_len = (int) dest_view->ne[1]; + // One cache row per active sequence: [conv_state_size, n_seqs] (qwen35) or, with the q/k/v conv + // states packed in one row, [d_conv - 1, d_inner, n_seqs] (bailingmoe3), so count the rows spanned. + compute_params.s_copy_active_slot_len = (int) ((ggml_nbytes(dest_view) + row_bytes - 1) / row_bytes); } } } @@ -1573,7 +1560,10 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, else { input_shape = ov::PartialShape{get_shape(input)}; } - if (dynamic_dim_index != -1 && m_model_is_splitted) { + // A static graph (NPU) keeps the fixed token count set above; only a split static graph, whose parts are + // fed by other backends, marks the dimension dynamic. Without this the token dimension of inp_tokens becomes + // dynamic in the NPU graph (and, for example, the GATED_DELTA_NET pad masking fails). + if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted)) { input_shape[3 - dynamic_dim_index] = -1; } if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE && @@ -1985,7 +1975,9 @@ void GgmlOvDecoder::compute_model_outputs() { } } } - if (input_use_count == cur_node_use_count) { + // op tests (the naive path) can read any node of the graph, e.g. the intermediate sum of a fused + // ADD + RMS_NORM + MUL, so every non-in-place node is a model output there + if (input_use_count == cur_node_use_count && (!m_naive || ::is_inplace_op(cur_node))) { cur_node = nullptr; } } @@ -2774,11 +2766,14 @@ size_t GgmlOvDecoder::get_output_op_offset(int node_idx) const { } void GgmlOvDecoder::visit_subgraph(std::function, int node_idx)> node_visitor) const { + // One copy for the whole walk: translators only read the decoder, and a copy per node costs a full + // copy of the node list for every node. + auto decoder = std::make_shared(*this); for (int node_idx = 0; node_idx < m_cgraph->n_nodes; node_idx++) { if (m_cgraph->nodes[node_idx]->op == GGML_OP_NONE) { continue; } - node_visitor(std::make_shared(*this), node_idx); + node_visitor(decoder, node_idx); } } @@ -2851,6 +2846,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[src] = 1; continue; } + if (is_inp_embd_2d(src, node)) { + m_node_dynamic_dims[src] = 1; + continue; + } self(self, src); } } @@ -2921,10 +2920,22 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1; break; } + + // A VIEW that does not change the shape is a pass-through for dynamic-dim purposes. + if (is_same_shape(node->src[0], node)) { + m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]]; + break; + } // Use stride-based matching: the stride of a VIEW dimension directly // encodes which source dimension it indexes into, so it uniquely // identifies the dynamic dim even when two dims share the same size. m_node_dynamic_dims[node] = -1; + if (!m_model_params.has_rs_rollback && node->src[0]->op == GGML_OP_GATED_DELTA_NET) { + // The GDN translator publishes attention [S_v, H_v, n_tokens, n_seqs] and state directly under these + // VIEW names (get_output_names), not the packed [attention | state] the strides describe. + m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1; + break; + } if (m_node_dynamic_dims[node->src[0]] != -1) { auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]]; auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx]; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 12b08cebce4b..39b3496e5669 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -458,6 +458,11 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { void update_io(ggml_cgraph * cgraph); bool is_bound_to(const ggml_cgraph * cgraph) const; + // Was this decoder built for a graph with the same OUTPUT set as `cgraph`? The cache key is + // only (n_nodes, first/last node name), which cannot see a change in which tensors are marked + // as outputs, and the compiled model's Results are fixed at compile time. + bool has_same_graph_io(const ggml_cgraph * cgraph) const; + static bool is_inp_tok(const ggml_tensor * tensor, const ggml_tensor * op) { return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op == GGML_OP_NONE; } @@ -501,6 +506,16 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { (tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY); } + // A 2-D float graph input feeding a matmul as src[1]. Speculative decoding hands the draft the + // target's hidden features this way ([n_embd, n_tokens], with no GET_ROWS lookup, so none of the + // other seeds match it) and the token count differs between the prompt pass and the shorter + // draft blocks, so its token dim must stay dynamic. + static bool is_inp_embd_2d(const ggml_tensor * tensor, const ggml_tensor * op) { + return (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->op == GGML_OP_NONE && + tensor->type == GGML_TYPE_F32 && tensor->ne[2] == 1 && tensor->ne[3] == 1 && + op->op == GGML_OP_MUL_MAT && tensor == op->src[1]; + } + static bool is_inp_mask(const ggml_tensor * tensor, const ggml_tensor * op) { return op->op == GGML_OP_CPY || (op->op == GGML_OP_FLASH_ATTN_EXT && tensor == op->src[3]) || (op->op == GGML_OP_SOFT_MAX && tensor == op->src[1]); @@ -759,6 +774,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { std::map> m_model_weights; std::map m_model_outputs; std::set m_model_output_names; + // The output set the compiled model was built from, for has_same_graph_io(). + std::set m_built_output_names; std::vector m_node_info_list; std::map m_node_dynamic_dims; std::set m_kvcache_4d; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 2537f8af3a31..7e6711dd88a0 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -179,6 +179,9 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_RELEASE_WEIGHTS", env_type::BOOL}, {"GGML_OPENVINO_REDUCE_COMPILE_MEM", env_type::BOOL}, {"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", env_type::BOOL}, + {"GGML_OPENVINO_LOG_SUPPORTS_OP", env_type::INT}, + {"GGML_OPENVINO_DIAG_GRAPH_IO", env_type::BOOL}, + {"GGML_OPENVINO_ROPE_F32_ANGLE", env_type::BOOL}, {"GGML_OPENVINO_LOG_SWA_LAYERS", env_type::BOOL}, {"GGML_OPENVINO_NATIVE_SOFTPLUS", env_type::BOOL}, {"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", env_type::BOOL}, @@ -543,6 +546,14 @@ std::string ggml_openvino_config_overrides_in_use() { return value ? std::string(name) + "=" + value : std::string(); } +bool ggml_openvino_manual_gqa_enabled() { + // set: a positive value enables it, 0 disables it; unset: on GPU only + if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) { + return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0; + } + return ggml_openvino_is_gpu(); +} + bool ggml_openvino_gdn_prescale_enabled() { // float value, so not getenv_int: "64.0" must enable it. Unset means on. const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_GDN_Q_SCALE", nullptr); @@ -997,6 +1008,10 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * const bool sym128_all = is_opt("q4_sym128_all"); const bool asym64_all = is_opt("q4_asym64_all"); const bool asym64 = is_opt("q4_asym64"); + // A group of 64 must fit within each row; other widths keep channel-wise INT8. + auto group64 = [tensor](ExtraQuantType type) { + return tensor->ne[0] % 64 == 0 ? type : ExtraQuantType::Q8_0_C; + }; // TODO: temporary workaround for slow GPU-plugin GatherMatmul prefill above 16 tokens. // Q4_1_64 experts let the plugin fuse the MoE into MOECompressed. @@ -1021,8 +1036,7 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * return tensor->ne[0] % 64 == 0 ? ExtraQuantType::Q4_1_64 : ExtraQuantType::Q8_0_C; } if (tensor->type == GGML_TYPE_Q5_0) { - //return ExtraQuantType::Q4_0_128; - return ExtraQuantType::Q4_0_64; + return group64(ExtraQuantType::Q4_0_64); } // MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side // equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4 @@ -1031,10 +1045,10 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * // (704/64 = 11) and 128 does not. if (tensor->ne[2] > 1 && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) { if (sym128 || sym128_all) { - return ExtraQuantType::Q4_0_64; + return group64(ExtraQuantType::Q4_0_64); } if (asym64 || asym64_all) { - return ExtraQuantType::Q4_1_64; + return group64(ExtraQuantType::Q4_1_64); } // TODO: temporary workaround for a known OpenVINO GPU-plugin bug -- remove once the // plugin computes grouped 8-bit GatherMatmulCompressed correctly. This costs accuracy @@ -1049,7 +1063,7 @@ std::optional ggml_openvino_get_requant_type(const ggml_tensor * // avoids the broken layout and restores correct output. // Opt out with GGML_OPENVINO_REQUANT_KQUANT=native. if (ggml_openvino_is_gpu() && !is_opt("native")) { - return ExtraQuantType::Q4_0_64; + return group64(ExtraQuantType::Q4_0_64); } } switch (tensor->type) { diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 406ac6d4cb5a..ca3227a41aab 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -206,6 +206,9 @@ bool ggml_openvino_is_gpu(); // Read n_seq_active and attention_size(_swa) from the KQ mask shape (off with GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK=1) bool ggml_openvino_shape_from_mask_enabled(); +// Manual GQA attention instead of SDPA (GGML_OPENVINO_MANUAL_GQA_ATTN, on GPU by default) +bool ggml_openvino_manual_gqa_enabled(); + // GDN q pre-scale for eligible graphs on the NPU static path. On by default; // GGML_OPENVINO_GDN_Q_SCALE=0 (or a negative or non-numeric value) turns it off. bool ggml_openvino_gdn_prescale_enabled(); @@ -242,6 +245,7 @@ size_t ggml_openvino_max_alloc_size(const std::string & device); // release: madvise(MADV_DONTNEED) all registered buffers, dropping their RSS. // released: true once release has run (used to fail-fast on post-release recompile). void ggml_openvino_register_weight_buffer(void * data, size_t size); +void ggml_openvino_unregister_weight_buffer(const void * data); void ggml_openvino_release_weight_buffers(); bool ggml_openvino_weight_buffers_released(); diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index bd49560d8e1e..b331349d1262 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -99,14 +100,20 @@ struct ggml_backend_openvino_buffer_context { // Used for re-allocation on device for kvcache void * data_prev = nullptr; + // data is in the weight buffer registry + bool weight_registered = false; + + // One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer + // buffer and an allocated buffer must never share one. + static size_t next_buffer_id() { + static std::atomic next_id{1}; + return next_id.fetch_add(1); + } ggml_backend_openvino_buffer_context(int device, void * external_data, size_t size) : device(device), name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)), - id([]() { - static std::atomic next_id{1}; - return next_id.fetch_add(1); - }()), + id(next_buffer_id()), data(external_data), size(size), is_remote(false), @@ -117,10 +124,7 @@ struct ggml_backend_openvino_buffer_context { ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false) : device(device), name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)), - id([]() { - static std::atomic next_id{1}; - return next_id.fetch_add(1); - }()), + id(next_buffer_id()), data(nullptr), size(size), is_remote(is_remote) { @@ -260,6 +264,10 @@ struct ggml_backend_openvino_buffer_context { delete pair.second; } tensor_extras.clear(); + // a later release must not madvise memory this buffer no longer owns + if (weight_registered) { + ggml_openvino_unregister_weight_buffer(data); + } if (kv_on_demand) { ggml_openvino_kv_storage_unregister(data, size); } @@ -321,6 +329,17 @@ void ggml_openvino_register_weight_buffer(void * data, size_t size) { reg.buffers.emplace_back(data, size); } +void ggml_openvino_unregister_weight_buffer(const void * data) { + if (data == nullptr) { + return; + } + auto & reg = ov_weight_registry(); + std::lock_guard lock(reg.mutex); + reg.buffers.erase(std::remove_if(reg.buffers.begin(), reg.buffers.end(), + [data](const std::pair & b) { return b.first == data; }), + reg.buffers.end()); +} + bool ggml_openvino_weight_buffers_released() { auto & reg = ov_weight_registry(); std::lock_guard lock(reg.mutex); @@ -378,21 +397,53 @@ static bool is_self_contained_mmap_enabled() { ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR"); } +// Stores extra as the tensor's extra, deleting the one it replaces +static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx, + ggml_tensor * tensor, + ggml_openvino_extra_base * extra) { + auto it = ctx->tensor_extras.find(tensor); + if (it != ctx->tensor_extras.end() && it->second != extra) { + delete it->second; + } + ctx->tensor_extras[tensor] = extra; + tensor->extra = extra; +} + +// Replaces the buffer's context with a new allocation of the same size and moves tensor->data to it. The old +// allocation is freed first, so the two never take memory at the same time. Returns false when the new +// allocation fails. +static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer, + ggml_backend_openvino_buffer_context *& ctx, + ggml_tensor * tensor, + bool is_remote, + bool lazy) { + const int device = ctx->device; + const size_t size = ctx->size; + const size_t offset = (char *) tensor->data - (char *) ctx->data; + delete ctx; + ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy); + buffer->context = ctx; + if (ctx->data == nullptr) { + return false; + } + tensor->data = (char *) ctx->data + offset; + return true; +} + static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) { // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name); ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context; - // Put kvcache on device memory for GPU (NPU memory is too small even for kvcache) - if (strncmp(tensor->name, "cache_", 6) == 0 && !ctx->is_remote && ggml_openvino_is_gpu() && - !is_stateful_enabled()) { + // Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative + // decoding feature buffers (llama_context::layer_inp_dev / h_nextn_dev): every graph reads or writes the whole + // buffer, so in host memory the plugin copies it to the device and back on every inference. + const bool is_device_state = strncmp(tensor->name, "cache_", 6) == 0 || + strcmp(tensor->name, "layer_inp_dev") == 0 || strcmp(tensor->name, "h_nextn_dev") == 0; + if (is_device_state && !ctx->is_remote && ggml_openvino_is_gpu() && !is_stateful_enabled()) { GGML_ASSERT(ctx->tensor_extras.empty()); - auto device = ctx->device; - auto size = ctx->size; - auto * data_prev = ctx->data; - delete ctx; - ctx = new ggml_backend_openvino_buffer_context(device, size, true); - buffer->context = ctx; - tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev); + if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false)) { + return GGML_STATUS_ALLOC_FAILED; + } } // On-demand NPU KV: swap the eagerly committed buffer for demand-zero memory at its first KV tensor @@ -401,14 +452,10 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu if (is_kv_tensor && tensor->view_src == nullptr && !ctx->is_remote && ggml_openvino_npu_kv_on_demand_enabled() && tensor->ne[2] == 1 && tensor->ne[3] == 1 && tensor->nb[1] == ggml_row_size(tensor->type, tensor->ne[0])) { if (!ctx->kv_on_demand && ctx->tensor_extras.empty() && tensor->data == ctx->data) { - auto device = ctx->device; - auto size = ctx->size; - auto * data_prev = ctx->data; - delete ctx; - ctx = new ggml_backend_openvino_buffer_context(device, size, false, true); + if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, false, true)) { + return GGML_STATUS_ALLOC_FAILED; + } ctx->kv_on_demand = true; - buffer->context = ctx; - tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev); } if (ctx->kv_on_demand) { ggml_openvino_kv_storage_register(tensor->data, tensor->nb[1], tensor->ne[1]); @@ -431,12 +478,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu if (ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra(tensor, ctx->is_remote, ggml_openvino_get_available_devices()[ctx->device])) { - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); return GGML_STATUS_SUCCESS; } } @@ -451,12 +493,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra( tensor, ctx->is_remote, ggml_openvino_get_available_devices()[ctx->device]); if (extra != nullptr) { - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); } } @@ -644,8 +681,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer // } } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); // Register the host buffer so its pages can be dropped after the GPU // plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS). @@ -661,6 +697,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer "multi-model runs."); } ggml_openvino_register_weight_buffer(ctx->data, ctx->size); + ctx->weight_registered = true; } if (!ctx->external_memory) { @@ -700,12 +737,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer return; } - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(ctx, tensor, extra); } } @@ -1087,15 +1119,8 @@ void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_ext GGML_ASSERT(tensor->buffer != nullptr); GGML_ASSERT(ggml_backend_buffer_is_openvino(tensor->buffer)); - auto * ctx = static_cast(tensor->buffer->context); - - auto it = ctx->tensor_extras.find(tensor); - if (it != ctx->tensor_extras.end()) { - delete it->second; - } - - ctx->tensor_extras[tensor] = extra; - tensor->extra = extra; + ggml_openvino_set_extra(static_cast(tensor->buffer->context), tensor, + extra); } bool ggml_backend_buft_is_openvino(ggml_backend_buffer_type_t buft) { @@ -1837,7 +1862,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { case GGML_OP_DIV: { // The GPU plugin can fuse broadcast DIV into the preceding FFN GEMM path // and produce infs for per-channel scale vectors. Keep those DIVs on CPU - // until the fused GPU kernel is reliable. (falied case llama-arch-test mpt) + // until the fused GPU kernel is reliable (failing case: test-llama-archs, mpt). // Only a weight divisor is such a scale; at one token an activation divisor has the same shape // (qwen2moe's shared-expert sigmoid, silu(x) / x). if (ggml_openvino_is_gpu() && op->src[1]->ne[0] == op->ne[0] && @@ -1898,11 +1923,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { memcpy(&max_bias, (const float *) op_params + 1, sizeof(float)); memcpy(&logit_softcap, (const float *) op_params + 2, sizeof(float)); - // Keep gemma3n flash-attn pattern on CPU for GPU runs to avoid - // accuracy drift in the OpenVINO path. Restrict by scale=1.0 to avoid - // affecting non-gemma3n models such as Llama-3.2. + // Keep gemma3n flash-attn pattern on CPU to avoid accuracy drift in the OpenVINO path. + // Restrict by scale=1.0 to avoid affecting non-gemma3n models such as Llama-3.2. if (fabsf(scale - 1.0f) < 1e-6f && is_gemma3n_flash_attn_pattern(op)) { - return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"}; + return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"}; } // K/V row lists (ggml_flash_attn_ext_rows) are not supported @@ -1948,7 +1972,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, "CPY with BF16 src[1] type is not supported"}; } if (ggml_openvino_is_npu() && (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16)) { - return {false, "CPY with BF16 is not supported is not supported on NPU"}; + return {false, "CPY with BF16 is not supported on NPU"}; } // CPY to a quantized destination (e.g. f32 -> q4_0) is numerically unstable with OpenVINO backend. if (ggml_is_quantized(op->type)) { @@ -2063,12 +2087,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { // return true; // } const char * reason = nullptr; - if (op->src[2]->op == GGML_OP_PERMUTE) { + // a VIEW of the PERMUTE (v with padded heads) is still a permuted v + const ggml_tensor * v_src = op->src[2]->op == GGML_OP_VIEW ? op->src[2]->src[0] : op->src[2]; + if (v_src->op == GGML_OP_PERMUTE) { reason = "GATED_DELTA_NET with PERMUTE src2 is not supported"; } - else if (op->src[3]->ne[0] != 1) { - // kda (per-key-dimension gating) not supported by fused GatedDeltaNet op - reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported"; + else if (op->src[3]->ne[0] != 1 && (op->op_params[0] > 1 || ggml_openvino_gdn_native_state_enabled()) && + !ov::frontend::ggml::op::gdn_per_key_gate_supported()) { + reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state " + "snapshots or the native state layout"; } else if (op->op_params[0] > 1) { if (ggml_openvino_is_static()) { @@ -2084,12 +2111,6 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } break; } - case GGML_OP_SSM_CONV: { - // qwen3next is numerically unstable with OpenVINO SSM_CONV. - // Keep this op on CPU until the OpenVINO implementation is fixed. - // return true; - break; - } case GGML_OP_SSM_SCAN: { // SelectiveSSM implements the Mamba-2 recurrence: scalar decay per head, one final state if (op->src[3]->ne[0] != 1) { @@ -2292,9 +2313,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg if (!supported) { return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " has no op translator"}; } - // if (has_view_op_input(op)) { - // return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " with view input is not supported"}; - // } if (op->src[1] == nullptr && op->src[0]->ne[0] % 2 != 0) { // triggers bug in ov gpu return {false, "GLU op with odd src0 ne[0] and null src1 is not supported"}; @@ -2347,16 +2365,114 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg return {true, ""}; } +// Report what supports_op() accepts and rejects, so a graph that silently falls back to another +// backend can be diagnosed. Every op rejected here becomes a graph split; if nothing is rejected, +// the whole graph runs on OpenVINO. +// +// Gated by GGML_OPENVINO_LOG_SUPPORTS_OP: +// 1 one summary at exit listing every distinct op kind and verdict -- start here +// 2 additionally log every individual call, with the tensor name and shape +// +// This wraps the decision function instead of instrumenting it, so all of its return paths are +// covered -- including the several that reject without logging a reason of their own, and any +// added later. +// +// The summary is reported at exit rather than on each op's first occurrence, because the earliest +// calls happen before the log handler emits anything: with level 2 the first line to actually +// appear already reads "call 1244". A first-occurrence line would therefore be silently dropped +// for exactly the ops that are only ever seen early. Counting is unaffected, so the summary is the +// reliable view; treat the level-2 stream as a sample, not a complete trace. +namespace { + +struct supports_op_tally { + std::mutex mutex; + // key: ":ok" / ":no" -> number of calls + std::map counts; + + // Report totals once, at exit. Registered lazily so a run with the knob off costs nothing. + // atexit runs while the ggml log callback is still valid, which static destruction does not + // guarantee. + void arm_summary() { + static std::once_flag armed; + std::call_once(armed, [] { + std::atexit([] { + auto & self = instance(); + std::lock_guard lock(self.mutex); + + size_t n_accept_kinds = 0; + size_t n_reject_kinds = 0; + GGML_LOG_WARN("ov-supports-op: ---- summary (distinct op kinds, with call counts) ----\n"); + for (const auto & [key, count] : self.counts) { + const bool ok = key.size() > 3 && key.compare(key.size() - 3, 3, ":ok") == 0; + ok ? ++n_accept_kinds : ++n_reject_kinds; + GGML_LOG_WARN("ov-supports-op: %-8s %-24s %zu call(s)\n", ok ? "ACCEPT" : "REJECT", + key.substr(0, key.size() - 3).c_str(), count); + } + if (n_reject_kinds == 0) { + GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, 0 rejected" + " -- every op was supported, so no split originated here\n", + n_accept_kinds); + } else { + GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, %zu REJECTED" + " -- each rejected kind forces a graph split\n", + n_accept_kinds, n_reject_kinds); + } + }); + }); + } + + static supports_op_tally & instance() { + static supports_op_tally tally; + return tally; + } +}; + +} // namespace + static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { auto res = ggml_backend_openvino_device_supports_op_impl(dev, op); - if (!res.is_supported) { + const bool supported = res.is_supported; + if (!supported) { static const bool log_unsupported = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_UNSUPPORTED_OPS") != 0; if (log_unsupported) { GGML_LOG_WARN("OpenVINO op unsupported: op '%s' (%s), type %s: %s\n", op->name, ggml_op_name(op->op), ggml_type_name(op->type), res.reason.c_str()); } } - return res.is_supported; + + static const int log_level = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SUPPORTS_OP"); + if (log_level <= 0) { + return supported; + } + + // Name the op the way ggml does: UNARY and GLU carry their real identity in a sub-enum, so + // logging only "UNARY" would merge SILU with everything else. + std::string op_desc = ggml_op_name(op->op); + if (op->op == GGML_OP_UNARY) { + op_desc += std::string("/") + ggml_unary_op_name(ggml_get_unary_op(op)); + } else if (op->op == GGML_OP_GLU) { + op_desc += std::string("/") + ggml_glu_op_name(ggml_get_glu_op(op)); + } + + // The scheduler calls supports_op() on every graph build and may do so from several threads, + // so the tally needs a lock. Keyed on op identity *and* verdict, because the same op can be + // accepted at one shape and rejected at another (e.g. a quantized 3-D src). + auto & tally = supports_op_tally::instance(); + tally.arm_summary(); + + size_t count; + { + std::lock_guard lock(tally.mutex); + count = ++tally.counts[op_desc + (supported ? ":ok" : ":no")]; + } + + if (log_level >= 2) { + GGML_LOG_WARN("ov-supports-op: %-6s %-22s name='%s' type=%s ne=[%ld,%ld,%ld,%ld] (call %zu)\n", + supported ? "ACCEPT" : "REJECT", op_desc.c_str(), op->name, ggml_type_name(op->type), + (long) op->ne[0], (long) op->ne[1], (long) op->ne[2], (long) op->ne[3], count); + } + + return supported; } static bool ggml_backend_openvino_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) { diff --git a/ggml/src/ggml-openvino/ggml-quants.cpp b/ggml/src/ggml-openvino/ggml-quants.cpp index 96b8da9be795..0c0501fec69e 100644 --- a/ggml/src/ggml-openvino/ggml-quants.cpp +++ b/ggml/src/ggml-openvino/ggml-quants.cpp @@ -154,19 +154,22 @@ void extract_q4_1_data(const ggml_tensor * tensor, }); } else { auto * zp = static_cast(zp_arr.data()); - ov::parallel_for(scales_arr.get_size(), [&](size_t i) { - float scale = static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block)))); - float min = static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2)))); - scales[i] = ov::float16(scale); - // zp = -min / scale (bias = min, so zp = -bias/scale) - uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::round(-min / scale) : 0; - // Pack two 4-bit zero points per byte - if (i % 2 == 0) { - zp[i / 2] = zp_val & 0x0F; // Lower nibble - } else { - zp[i / 2] |= (zp_val << 4); // Upper nibble + const size_t n_blocks = scales_arr.get_size(); + // One iteration per zero point byte: the two blocks that share a byte are packed together, so no two + // threads write the same byte. + ov::parallel_for((n_blocks + 1) / 2, [&](size_t pair) { + uint8_t packed = 0; + for (size_t i = 2 * pair; i < std::min(2 * pair + 2, n_blocks); i++) { + float scale = static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block)))); + float min = + static_cast(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2)))); + scales[i] = ov::float16(scale); + // zp = -min / scale (bias = min, so zp = -bias/scale), in the u4 range + const uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 15L) : 0; + packed |= (i % 2 == 0) ? zp_val : (uint8_t) (zp_val << 4); + unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16); } - unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16); + zp[pair] = packed; }); } } @@ -259,7 +262,7 @@ void extract_q5_1_data(const ggml_tensor * tensor, float min = static_cast(ov::float16::from_bits(read_u16(block + 2))); scales[i] = ov::float16(scale); // zp = -min / scale (dequant: (w - zp) * s == w*s + min) - zp[i] = (scale != 0.0f) ? (uint8_t) std::lround(-min / scale) : 0; + zp[i] = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 255L) : 0; unpack_block(block, weights + i * qk); }); } @@ -378,7 +381,9 @@ void extract_q4_k_data(const ggml_tensor * tensor, bias_f16[i * 8 + j] = ov::float16(-min_vals[j]); } else { // zp = min / scale (since bias = -min and zp = -bias/scale) - uint8_t zp_val = (scale_vals[j] != 0.0f) ? (uint8_t) std::round(min_vals[j] / scale_vals[j]) : 0; + uint8_t zp_val = (scale_vals[j] != 0.0f) ? + (uint8_t) std::clamp(std::lround(min_vals[j] / scale_vals[j]), 0L, 15L) : + 0; // Pack two 4-bit zero points per byte size_t idx = i * 8 + j; if (idx % 2 == 0) { diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 7bfa7ad08b11..d35168750da8 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -186,6 +186,7 @@ static const char * cache_settings[] = { "GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK", "GGML_OPENVINO_KV_SCATTER_ELEMENTS", "GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN", + "GGML_OPENVINO_ROPE_F32_ANGLE", }; void ggml_openvino_model_cache_init() { @@ -368,7 +369,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive. // Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter. // Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags. - h = fnv1a_u64(h, 8); + // Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in. + h = fnv1a_u64(h, 9); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); @@ -548,8 +550,10 @@ static bool read_weights_hash(const std::string & path, uint64_t & hash) { std::string key, value; while (meta >> key >> value) { if (key == "hash") { - hash = std::stoull(value, nullptr, 16); - return true; + // a damaged record counts as no hash, so the caller rewrites the file + char * end = nullptr; + hash = std::strtoull(value.c_str(), &end, 16); + return end != value.c_str() && *end == '\0'; } } return false; diff --git a/ggml/src/ggml-openvino/openvino/op/argmax.cpp b/ggml/src/ggml-openvino/openvino/op/argmax.cpp new file mode 100644 index 000000000000..441a6a5b2ad6 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/argmax.cpp @@ -0,0 +1,51 @@ +#include "../node_context.h" +#include "../op_table.h" +#include "../utils.h" +#include "ggml.h" + +#include +#include +#include +#include +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace op { + +// GGML_OP_ARGMAX: src0 is a matrix [ne0, ne1]; the result is a 1-D I32 tensor of ne1 entries +// holding, for each row, the index of the maximum along ne0. ggml shapes arrive reversed here, so +// ne0 is the last OV axis and ne1 is axis 2. TopK(k=1, axis=last, MAX) yields exactly that index, +// then reshape to the [1,1,1,ne1] layout the decoder expects for a 1-D ggml output. +// +// Note ggml's argmax returns the FIRST maximum on a tie, while TopK's tie-breaking is not specified +// to match. Ties on real logits are vanishingly rare and none were observed, but the two are not +// proven equivalent. +OutputVector translate_argmax(const NodeContext & context) { + num_inputs_check(context, 1, 1); + + auto input = process_view_input_new(context, 0); + + auto k = ov::op::v0::Constant::create(ov::element::i64, {}, {1}); + auto topk = std::make_shared(input, + k, + 3, + ov::op::v11::TopK::Mode::MAX, + ov::op::v11::TopK::SortType::SORT_VALUES, + context.get_output_type(), + false); + + // ne1 is the dynamic row count, so build the target shape at runtime. + auto leading = ov::op::v0::Constant::create(ov::element::i64, {3}, {1, 1, 1}); + auto rows = get_dimensions(input.get_node_shared_ptr(), {2}); + auto target_shape = std::make_shared(OutputVector{leading, rows}, 0); + auto res = std::make_shared(topk->output(1), target_shape, false); + + return rename_outputs_with_suffix({res}, context.get_name()); +} + +} // namespace op +} // namespace ggml +} // namespace frontend +} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp index 065e92fcddcc..b83c6de3a1c4 100644 --- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp +++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp @@ -182,13 +182,7 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) { // Manual GQA attention: enabled by default on GPU in stateless mode. // Set GGML_OPENVINO_MANUAL_GQA_ATTN to a positive value (e.g. 1) to force-enable, // or to 0 to force-disable. Unset falls back to the device-based default. - static const bool manual_gqa_enabled = []() { - const char * env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN"); - if (env != nullptr) { - return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0; - } - return ggml_openvino_is_gpu(); - }(); + static const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); // The manual path reshapes Q, K, V and the output with one head size; models whose K/V head sizes differ // from Q's (e.g. MLA) take the SDPA path. const bool same_head_size = k_shape[3] == q_shape[3] && v_shape[3] == q_shape[3]; diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index 9acf3effb9d0..6caafeb4fde8 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -52,6 +54,31 @@ namespace op { static OutputVector translate_gated_delta_net_ref(const NodeContext & context); +// Asks the device: OpenVINO releases without the per-key gate reject a rank-4 gate when the node is built, and a plugin +// without a per-key kernel leaves the node out of query_model +bool gdn_per_key_gate_supported() { + static const bool supported = [] { + ov::ParameterVector params; + auto param = [¶ms](const ov::Shape & shape) { + params.push_back(std::make_shared(ov::element::f32, shape)); + return params.back(); + }; + std::shared_ptr gdn; + try { + gdn = std::make_shared(param({1, 1, 1, 2}), param({1, 1, 1, 2}), + param({1, 1, 1, 2}), param({1, 1, 2, 2}), + param({1, 1, 1, 2}), param({1, 1, 1})); + } catch (const ov::Exception &) { + return false; + } + const auto model = std::make_shared(gdn->outputs(), params); + return ov_singleton_core() + .query_model(model, ggml_openvino_get_device_name()) + .count(gdn->get_friendly_name()) != 0; + }(); + return supported; +} + static bool match_gdn_l2_norm(const Output & normalized, Output & input, float & eps) { // Match the RMSNorm decomposition emitted by translate_rms_norm, followed by GGML SCALE. const auto scale = ov::as_type_ptr(normalized.get_node_shared_ptr()); @@ -379,23 +406,36 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v] auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k] - // Fused GatedDeltaNet op only supports scalar gate (kda=0). - // Fall back to reference implementation for per-key-dimension gating. - // if (kda) { - // return translate_gated_delta_net_ref(context); - // } + // g [B, T, H_v, 1] gates each head, g [B, T, H_v, S_k] each key dimension (kda); the fused op takes the latter as + // a rank-4 gate + const bool kda = context.get_input_shape(3)[3] != 1; + if (kda && !gdn_per_key_gate_supported()) { + // the reference loop reads and writes the state in the ggml layout, one state per call + FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 && + !ggml_openvino_gdn_native_state_enabled(), + "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 " + "gate for recurrent caches, state snapshots or the native state layout"); + return translate_gated_delta_net_ref(context); + } - // const int64_t B = v_shape[0]; - // const int64_t T = v_shape[1]; const int64_t H_v = v_shape[2]; const int64_t S_v = v_shape[3]; const int64_t H_k = q_shape[2]; const int64_t snapshot_count = context.get_output_op_params()[0]; - // const int64_t S_k = q_shape[3]; + + // v is usually a VIEW of the fused qkv conv output, [S_v, H_v, T, B] over [conv_dim, T, B], with the heads packed + // in each row: a Slice of that row plus the Reshape below. Any other view layout, e.g. heads padded to a wider + // row, goes through the generic view resolution, which already returns [B, T, H_v, S_v]. + const bool v_is_view = context.get_view_input_size(2) > 0; + bool v_packed_heads = true; + if (v_is_view) { + const auto v_stride = context.get_view_input_stride(2, 0); // OV order: v_stride[3] = nb[0], v_stride[2] = nb[1] + v_packed_heads = v_stride.size() == 4 && v_stride[2] == (size_t) S_v * v_stride[3]; + } auto q = context.get_input(0); auto k = context.get_input(1); - auto v = process_view_input(context, 2, H_v * S_v, 3); + auto v = v_packed_heads ? process_view_input(context, 2, H_v * S_v, 3) : process_view_input_new(context, 2); auto g = context.get_input(3); auto beta = context.get_input(4); auto state = context.get_input(5); @@ -424,7 +464,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto k = std::make_shared(k, repeats); } - if (context.get_view_input_size(2)) { + if (v_is_view && v_packed_heads) { // Same as l2_norm case 1 v = std::make_shared(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0})); auto v_shape = context.get_input_shape(2).to_shape(); @@ -443,7 +483,9 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto state = std::make_shared(state, state_perm); } - g = std::make_shared(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + if (!kda) { + g = std::make_shared(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + } beta = std::make_shared(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); if (context.has_input("chunk_valid_len")) { @@ -453,7 +495,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto // state equal to the state after the last real token. Attention output at those positions // is garbage but never read. const auto & g_ps = g.get_partial_shape(); - FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps.rank().get_length() == 3 && g_ps[1].is_static(), + FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps[1].is_static(), "GATED_DELTA_NET pad masking requires a static token dimension"); const int64_t n_tokens = g_ps[1].get_length(); std::vector positions(n_tokens); @@ -464,8 +506,12 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto auto mask = std::make_shared( std::make_shared(valid, g.get_element_type()), ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector{0, 2})); - g = std::make_shared(g, mask); beta = std::make_shared(beta, mask); + if (kda) { + mask = std::make_shared(mask, + ov::op::v0::Constant::create(ov::element::i64, {1}, {3})); + } + g = std::make_shared(g, mask); } // std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape() @@ -540,6 +586,8 @@ OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, co static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { num_inputs_check(context, 6, 6); + FRONT_END_OP_CONVERSION_CHECK(!context.has_input("chunk_valid_len"), + "GATED_DELTA_NET reference loop does not support padded prefill chunks"); // Inputs (OV shapes are reversed from ggml): // ggml: q[S_k, H_k, T, B], k[S_k, H_k, T, B], v[S_v, H_v, T, B] @@ -559,8 +607,8 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k] auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v] + // The token count T is dynamic: shapes below use -1 for it and the loop runs once per input token. const int64_t B = v_shape[0]; - const int64_t T = v_shape[1]; const int64_t H_v = v_shape[2]; const int64_t S_v = v_shape[3]; const int64_t H_k = q_shape[2]; @@ -599,14 +647,14 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { auto q_transposed = std::make_shared(q_bcast, perm_5d); auto k_transposed = std::make_shared(k_bcast, perm_5d); - auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, T, S_v}); + auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, -1, S_v}); q_bh = std::make_shared(q_transposed, new_shape, false); k_bh = std::make_shared(k_transposed, new_shape, false); } // Merge batch and head dims: [B*H_v, T, S_v] auto merge_bh = [&](const ov::Output & x, int64_t last_dim) { - auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector{B * H_v, T, last_dim}); + auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector{B * H_v, -1, last_dim}); return std::make_shared(x, shape, false); }; @@ -682,7 +730,9 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { ov::OutputVector{body_cond_out, state_updated, attn_out_unsq}, ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta}); - auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector{T}); + auto vm_shape = std::make_shared(v_m, ov::element::i64); + auto trip_count = + std::make_shared(vm_shape, axis_1, ov::op::v0::Constant::create(ov::element::i64, {}, {0})); auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector{true}); auto loop = std::make_shared(trip_count, exec_cond); @@ -709,7 +759,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { // attn: [B, T, H_v, S_v] row-major, state: [B, H_v, S_v, S_v] row-major // attn: [B*H_v, T, S_v] -> [B, H_v, T, S_v] -> transpose to [B, T, H_v, S_v] -> flatten - auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, T, S_v}); + auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{B, H_v, -1, S_v}); auto attn_4d = std::make_shared(attn_concat_out, attn_4d_shape, false); auto attn_perm = std::make_shared(attn_4d, perm_0213); // [B, T, H_v, S_v] @@ -729,7 +779,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { // Concat [attn | state] and reshape to final output auto packed = std::make_shared(ov::OutputVector{attn_1d, state_1d}, 0); auto out_shape = - ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, T * B + S_v * B, S_v * H_v}); + ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{1, 1, -1, S_v * H_v}); auto res = std::make_shared(packed, out_shape, false); return rename_outputs_with_suffix({res}, context.get_name()); diff --git a/ggml/src/ggml-openvino/openvino/op/reshape.cpp b/ggml/src/ggml-openvino/openvino/op/reshape.cpp index 98ef6fa2c1da..203d3d396d54 100644 --- a/ggml/src/ggml-openvino/openvino/op/reshape.cpp +++ b/ggml/src/ggml-openvino/openvino/op/reshape.cpp @@ -30,6 +30,10 @@ OutputVector translate_reshape(const NodeContext & context) { std::shared_ptr new_shape_node; switch (op_case) { case 0: + // keep the tracked dynamic dim, e.g. the tokens of a reshape that only adds a trailing 1 (see translate_cont) + if (context.get_op_dynamic_dim() != -1) { + shape[3 - context.get_op_dynamic_dim()] = -1; + } break; case 1: case 9: diff --git a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp index fb9eb5cc1680..078b31823c3e 100644 --- a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp +++ b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp @@ -34,7 +34,7 @@ OutputVector translate_rms_norm(const NodeContext & context) { input_node = context.get_input(0); } else if (op_case == 1) { input_node = process_view_input_new(context, 0); - } else if (op_case == 2 || op_case == 3) { + } else if (op_case == 2 || op_case == 5) { auto ssm_state_size = context.get_ssm_state_size(); // The GDN op packs [attn | new_state] along the row axis; the state occupies the last // ssm_state_size * n_seqs rows. Slice it off (scaling by the active sequence count) to keep @@ -83,7 +83,7 @@ OutputVector translate_rms_norm(const NodeContext & context) { float eps; memcpy(&eps, context.get_output_op_params(), sizeof(float)); - if (op_case == 3 && ggml_openvino_gdn_prescale_enabled()) { + if ((op_case == 3 || op_case == 5) && ggml_openvino_gdn_prescale_enabled()) { // input is the GDN output pre-scaled by ggml_openvino_gdn_q_scale(): rms_norm(s*x, s*s*eps) == rms_norm(x, eps) const float q_scale = ggml_openvino_gdn_q_scale(); eps *= q_scale * q_scale; diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp index 476890911c04..24cbeac35cfa 100644 --- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp @@ -118,16 +118,41 @@ static OutputVector translate_column_set_rows(const NodeContext & context) { if (data.get_element_type() != context.get_output_type()) { data = std::make_shared(data, context.get_output_type()); } - Output rows = std::make_shared(process_view_input_new(context, 1), i64_const({-1}), false); + auto row_ids = process_view_input_new(context, 1); + Output rows = std::make_shared(row_ids, i64_const({-1}), false); if (rows.get_element_type() != ov::element::i64) { rows = std::make_shared(rows, ov::element::i64); } auto axis = v0::Constant::create(ov::element::i64, {}, {2}); - auto buffer = std::make_shared(base, i64_const({1, 1, -1, row_size}), false); + Output buffer = std::make_shared(base, i64_const({1, 1, -1, row_size}), false); + Output base_shape_of = std::make_shared(base, ov::element::i64); + Output existing; + + // Every write copies the whole buffer, so fold this one into the previous column write when both use the same + // rows (DFlash writes every target layer at the same batch rows): splice into its rows and scatter once + auto rows_source = [](Output r) { + if (ov::as_type_ptr(r.get_node_shared_ptr())) { + r = r.get_node()->input_value(0); + } + return ov::as_type_ptr(r.get_node_shared_ptr()) ? r.get_node()->input_value(0) : Output(); + }; + auto prev_res = ov::as_type_ptr(base.get_node_shared_ptr()); + auto prev = prev_res ? ov::as_type_ptr(prev_res->get_input_node_shared_ptr(0)) : nullptr; + if (prev && rows_source(prev->input_value(1)) == row_ids && + prev->input_value(2).get_partial_shape().rank().is_static() && + prev->input_value(2).get_partial_shape()[3] == row_size) { + buffer = prev->input_value(0); + rows = prev->input_value(1); + existing = prev->input_value(2); + base_shape_of = prev_res->input_value(1); + } + Output updates = data; if (width < row_size) { - auto existing = std::make_shared(buffer, rows, axis); + if (!existing.get_node_shared_ptr()) { + existing = std::make_shared(buffer, rows, axis); + } auto col_axis = i64_const({3}); OutputVector parts; if (col_begin > 0) { @@ -142,7 +167,7 @@ static OutputVector translate_column_set_rows(const NodeContext & context) { updates = std::make_shared(parts, 3); } auto updated = std::make_shared(buffer, rows, updates, axis); - auto res = std::make_shared(updated, std::make_shared(base, ov::element::i64), false); + auto res = std::make_shared(updated, base_shape_of, false); return rename_outputs_with_suffix({res}, context.get_name()); } diff --git a/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp b/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp deleted file mode 100644 index 840233f85440..000000000000 --- a/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include "../node_context.h" -#include "../op_table.h" -#include "../utils.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ov { -namespace frontend { -namespace ggml { -namespace op { - -// GGML SOLVE_TRI: solve Ax = B for lower-triangular A via forward substitution. -// Currently only lower, right, non-unitriangular variant is implemented. -// -// ggml layout: A [n, n, B1, B2], B [k, n, B1, B2] → X [k, n, B1, B2] -// OV layout: A [B2, B1, n, n], B [B2, B1, n, k] → X [B2, B1, n, k] -// -// Forward substitution row i: -// x[i] = (b[i] - sum_{t(A_shape[2]); - - // Initial X: zeros with shape of B - auto B_shape_node = std::make_shared(B, ov::element::i64); - auto zero_f32 = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f}); - auto X_init = std::make_shared(zero_f32, B_shape_node); - - // --- Loop body parameters --- - // body_iter: iteration counter injected by the Loop op (i64, shape {1}) - auto body_iter = std::make_shared(ov::element::i64, ov::Shape{1}); - auto body_X = std::make_shared(ov::element::f32, ov::PartialShape::dynamic(4)); - auto body_A = std::make_shared(ov::element::f32, ov::PartialShape::dynamic(4)); - auto body_B_p = std::make_shared(ov::element::f32, ov::PartialShape::dynamic(4)); - - auto c_axis2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(2)}); - auto c_axis3 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(3)}); - auto c_axis2_scalar = ov::op::v0::Constant::create(ov::element::i64, {}, {int64_t(2)}); - - // b_i = B[..., i, :] [B2, B1, 1, k] - auto b_i = std::make_shared(body_B_p, body_iter, c_axis2); - - // A_row_i = A[..., i, :] [B2, B1, 1, n] - auto A_row_i = std::make_shared(body_A, body_iter, c_axis2); - - // sum_i = A_row_i @ X [B2, B1, 1, k] - // (lower-tri zeros + unfilled-X zeros make this equal to the partial sum) - auto sum_i = std::make_shared(A_row_i, body_X, false, false); - - // diag_i = A[..., i, i] [B2, B1, 1, 1] - auto diag_i = std::make_shared(A_row_i, body_iter, c_axis3); - - // x_i = (b_i - sum_i) / diag_i [B2, B1, 1, k] - auto x_i = std::make_shared( - std::make_shared(b_i, sum_i), diag_i); - - // X_updated: scatter x_i into body_X at row i along axis 2 - auto X_updated = std::make_shared(body_X, body_iter, x_i, c_axis2_scalar); - - auto body_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true}); - - auto body = std::make_shared( - ov::OutputVector{body_cond, X_updated}, - ov::ParameterVector{body_iter, body_X, body_A, body_B_p}); - - // --- Assemble Loop --- - auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector{n}); - auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true}); - - auto loop = std::make_shared(trip_count, exec_cond); - loop->set_function(body); - // iter_counter_body_param_idx=0 (body_iter), exec_condition_body_result_idx=0 (body_cond) - loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0}); - - // Carried state: X feeds back from X_updated each iteration - loop->set_merged_input(body_X, X_init, X_updated); - // Invariant inputs passed through unchanged - loop->set_invariant_input(body_A, A); - loop->set_invariant_input(body_B_p, B); - - // Final output: value of X_updated after the last iteration - auto X_final = loop->get_iter_value(X_updated, -1); - - return rename_outputs_with_suffix({X_final}, context.get_name()); -} - -} // namespace op -} // namespace ggml -} // namespace frontend -} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index defc428d1d4c..4983e2a7ccfe 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -57,6 +57,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_SQR", op::translate_sqr }, {"GGML_OP_SQRT", op::translate_sqrt }, {"GGML_OP_SOFT_MAX", op::translate_soft_max }, + {"GGML_OP_ARGMAX", op::translate_argmax }, {"GGML_OP_ARGSORT", op::translate_argsort }, {"GGML_OP_SUB", op::translate_1to1_match_2_inputs}, {"GGML_OP_TRANSPOSE", op::translate_transpose }, @@ -102,7 +103,6 @@ std::unordered_map get_supported_ops() { {"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net }, {"GGML_OP_REPEAT", op::translate_repeat }, {"GGML_OP_CUMSUM", op::translate_cumsum }, - {"GGML_OP_FILL", op::translate_fill }, {"GGML_OP_DIAG", op::translate_diag }, {"GGML_OP_TRI", op::translate_tri }, {"GGML_OP_SET", op::translate_set }, @@ -115,8 +115,6 @@ std::unordered_map get_supported_ops() { {"GGML_OP_CONV_TRANSPOSE_1D", op::translate_conv_transpose_1d }, {"GGML_OP_CONV_TRANSPOSE_2D", op::translate_conv_transpose_2d }, {"GGML_OP_CONV_3D", op::translate_conv_3d }, - // solve_tri has accuracy issues on GPU - // {"GGML_OP_SOLVE_TRI", op::translate_solve_tri }, }; } diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 54c60c634bf6..766ca4e6f76c 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -43,6 +43,7 @@ GGML_OP_CONVERTER(translate_glu_geglu); GGML_OP_CONVERTER(translate_glu_geglu_quick); GGML_OP_CONVERTER(translate_set_rows); GGML_OP_CONVERTER(translate_cpy); +GGML_OP_CONVERTER(translate_argmax); GGML_OP_CONVERTER(translate_argsort); GGML_OP_CONVERTER(translate_top_k); GGML_OP_CONVERTER(translate_flash_attn_ext); @@ -51,16 +52,16 @@ GGML_OP_CONVERTER(translate_pad); GGML_OP_CONVERTER(translate_ssm_conv); GGML_OP_CONVERTER(translate_ssm_scan); GGML_OP_CONVERTER(translate_gated_delta_net); +// The device runs GatedDeltaNet with a gate per key dimension; otherwise the translator falls back to its reference loop +bool gdn_per_key_gate_supported(); #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); #endif GGML_OP_CONVERTER(translate_repeat); GGML_OP_CONVERTER(translate_cumsum); -GGML_OP_CONVERTER(translate_fill); GGML_OP_CONVERTER(translate_set); GGML_OP_CONVERTER(translate_diag); GGML_OP_CONVERTER(translate_tri); -GGML_OP_CONVERTER(translate_solve_tri); GGML_OP_CONVERTER(translate_pool_1d); GGML_OP_CONVERTER(translate_pool_2d); GGML_OP_CONVERTER(translate_roll); diff --git a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp b/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp deleted file mode 100644 index 0671542ee383..000000000000 --- a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "fuse_to_sdpa.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ov { -namespace frontend { -namespace ggml { -namespace pass { - -FuseToSDPA::FuseToSDPA() { - // Not maintained since FLASH_ATTN_EXT has replaced this pattern - const auto m_k = ov::pass::pattern::any_input(); - const auto m_q = ov::pass::pattern::any_input(); - const auto m_qk = ov::pass::pattern::wrap_type({m_q, m_k}); - const auto m_qk_f32 = ov::pass::pattern::wrap_type({m_qk}); - const auto m_scale = ov::pass::pattern::any_input(); - const auto m_scaled_qk = ov::pass::pattern::wrap_type({m_qk_f32, m_scale}); - const auto m_mask = ov::pass::pattern::any_input(); - const auto m_masked_qk = ov::pass::pattern::wrap_type({m_scaled_qk, m_mask}); - const auto m_softmax_qk = ov::pass::pattern::wrap_type({m_masked_qk}); - const auto m_softmax_qk_f16 = ov::pass::pattern::wrap_type({m_softmax_qk}); - const auto m_v = ov::pass::pattern::any_input(); - const auto m_qkv = ov::pass::pattern::wrap_type({m_softmax_qk_f16, m_v}); - - const auto callback = [=](ov::pass::pattern::Matcher & m) { - auto & pattern_to_output = m.get_pattern_value_map(); - auto k = pattern_to_output[m_k]; - auto q = pattern_to_output[m_q]; - auto v = pattern_to_output[m_v]; - auto mask = pattern_to_output[m_mask]; - auto scale = pattern_to_output[m_scale]; - - auto mask_f16 = register_new_node(mask, ov::element::f16); - auto scale_f16 = register_new_node(scale, ov::element::f16); - auto sdpa = std::make_shared(q, k, v, mask_f16, scale_f16, false); - - ov::replace_node(m.get_match_root(), sdpa); - ov::copy_runtime_info(m.get_matched_nodes(), sdpa); - - return true; - }; - register_matcher(std::make_shared(m_qkv, "ov::frontend::ggml::pass::FuseToSDPA"), - callback); -} - -} // namespace pass -} // namespace ggml -} // namespace frontend -} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h b/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h deleted file mode 100644 index 8b5164d23293..000000000000 --- a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h +++ /dev/null @@ -1,17 +0,0 @@ -#include "openvino/pass/matcher_pass.hpp" - -namespace ov { -namespace frontend { -namespace ggml { -namespace pass { - -class FuseToSDPA : public ov::pass::MatcherPass { -public: - OPENVINO_MATCHER_PASS_RTTI("ov::frontend::ggml::pass::FuseToSDPA") - FuseToSDPA(); -}; - -} // namespace pass -} // namespace ggml -} // namespace frontend -} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index 3da712f72bdf..eddebd901dab 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -225,42 +225,12 @@ void add_position_mask_stateful_swa(TensorMap & tensor_map) { tensor_map["KQ_mask_swa_sliced"] = mask->output(0); } -void add_rope_sin_cos(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) { - // When ROPE ops in the graph have divergent op_params (e.g. gemma4's mixed - // SWA/non-SWA layers with different n_dims or freq_base), a shared sin/cos - // precompute cannot broadcast across every ROPE use. Skip it here and let - // translate_rope() build sin/cos per-op from its own op_params. - if (ggml_model_decoder.has_mixed_rope_params()) { - return; - } - int32_t * rope_params = ggml_model_decoder.get_rope_params(); - if (tensor_map.find("inp_pos") == tensor_map.end() || rope_params == nullptr) { - return; - } - auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr(); - std::shared_ptr rope_freqs_weight; - if (tensor_map.find("rope_freqs.weight") != tensor_map.end()) { - rope_freqs_weight = tensor_map.at("rope_freqs.weight").get_node_shared_ptr(); - } - - auto sin_cos = make_sin_cos(rope_params, inp_pos, rope_freqs_weight); - auto sin_theta = sin_cos.first; - auto cos_theta = sin_cos.second; - - cos_theta.get_node_shared_ptr()->set_friendly_name("rope_cos"); - sin_theta.get_node_shared_ptr()->set_friendly_name("rope_sin"); - tensor_map.insert({"rope_cos", cos_theta}); - tensor_map.insert({"rope_sin", sin_theta}); -} - // Create common patterns void preprocess(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) { if (ggml_model_decoder.is_stateful()) { add_sliced_mask_stateful(tensor_map, ggml_model_decoder.get_rope_params()[2] == GGML_ROPE_TYPE_IMROPE); add_position_mask_stateful_swa(tensor_map); } - // This optimization is error-prone - // add_rope_sin_cos(tensor_map, ggml_model_decoder); } } // namespace diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index e82a6c92fc47..7094cb7338ea 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include namespace ov { @@ -43,18 +44,6 @@ void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected"); } -int non_cont_dim(std::vector ne, std::vector nb) { - int dim = nb.size() - 1; - size_t bytes = nb[dim]; - for (int i = dim; i > 0; i--) { - bytes *= ne[i]; - if (bytes != nb[i - 1]) { - return i; - } - } - return 0; -} - std::shared_ptr get_dimensions(const std::shared_ptr & shape, const std::vector & dims) { using namespace ov::op; @@ -311,14 +300,77 @@ std::pair, ov::Output> make_sin_cos(int32_t * rope_params } } - Output cos_theta = std::make_shared(theta); - Output sin_theta = std::make_shared(theta); + // Keep the ROPE ANGLE in f32 even under INFERENCE_PRECISION_HINT=f16. + // + // Everything above builds theta = pos * freq_factors with a declared f32 type, but a declared + // element type is not an execution precision: under the f16 hint the GPU plugin compresses these + // subgraphs to f16 anyway. theta's magnitude IS the token position, so at position 6525 it lands + // where f16 spacing is 4 and the value is not even representable. Worse, a model whose freq_base + // and head_dim make factor[0] == 1.0 exactly feeds the raw position in as the top-frequency + // angle, so an absolute error of 1-2 becomes an error of 1-2 RADIANS -- up to a third of a cycle. Sin/Cos of an angle wrong by radians is not approximately + // right, it is arbitrary, and trig amplifies the error without bound. + // + // Measured on a large decoder-only model at inp_pos=6525, same device, f16 vs f32 execution: the + // whole Q/K projection chain is clean at rel ~1e-4, then Cos jumps to rel 0.124 and Sin to 0.155, + // and K right after the rotation carries rel 0.081. The error is depth-dependent because f16 + // spacing grows with magnitude: sin rel is 0.006 at position 512 and 0.16 at 6525. + // + // mark_as_precision_sensitive disables fp16 compression of the subgraph feeding an input, which is + // exactly the guarantee needed. Marking Sin/Cos's input covers the whole theta chain back to the + // Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the + // matmuls that dominate. The rotation itself and everything downstream stay f16. + // + // Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model, + // it is validated on one model on the GPU only, and on an f32 path the round trip below makes + // cos and sin less accurate. + const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0; + + auto cos_op = std::make_shared(theta); + auto sin_op = std::make_shared(theta); + if (pin_angle) { + ov::mark_as_precision_sensitive(cos_op->input(0)); + ov::mark_as_precision_sensitive(sin_op->input(0)); + } + Output cos_theta = cos_op; + Output sin_theta = sin_op; if (mscale != 1.0f) { auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale}); - cos_theta = std::make_shared(cos_theta, mscale_node); - sin_theta = std::make_shared(sin_theta, mscale_node); + auto cos_scaled = std::make_shared(cos_theta, mscale_node); + auto sin_scaled = std::make_shared(sin_theta, mscale_node); + // Mark this Constant's input too. Marking only Sin/Cos keeps those nodes f32 but leaves the + // sibling mscale Constant to be compressed to f16, and the pass does not reconcile the pair, + // so compilation fails with "Arguments do not have the same element type". + if (pin_angle) { + ov::mark_as_precision_sensitive(cos_scaled->input(1)); + ov::mark_as_precision_sensitive(sin_scaled->input(1)); + } + cos_theta = cos_scaled; + sin_theta = sin_scaled; + } + + // Close the f32 island explicitly with an f16 round trip. + // + // ConvertPrecision does not insert the boundary Convert: with only the marking above, the f32 + // region propagates forward through the shape-only ops of the cos/sin expansion and then collides + // with f16 data in the rotation, so the type mismatch just moves one step down the graph. + // + // Rounding the RESULT of the trig is harmless -- cos/sin are in [-1,1], where f16 spacing is ~6e-4, + // the ordinary f16 cost accepted everywhere else. What must not be rounded is the ANGLE, which the + // marking above protects. So this spends the cheap rounding to buy a type-consistent graph: the + // chain from inp_pos through Sin/Cos stays f32, everything downstream is f16, and the transition is + // a node we control rather than one the pass has to infer. + // + // Declared types are f32 on both sides at build time, so the frontend sees no type change. On an + // f32 path (the CPU device in test-backend-ops) the two Converts still round cos and sin to f16. + if (pin_angle) { + auto pin_boundary = [](Output x) -> Output { + auto down = std::make_shared(x, ov::element::f16); + return std::make_shared(down, ov::element::f32); + }; + cos_theta = pin_boundary(cos_theta); + sin_theta = pin_boundary(sin_theta); } return std::make_pair(sin_theta, cos_theta); @@ -784,20 +836,23 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return split_node->output(static_cast(split_index)); } if (split_index >= 0 && split_index < num_splits && !dynamic_split) { + // as above: a weak reference, and one Split per output port auto src_node = input.get_node_shared_ptr(); - std::string rt_key = "split_dim_" + std::to_string(split_dim); + std::string rt_key = + "split_dim_static_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index()); auto & rt_info = src_node->get_rt_info(); - - if (rt_info.find(rt_key) == rt_info.end()) { + std::shared_ptr split_node; + if (rt_info.count(rt_key) != 0) { + split_node = rt_info[rt_key].as>().lock(); + } + if (split_node == nullptr) { auto axis_const = ov::op::v0::Constant::create(ov::element::i64, {}, {static_cast(split_dim)}); - auto split_node = + split_node = std::make_shared(input, axis_const, static_cast(num_splits)); split_node->set_friendly_name(src_node->get_friendly_name() + "_split"); - rt_info[rt_key] = split_node; + rt_info[rt_key] = std::weak_ptr(split_node); } - - auto split_node = rt_info[rt_key].as>(); return split_node->output(static_cast(split_index)); } } diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index aaee05116445..3fe3b60f918b 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -13,42 +13,8 @@ namespace ov { namespace frontend { namespace ggml { -std::string getCurrentTime(); - void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs); -int non_cont_dim(std::vector ne, std::vector nb); - -template std::vector argsort_descend(const std::vector & v) { - std::vector idx(v.size()); - std::iota(idx.begin(), idx.end(), 0); - std::sort(idx.begin(), idx.end(), [&v](int i1, int i2) { return v[i1] > v[i2]; }); - return idx; -} - -template std::vector sorted_descend(std::vector v) { - std::sort(v.begin(), v.end(), [](T a, T b) { return a > b; }); - return v; -} - -template bool is_permuted(const std::vector & strides) { - for (size_t i = 0; i < strides.size() - 1; ++i) { - if (strides[i] < strides[i + 1]) { - return true; - } - } - return false; -} - -template std::vector permute(const std::vector & x, const std::vector & perm) { - std::vector result; - result.reserve(perm.size()); - for (int i : perm) { - result.push_back(x[i]); - } - return result; -} - std::shared_ptr get_dimensions(const std::shared_ptr & shape, const std::vector & dims); std::shared_ptr get_dimensions(const std::shared_ptr & node, const std::vector & dims); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index c959ce0d9203..03479f35edd3 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -151,6 +151,12 @@ std::optional try_make_kv_sliced_tensor(const std::shared_ptrdata == nullptr) { + // unallocated input: let the caller build an owning zero tensor rather than slice a null + // pointer + return std::nullopt; + } + ov::Shape sliced_shape = full_shape; sliced_shape[2] = static_cast(n_kv); @@ -192,10 +198,10 @@ std::optional try_make_kv_4d_tensor(const std::shared_ptr ggml_decoder, const std::string & name) { +static size_t get_static_attention_size(const std::shared_ptr & ggml_decoder, const std::string & name) { const bool is_swa = ggml_decoder->is_swa_mask(ggml_decoder->get_input_ggml_tensor(name)); if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0) { - const auto params = ggml_decoder->get_compute_params(); + const auto & params = ggml_decoder->get_compute_params(); const int attention_size = is_swa ? params.attention_size_swa : params.attention_size; if (attention_size > 0) { return static_cast(attention_size); @@ -209,10 +215,7 @@ static size_t get_static_attention_size(std::shared_ptr ggml_deco } static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) { - const char * manual_gqa_env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN"); - const bool manual_gqa_enabled = manual_gqa_env != nullptr ? - ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 : - ggml_openvino_is_gpu(); + const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results. #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE @@ -561,6 +564,11 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr & ggml_d return context.create_tensor(output_type, output_shape, resolved); } + // A graph output can also have no backing storage. Give OV an owning tensor so the infer request + // has somewhere to write; nothing downstream reads it. + if (output_data == nullptr) { + return ov::Tensor(output_type, output_shape); + } ov::Tensor output_tensor(output_type, output_shape, output_data); return output_tensor; } @@ -713,6 +721,20 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr & ggml_ return make_contiguous_split_input_tensor(ggml_tensor, input_shape); } + // A graph input may legitimately be left unallocated (data == nullptr, no buffer): llama.cpp + // skips filling the attention mask when a graph only stores K/V without attending, which is what + // a speculative KV-injection pass does. Such an input is never read, but OpenVINO still requires + // a backing tensor for the Parameter and constructing an ov::Tensor over a null pointer asserts. + // Hand OV an owning zero-filled tensor; its contents cannot affect the result because no op + // consumes them. + if (input_data == nullptr) { + GGML_LOG_WARN("ggml-openvino: unallocated INPUT '%s' (ggml name '%s', type %s, ne=[%ld,%ld,%ld,%ld]) " + "-> zero tensor\n", + name.c_str(), ggml_tensor->name, ggml_type_name(ggml_tensor->type), + (long) ggml_tensor->ne[0], (long) ggml_tensor->ne[1], (long) ggml_tensor->ne[2], + (long) ggml_tensor->ne[3]); + return ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape); + } auto input_tensor = ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape, input_data); return input_tensor; } @@ -790,10 +812,8 @@ ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptrdata); - assert(ggml_tensor->ne[0] == 1); - assert(inp_out_id == 0); - *input_tensor.data() = inp_out_id; + // The only decode token is row 0. out_ids is empty when the graph has no output, so it is not read. + *input_tensor.data() = 0; return input_tensor; } @@ -1256,13 +1276,15 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share cache_hit = it != r_ctx->decoder_cache.end(); if (cache_hit) { entry = it->second; + r_ctx->touch_locked(key); } else { - if (r_ctx->stateful || r_ctx->decoder_cache.size() >= 8) { + if (r_ctx->stateful) { r_ctx->clear_caches_locked(); } auto mutex = std::make_shared(); entry = std::make_shared(mutex); r_ctx->decoder_cache[key] = entry; + r_ctx->admit_locked(key); } } else { auto mutex = std::make_shared(); @@ -1276,10 +1298,21 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share if (cache_hit) { ggml_decoder = entry->ptr; + // The cache key is only (n_nodes, first/last node name), so it cannot see a change in + // WHICH tensors are graph outputs -- and the compiled model's Results are fixed when it is + // built. A consumer that starts requesting extra outputs later (speculative decoding marks + // the target's per-layer residuals only once the draft is initialised) would otherwise keep + // reusing a model that never produces them, and the host would read unwritten buffers as + // zeros. Recompile when the output set differs. old_m_params = ggml_decoder->get_model_params(); if (!ggml_decoder->is_splited_model()) { cache_hit = old_m_params.can_reuse_dynamically(m_params); } + // Must come AFTER can_reuse_dynamically(), which ASSIGNS to cache_hit rather than + // and-ing into it and would otherwise silently undo this invalidation. + if (cache_hit && !ggml_decoder->has_same_graph_io(cgraph)) { + cache_hit = false; + } } std::vector ov_input_names; @@ -1654,8 +1687,6 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share infer_request = std::make_shared(compiled_model.create_infer_request()); shared_model = compiled_model; - entry->ptr = ggml_decoder; - } // end non-imported (compile) path entry->ptr = ggml_decoder; @@ -1725,7 +1756,20 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share id = binding.staging_id; } if (needs_bind(binding, input_tensor, id)) { - infer_request->set_input_tensor(i, input_tensor); + try { + infer_request->set_input_tensor(i, input_tensor); + } catch (const std::exception & e) { + if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) { + auto port = infer_request->get_compiled_model().input(i); + GGML_LOG_WARN( + "ggml-openvino: DIAG set_input_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n" + " model_shape=%s bound_shape=%s\n", + i, param_name.c_str(), key.n_nodes, key.first_node_name.c_str(), + key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(), + input_tensor.get_shape().to_string().c_str()); + } + throw; + } } if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) { @@ -1786,12 +1830,40 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share id = binding.staging_id; } if (needs_bind(binding, output_tensor, id)) { - infer_request->set_output_tensor(i, output_tensor); + try { + infer_request->set_output_tensor(i, output_tensor); + } catch (const std::exception & e) { + if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) { + auto port = infer_request->get_compiled_model().output(i); + GGML_LOG_WARN( + "ggml-openvino: DIAG set_output_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n" + " model_shape=%s bound_shape=%s\n", + i, ov_output_names[i].c_str(), key.n_nodes, key.first_node_name.c_str(), + key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(), + output_tensor.get_shape().to_string().c_str()); + } + throw; + } } } ov_raw_infer_start = ggml_time_us(); - infer_request->infer(); + try { + infer_request->infer(); + } catch (const std::exception & e) { + if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) { + auto cm = infer_request->get_compiled_model(); + GGML_LOG_WARN("ggml-openvino: DIAG infer() threw for n_nodes=%d first=%s last=%s: %s\n", key.n_nodes, + key.first_node_name.c_str(), key.last_node_name.c_str(), e.what()); + for (size_t i = 0; i < ov_input_names.size(); i++) { + auto port = cm.input(i); + GGML_LOG_WARN(" param[%zu] name=%s model_shape=%s bound_shape=%s\n", i, + ov_input_names[i].c_str(), port.get_partial_shape().to_string().c_str(), + infer_request->get_input_tensor(i).get_shape().to_string().c_str()); + } + } + throw; + } infer_end_time = ggml_time_us(); for (const auto & out : staged_outputs) { std::memcpy(out.dst, out.src, out.bytes); @@ -2190,11 +2262,12 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared cache_hit = it != r_ctx->decoder_cache.end(); if (cache_hit) { entry = it->second; + r_ctx->touch_locked(key); } else { - r_ctx->clear_caches_locked(); auto mutex = std::make_shared(); entry = std::make_shared(mutex); r_ctx->decoder_cache[key] = entry; + r_ctx->admit_locked(key); } } else { auto mutex = std::make_shared(); @@ -2265,10 +2338,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared // Same fail-fast as the dynamic path: once the host weight pages have been dropped // they read as zeros, so a recompile here would bake garbage into the new model. if (ggml_openvino_weight_buffers_released()) { - GGML_ABORT( - "ggml-openvino: a new graph needs to be compiled but host weight buffers were already " - "released via GGML_OPENVINO_RELEASE_WEIGHTS. This mode requires " - "stable graph shapes; disable host weight release for dynamic workloads."); + GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n"); + return GGML_STATUS_FAILED; } if (cache_enabled) { std::lock_guard map_lock(r_ctx->ctx_mutex); @@ -2318,6 +2389,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } } else { auto decode_c_params = c_params; + // A decode step outputs its one token. llama-perplexity asks for many outputs in the prefill graph; the + // decode model of the pair keeps one (decode_signature below), or its last layer would gather more rows + // than the graph has tokens. + decode_c_params.output_len = 1; if (ggml_openvino_kv_slice_enabled()) { decode_c_params.attention_size = m_params.ctx_per_seq; decode_c_params.attention_size_swa = m_params.ctx_per_seq_swa; @@ -3322,7 +3397,7 @@ bool is_model_splitted(ggml_cgraph * cgraph) { // the src is also not the model weights, we think the model is splitted. // the src is also not in model leafs, we think the model is splitted. if (src != nullptr && model_nodes.find(src) == model_nodes.end() && - model_weights.find(std::string(src->name)) == model_weights.end() && !model_leafs.empty() == false && + model_weights.find(std::string(src->name)) == model_weights.end() && model_leafs.find(src) == model_leafs.end()) { if (GgmlOvDecoder::is_inp_tok(src, node)) { return false; @@ -3345,75 +3420,6 @@ bool is_naive(ggml_cgraph * cgraph) { return count < naive_graph_size_threshold; } -size_t checksum(const void * data, size_t size) { - const uint8_t * bytes = static_cast(data); - size_t sum = 0; - for (size_t i = 0; i < size; ++i) { - sum += (uint8_t) i; - sum += bytes[i]; - } - return sum; -} - -bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path) { - if (tensor == nullptr || tensor->data == nullptr) { - return false; - } - - std::ofstream out(file_path); - if (!out.is_open()) { - return false; - } - - const size_t n = ggml_nelements(tensor); - out << "name: " << tensor->name << ", type: " << ggml_type_name(tensor->type) << ", shape: [" << tensor->ne[0] - << ", " << tensor->ne[1] << ", " << tensor->ne[2] << ", " << tensor->ne[3] << "]" << ", elements: " << n - << ", data:" << '\n'; - - switch (tensor->type) { - case GGML_TYPE_F32: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << data[i] << '\n'; - } - break; - } - case GGML_TYPE_F16: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << ggml_fp16_to_fp32(data[i]) << '\n'; - } - break; - } - case GGML_TYPE_BF16: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << ggml_bf16_to_fp32(data[i]) << '\n'; - } - break; - } - case GGML_TYPE_I32: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << data[i] << '\n'; - } - break; - } - case GGML_TYPE_I64: { - const auto * data = static_cast(tensor->data); - for (size_t i = 0; i < n; ++i) { - out << data[i] << '\n'; - } - break; - } - default: - out << "unsupported tensor type for text dump" << '\n'; - return false; - } - - return true; -} - void print_input_tensor_info(const std::string & name, const ov::Tensor & input) { // GPU inputs can be device (USM) tensors, whose data() throws; print a host copy of those. const bool is_remote = input.is(); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index c4450a387748..270676b07dca 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -158,6 +159,12 @@ struct ov_runtime_context { std::unordered_map, graph_key_hash> ov_output_names_cache; std::unordered_map, graph_key_hash> ov_input_names_cache_prefill; std::unordered_map, graph_key_hash> ov_output_names_cache_prefill; + // LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline + // that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/ + // injection graphs every round -- needs a slot per shape open at once; a single-entry cache + // would evict and recompile all of them, every call, forever. + std::list lru_keys; + static constexpr size_t max_cached_graphs = 8; size_t stateful_kv_size; std::map kv_state_input_name_map; // compute-only copies of graphs that carry unselected ggml_build_forward_select() branches @@ -169,6 +176,39 @@ struct ov_runtime_context { ov_runtime_context() : device("CPU"), stateful(false), stateful_kv_size(0) {} + // Mark `key` as the most recently used entry. Call on every cache hit and after inserting a + // new entry, so eviction always picks the graph shape that has gone longest unused. + void touch_locked(const graph_key & key) { + lru_keys.remove(key); + lru_keys.push_back(key); + } + + // Drop the least recently used graph shape's compiled model and its associated per-key + // caches. Leaves every other shape's compiled model intact. + void evict_lru_locked() { + if (lru_keys.empty()) { + return; + } + graph_key victim = lru_keys.front(); + lru_keys.pop_front(); + decoder_cache.erase(victim); + infer_request_cache.erase(victim); + infer_request_cache_prefill.erase(victim); + ov_input_names_cache.erase(victim); + ov_output_names_cache.erase(victim); + ov_input_names_cache_prefill.erase(victim); + ov_output_names_cache_prefill.erase(victim); + } + + // Make room for one more graph shape if the cache is at capacity, then mark `key` as most + // recently used. Call right after inserting `key` into decoder_cache. + void admit_locked(const graph_key & key) { + while (decoder_cache.size() > max_cached_graphs) { + evict_lru_locked(); + } + touch_locked(key); + } + void clear_caches_locked() { decoder_cache.clear(); infer_request_cache.clear(); @@ -177,6 +217,7 @@ struct ov_runtime_context { ov_output_names_cache.clear(); ov_input_names_cache_prefill.clear(); ov_output_names_cache_prefill.clear(); + lru_keys.clear(); kv_state_input_name_map.clear(); stateful_kv_size = 0; } @@ -192,10 +233,6 @@ enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t ba // Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR). void ov_clear_imported_blobs(); -size_t checksum(const void * data, size_t size); - -bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path); - void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor); void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst); From 2359d27a3694f220b190e5947684fcd4b3b2340f Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 15:45:44 +0100 Subject: [PATCH 065/401] ui: name the PWA from the build env and default it to Llama Chat (#32890) The manifest is built in Node by its Vite plugin, where import.meta.env is not set, so it was always named llama-ui whatever VITE_PUBLIC_APP_NAME said. The plugin now names it from the env Vite loaded (.env files included), and the default name is Llama Chat. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/.env.example | 2 +- ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts | 16 +++++++++++----- ui/apps/chat/src/lib/constants/app.constants.ts | 2 +- ui/apps/chat/src/lib/constants/pwa.constants.ts | 11 +++++++++++ 4 files changed, 24 insertions(+), 7 deletions(-) diff --git a/ui/apps/chat/.env.example b/ui/apps/chat/.env.example index ed46f9aded97..9760b0dd43fb 100644 --- a/ui/apps/chat/.env.example +++ b/ui/apps/chat/.env.example @@ -1,4 +1,4 @@ -VITE_PUBLIC_APP_NAME='llama-ui' +VITE_PUBLIC_APP_NAME='Llama Chat' VITE_DEBUG='true' VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033' diff --git a/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts b/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts index d6ba3d2aa505..a82eac906eeb 100644 --- a/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts +++ b/ui/apps/chat/scripts/vite-plugin-pwa-manifest.ts @@ -1,12 +1,11 @@ import { HEADERS } from '../src/lib/constants/headers.constants'; import { PWA_FILE_PATHS, - PWA_MANIFEST, - PWA_MANIFEST_PLUGIN + PWA_MANIFEST_PLUGIN, + pwaManifest } from '../src/lib/constants/pwa.constants'; import type { Plugin } from 'vite'; -const MANIFEST_SOURCE = JSON.stringify(PWA_MANIFEST); // the build writes files relative to its output directory: the path without its leading slash const MANIFEST_FILE = PWA_FILE_PATHS.MANIFEST.slice(1); @@ -15,17 +14,24 @@ const MANIFEST_FILE = PWA_FILE_PATHS.MANIFEST.slice(1); * The adapter copies the client output, so the file lands at the root of the build. */ export function pwaManifestPlugin(): Plugin { + let manifestSource = ''; + return { + // named from the env Vite loaded (.env files too): this module runs in Node, where + // import.meta.env is not set and APP_NAME would fall back to its default + configResolved(config) { + manifestSource = JSON.stringify(pwaManifest(config.env)); + }, configureServer(server) { server.middlewares.use(PWA_FILE_PATHS.MANIFEST, (_req, res) => { res.setHeader(HEADERS.CONTENT_TYPE, PWA_MANIFEST_PLUGIN.CONTENT_TYPE); - res.end(MANIFEST_SOURCE); + res.end(manifestSource); }); }, generateBundle() { if (this.environment.name !== PWA_MANIFEST_PLUGIN.ENVIRONMENT) return; - this.emitFile({ fileName: MANIFEST_FILE, source: MANIFEST_SOURCE, type: 'asset' }); + this.emitFile({ fileName: MANIFEST_FILE, source: manifestSource, type: 'asset' }); }, name: PWA_MANIFEST_PLUGIN.NAME }; diff --git a/ui/apps/chat/src/lib/constants/app.constants.ts b/ui/apps/chat/src/lib/constants/app.constants.ts index c598f480fd4d..8e87264c3afd 100644 --- a/ui/apps/chat/src/lib/constants/app.constants.ts +++ b/ui/apps/chat/src/lib/constants/app.constants.ts @@ -1 +1 @@ -export const APP_NAME = import.meta.env?.VITE_PUBLIC_APP_NAME || 'llama-ui'; +export const APP_NAME = import.meta.env?.VITE_PUBLIC_APP_NAME || 'Llama Chat'; diff --git a/ui/apps/chat/src/lib/constants/pwa.constants.ts b/ui/apps/chat/src/lib/constants/pwa.constants.ts index 734356fb72bc..71e9cbfebdda 100644 --- a/ui/apps/chat/src/lib/constants/pwa.constants.ts +++ b/ui/apps/chat/src/lib/constants/pwa.constants.ts @@ -45,6 +45,10 @@ export const APPLE_ASSETS = { TOUCH_ICON: 'apple-touch-icon-180x180.png' } as const; +/** + * The web app manifest. In the browser APP_NAME follows the env; the manifest plugin runs in + * Node, where import.meta.env is not set, so it names the manifest with pwaManifest(). + */ export const PWA_MANIFEST = { background_color: THEME_COLORS.BACKGROUND_LIGHT, description: 'Local AI chat interface powered by llama.cpp', @@ -68,6 +72,13 @@ export const PWA_MANIFEST = { theme_color: THEME_COLORS.BACKGROUND_LIGHT }; +/** PWA_MANIFEST with the name a build sets (VITE_PUBLIC_APP_NAME) */ +export function pwaManifest(env: Record) { + const name = env.VITE_PUBLIC_APP_NAME || PWA_MANIFEST.name; + + return { ...PWA_MANIFEST, name, short_name: name }; +} + export const PWA_ICON_PATHS = { MASKABLE_512: '/maskable-icon-512x512.png', PWA_64: '/pwa-64x64.png', From a0677c341ba6bbfbbf74fa3c966f4dba74e1c830 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 15:47:30 +0100 Subject: [PATCH 066/401] ui: use a red edge on the send button's error state (#32856) The error state reused the primary button's edge, which shows as a light ring in dark mode. Use the danger button's edge instead. Assisted-by: Claude (Opus 5.5 Medium) --- .../chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte index fa26d6bbc10e..a9682034f529 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionSubmit.svelte @@ -28,7 +28,7 @@ class={[ 'md:size-8 size-9 rounded-full p-0', showErrorState && - 'bg-surface-danger text-fg-danger hover:bg-surface-danger/80 hover:text-fg-danger disabled:opacity-100' + '[--key-edge:var(--button-danger-edge)] bg-surface-danger text-fg-danger hover:bg-surface-danger/80 hover:text-fg-danger disabled:opacity-100' ]} disabled={isDisabled} type="submit" From 1f3ea67fbf857bb831d3fb9e3a91c0f8ad3fbe78 Mon Sep 17 00:00:00 2001 From: bri-prism <288398250+bri-prism@users.noreply.github.com> Date: Mon, 23 Nov 2026 07:15:34 -0800 Subject: [PATCH 067/401] metal: resolve gpu timeout on iPhone for Bonsai (#31815) --- ggml/src/ggml-metal/ggml-metal.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal.cpp b/ggml/src/ggml-metal/ggml-metal.cpp index 9a1bd2c773a3..aca83e13d59d 100644 --- a/ggml/src/ggml-metal/ggml-metal.cpp +++ b/ggml/src/ggml-metal/ggml-metal.cpp @@ -9,6 +9,8 @@ #include "ggml-metal-ops.h" #include "ggml-metal-tuning.h" +#include + #include #include @@ -653,6 +655,13 @@ static void ggml_backend_metal_graph_optimize(ggml_backend_t backend, ggml_cgrap ggml_metal_graph_optimize(ctx, cgraph); } +// iOS can stop a command buffer that runs for more than a few seconds, so split the graph into shorter ones there +#if TARGET_OS_IPHONE +#define GGML_METAL_DEFAULT_N_CB 8 +#else +#define GGML_METAL_DEFAULT_N_CB 1 +#endif // TARGET_OS_IPHONE + static void ggml_backend_metal_set_n_cb(ggml_backend_t backend, int n_cb) { GGML_ASSERT(ggml_backend_is_metal(backend)); @@ -704,7 +713,7 @@ ggml_backend_t ggml_backend_metal_init(void) { /* .context = */ ctx, }; - ggml_backend_metal_set_n_cb(backend, 1); + ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB); return backend; } @@ -799,7 +808,7 @@ static ggml_backend_t ggml_backend_metal_device_init_backend(ggml_backend_dev_t /* .context = */ ctx, }; - ggml_backend_metal_set_n_cb(backend, 1); + ggml_backend_metal_set_n_cb(backend, GGML_METAL_DEFAULT_N_CB); return backend; From b6d5ce4bc9a3691d26b3207cc6c9c63b732d67e8 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 16:18:59 +0100 Subject: [PATCH 068/401] ui: drop tool calls cut off by Stop from the next request (#32738) * ui: drop tool calls cut off by Stop from the next request A tool call stopped mid-stream could stay on its message with cut-off arguments. The server parses every call's arguments as JSON, so the next message in that chat ("Continue") failed with "Failed to parse tool call arguments as JSON". Requests now leave such calls out, with the tool results that answer them, and send a call with no arguments as {}. Assisted-by: Claude (Opus 5.5 Medium) * ui: add a demo trace that ends in a stopped tool call A conversation whose last tool call was stopped while its arguments were still streaming, for recording the fix in the previous commit. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/demo/fixtures/traces.ts | 40 +++++++++- ui/apps/chat/src/lib/services/chat.service.ts | 8 +- .../src/lib/utils/incomplete-tool-calls.ts | 76 +++++++++++++++++++ .../tests/unit/incomplete-tool-calls.test.ts | 69 +++++++++++++++++ 4 files changed, 190 insertions(+), 3 deletions(-) create mode 100644 ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts create mode 100644 ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts diff --git a/ui/apps/chat/demo/fixtures/traces.ts b/ui/apps/chat/demo/fixtures/traces.ts index dc766458e478..ce673a85e8f9 100644 --- a/ui/apps/chat/demo/fixtures/traces.ts +++ b/ui/apps/chat/demo/fixtures/traces.ts @@ -47,6 +47,17 @@ class Trace { this.push({ content: '', role: 'system', type: 'root' }); } + /** An assistant turn whose tool call was stopped mid-stream: cut-off arguments and no result. */ + stoppedTool(name: string, cutArguments: string, content = ''): this { + const id = uuid(this.name, `call-${this.calls++}`).replaceAll('-', ''); + + return this.push({ + content, + role: 'assistant', + toolCalls: [{ function: { arguments: cutArguments, name }, id, type: 'function' }] + }); + } + toJsonl(): string { const last = this.messages.at(-1)!; const session = { @@ -330,11 +341,38 @@ function diagrams(): Trace { return trace; } +/** A chat whose last tool call was stopped while its arguments were still streaming. */ +function stoppedToolCall(): Trace { + const trace = new Trace('Smoke test for the slides page'); + + trace.user('Write a quick Playwright smoke test for slides.html and run it.'); + trace.stoppedTool( + 'exec_shell_command', + JSON.stringify({ + command: [ + "cat > /tmp/slides-smoke.mjs <<'EOF'", + "import { chromium } from 'playwright';", + '', + 'const browser = await chromium.launch();', + 'const page = await browser.newPage();', + '', + "await page.goto('file:///tmp/slides.html');", + 'EOF', + 'node /tmp/slides-smoke.mjs' + ].join('\n') + }).slice(0, 160), + 'I will write the script to a file and run it.' + ); + + return trace; +} + /** Built-in traces, by name. */ export const DEMO_TRACES: Record Trace> = { 'agentic-debugging': agenticDebugging, diagrams, - 'long-chat': longChat + 'long-chat': longChat, + 'stopped-tool-call': stoppedToolCall }; export function generateTrace(name: string): null | string { diff --git a/ui/apps/chat/src/lib/services/chat.service.ts b/ui/apps/chat/src/lib/services/chat.service.ts index 38c7eba144b1..9d0a146cd989 100644 --- a/ui/apps/chat/src/lib/services/chat.service.ts +++ b/ui/apps/chat/src/lib/services/chat.service.ts @@ -8,6 +8,7 @@ import { getAudioInputFormat } from '../utils/audio-format'; import { capImageDataURLSize } from '../utils/cap-img-size'; +import { dropIncompleteToolCalls } from '../utils/incomplete-tool-calls'; import { API_CHAT, API_SLOTS, @@ -851,8 +852,7 @@ export class ChatService { model?: string | null ): Promise { const options = ChatService.conversionOptionsFor(model); - - return ( + const converted = ( await Promise.all( messages.map((msg) => { if ('id' in msg && 'convId' in msg && 'timestamp' in msg) { @@ -875,6 +875,10 @@ export class ChatService { return true; }); + + // a tool call cut off by Stop can still sit on the message: the server + // would reject the whole request on its arguments + return dropIncompleteToolCalls(converted); } /** diff --git a/ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts b/ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts new file mode 100644 index 000000000000..62ba5806179f --- /dev/null +++ b/ui/apps/chat/src/lib/utils/incomplete-tool-calls.ts @@ -0,0 +1,76 @@ +import { MessageRole } from '#lib/enums/index.ts'; +import type { ApiChatCompletionToolCall, ApiChatMessageData } from '#lib/types/api.d.ts'; + +const EMPTY_ARGUMENTS = '{}'; + +/** + * Drop the tool calls a stopped stream left with cut-off arguments, and the + * tool results that answer them. The server parses every call's arguments as + * JSON and rejects the whole request when one doesn't parse, so a call cut + * off mid-stream would otherwise break every request after it. A call with + * no arguments at all is kept and sent with `{}`. + */ +export function dropIncompleteToolCalls(messages: ApiChatMessageData[]): ApiChatMessageData[] { + const droppedIds = new Set(); + const result: ApiChatMessageData[] = []; + + for (const message of messages) { + if ( + message.role === MessageRole.TOOL && + message.tool_call_id && + droppedIds.has(message.tool_call_id) + ) { + continue; + } + + if (!message.tool_calls?.length) { + result.push(message); + + continue; + } + + const calls = message.tool_calls; + const kept: ApiChatCompletionToolCall[] = []; + + for (const call of calls) { + const sendable = sendableToolCall(call); + + if (sendable) { + kept.push(sendable); + } else if (call.id) { + droppedIds.add(call.id); + } + } + + if (kept.length === calls.length && kept.every((call, i) => call === calls[i])) { + result.push(message); + + continue; + } + + const { tool_calls: _dropped, ...rest } = message; + + result.push(kept.length > 0 ? { ...rest, tool_calls: kept } : rest); + } + + return result; +} + +/** The call as it can be sent, or null when its name or arguments were cut off. */ +function sendableToolCall(call: ApiChatCompletionToolCall): ApiChatCompletionToolCall | null { + if (!call.function?.name) return null; + + const args = call.function.arguments; + + if (!args?.trim()) { + return { ...call, function: { ...call.function, arguments: EMPTY_ARGUMENTS } }; + } + + try { + JSON.parse(args); + + return call; + } catch { + return null; + } +} diff --git a/ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts b/ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts new file mode 100644 index 000000000000..f287b1cbf798 --- /dev/null +++ b/ui/apps/chat/tests/unit/incomplete-tool-calls.test.ts @@ -0,0 +1,69 @@ +import { MessageRole } from '#lib/enums/index.ts'; +import type { ApiChatCompletionToolCall, ApiChatMessageData } from '#lib/types/api.d.ts'; +import { dropIncompleteToolCalls } from '#lib/utils/incomplete-tool-calls.ts'; +import { describe, expect, it } from 'vitest'; + +function call(id: string, args: string, name = 'exec_shell_command'): ApiChatCompletionToolCall { + return { function: { arguments: args, name }, id, type: 'function' }; +} + +const CUT = '{"command": "cd /repo && cat > /tmp/x.mjs <<\'EOF\'\\nimport'; + +describe('dropIncompleteToolCalls', () => { + it('leaves complete tool calls and their results alone', () => { + const messages: ApiChatMessageData[] = [ + { content: 'run it', role: MessageRole.USER }, + { content: '', role: MessageRole.ASSISTANT, tool_calls: [call('a', '{"command":"ls"}')] }, + { content: 'file.txt', role: MessageRole.TOOL, tool_call_id: 'a' } + ]; + const result = dropIncompleteToolCalls(messages); + + expect(result).toEqual(messages); + expect(result[1]).toBe(messages[1]); + }); + + it('drops a call whose arguments were cut off, keeping the text of the message', () => { + const result = dropIncompleteToolCalls([ + { + content: 'Let me write the script.', + role: MessageRole.ASSISTANT, + tool_calls: [call('a', CUT)] + }, + { content: 'Continue', role: MessageRole.USER } + ]); + + expect(result).toEqual([ + { content: 'Let me write the script.', role: MessageRole.ASSISTANT }, + { content: 'Continue', role: MessageRole.USER } + ]); + }); + + it('keeps the complete calls of a message and drops the results of the cut one', () => { + const result = dropIncompleteToolCalls([ + { + content: '', + role: MessageRole.ASSISTANT, + tool_calls: [call('a', '{"command":"ls"}'), call('b', CUT)] + }, + { content: 'file.txt', role: MessageRole.TOOL, tool_call_id: 'a' }, + { content: 'error', role: MessageRole.TOOL, tool_call_id: 'b' } + ]); + + expect(result).toEqual([ + { content: '', role: MessageRole.ASSISTANT, tool_calls: [call('a', '{"command":"ls"}')] }, + { content: 'file.txt', role: MessageRole.TOOL, tool_call_id: 'a' } + ]); + }); + + it('drops a call with no name and sends a call with no arguments as {}', () => { + const result = dropIncompleteToolCalls([ + { + content: '', + role: MessageRole.ASSISTANT, + tool_calls: [call('a', '{}', ''), call('b', '', 'list_tasks')] + } + ]); + + expect(result[0].tool_calls).toEqual([call('b', '{}', 'list_tasks')]); + }); +}); From 27d0a1fc73f3a50bc32e13d13e163e462cc37316 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 16:20:15 +0100 Subject: [PATCH 069/401] ui: unmount a closed collapsible's body after one transition (#32881) bits-ui rebuilds the Collapsible.Content snippet args when its close transition ends, which re-ran the region's effect and restarted the unmount timer, so a closed body stayed mounted for two transitions instead of one. Reading `open` through a derived keeps the effect from rerunning when only the args object changes. Assisted-by: Claude (Opus 5.5 Medium) --- .../components/ui/collapsible/collapsible-region.svelte | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte index 9910753395da..f56af787a7e7 100644 --- a/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte +++ b/ui/lib/ui/src/lib/components/ui/collapsible/collapsible-region.svelte @@ -18,8 +18,11 @@ // svelte-ignore state_referenced_locally let contentMounted = $state(open); + // bits-ui rebuilds the snippet args (with `open`) when its transition ends; the derived keeps that from restarting the unmount timer + const isOpen = $derived(open); + $effect(() => { - if (open) { + if (isOpen) { contentMounted = true; return; @@ -31,7 +34,7 @@ }); -
+
{#if contentMounted}
{@render children?.()} From 1094646c1fb706b0bc7cf3569c707a173032a01d Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 16:21:45 +0100 Subject: [PATCH 070/401] ui: set code in messages at the size of the text around it (#32892) Inline code and code blocks were 14px next to 16px text. Llama Mono has Llama Sans's x-height, so the two read as one size without the mono being scaled down. The chat form's editor follows. Assisted-by: Claude (Opus 5.5 Medium) --- .../app/content/MarkdownContent/markdown-content.css | 11 ++++++----- .../app/content/MarkdownEditor/MarkdownEditor.svelte | 3 +-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css index 5e894d0ae822..ed0bc932c29b 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/markdown-content.css @@ -17,7 +17,7 @@ overflow-x: visible; border-radius: 0; border: none; - font-size: 0.875rem; + font-size: 1em; } /* Base typography styles */ @@ -92,13 +92,14 @@ opacity: 0.7; } -/* Inline code */ +/* Inline code. Code is set at the size of the text around it, here and in the blocks below: Llama Mono + has Llama Sans's x-height, so the two read as one size without the mono being scaled down. */ .markdown-content :global(code:not(pre code)) { background: var(--surface-muted); color: var(--fg-muted); padding: 0.125rem 0.375rem; border-radius: 0.375rem; - font-size: 0.875rem; + font-size: 1em; } .markdown-content :global(pre) { @@ -358,7 +359,7 @@ div.markdown-user-content :global(.table-wrapper) { margin: 0; border-radius: 0; border: none; - font-size: 0.875rem; + font-size: 1em; } /* Mentions and hashtags */ @@ -761,7 +762,7 @@ div.markdown-user-content :global(.table-wrapper) { margin: 0; border-radius: 0; border: none; - font-size: 0.875rem; + font-size: 1em; } .markdown-content :global([data-view-mode='source'] .mermaid-scroll-container), diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte index 7564574828cb..3d5e0103ec82 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownEditor/MarkdownEditor.svelte @@ -89,7 +89,7 @@ { fontStyle: 'italic', tag: tags.emphasis }, { color: 'var(--fg-muted)', fontStyle: 'italic', tag: tags.quote }, { opacity: '0.7', tag: tags.strikethrough, textDecoration: 'line-through' }, - { fontFamily: 'var(--font-mono)', fontSize: '0.875rem', tag: tags.monospace } + { fontFamily: 'var(--font-mono)', tag: tags.monospace } ]); // The markdown language alone: markdown() would also bring the html, css and @@ -389,7 +389,6 @@ div :global(.cm-md-raw-code) { padding-inline: 1rem; font-family: var(--font-mono); - font-size: 0.875rem; background: var(--surface-code); border-inline: 1px solid color-mix(in oklch, var(--line-default) 30%, transparent); } From 325914defd2c1279a039366d999dff4c19a75b54 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 17:24:05 +0100 Subject: [PATCH 071/401] ui: show an agentic reply as a grouped Agent Trace (#32879) * ui: show tool calls in the trace as a grouped, plain-language log Tool calls and all the reasoning around them, up to the answer, collapse into one row whose title sums up what happened ("Ran 2 commands, read 1 file"), so a model that thinks before every call still reads as one row of work. Two calls, or one call with reasoning beside it, make a group; without per-turn stats a group spans turns. Each call reads as a sentence: built-in tools get hand-written phrasing in two tenses, MCP and unknown tools read as "Used ", and the generic block shows simple arguments as labelled fields. A call that has the argument a display setting picks (description by default, overridable per tool in Settings > Tools) shows it as the model wrote it instead, for any tool that declares it. A shell row always shows the command, after "Ran" or after that description, and opens into the terminal; the permission card shows the command that would run. An open group is a list of rows under one rule, with no icons in the headings; a running row shimmers. While a group is live its title says what is happening now ("Reading package.json", "Thinking"), with a timer since the prompt was sent, and the loop records the task's total time, which the response stats show. Thoughts and tool calls now stay collapsed while generating, with a one-time migration of the saved old default. Assisted-by: Claude (Opus 5.5 Medium) * ui: keep a live reply steady while its status changes The status line ( Loading weights, Processing 40% ) sat above the content before the first token and below it afterwards, and collapsed to nothing while tokens streamed, so the stats and actions under it jumped. It is now one row in the trace column with a trace row's box, shown only while nothing else is moving, and while a tool group closes the reply it becomes that group's live title instead. The model badge shows from the start of a live reply, the user message reserves its stats row while the prompt is processed, and a collapsed group title is muted. Assisted-by: Claude (Opus 5.5 Medium) * ui: glide a sent message to the top of the screen Sending snapped the page to its bottom in one frame, and layout that settled a moment later was followed with more snaps. The page now eases there: the target is read again every frame, so late layout bends the motion instead of ending it with a jump, and corrections shortly after a send are glided to as well. A frame that arrives late counts as one frame, so a busy page slows the glide instead of skipping it. Wheel, touch and scroll keys hand the page back at once; typing the next message does not. Reduced motion keeps the jump. Assisted-by: Claude (Opus 5.5 Medium) * ui: show tool images in the trace and in one slideshow of the thread A closed tool group shows every image its calls produced under its title, 64px tall at their own proportions, in a carousel once they overflow; the strip fades out when the group opens. A call with images shows tiny thumbnails beside its title while its row is closed. A group thumbnail, or an image in a user message, opens one slideshow of every image, audio clip and video in the open thread, in thread order, at the clicked item. Assisted-by: Claude (Opus 5.5 Medium) * ui: quiet the conversation around its messages Stats and actions under earlier messages stay hidden until the reader points at the message or tabs into it, changing only opacity so nothing moves; the latest exchange keeps them in view and touch screens keep them shown. A Display setting, Always show message statistics, keeps every message's statistics in view. With them out of sight the spacing tightens: messages sit 1rem apart, the answer sits 0.75rem from the trace rows around it, and the user message's stats and actions sit closer together. A queued message no longer sticks to the bottom of the screen and scrolls with the conversation. Assisted-by: Claude (Opus 5.5 Medium) * ui: name the agentic reply an Agent Trace and give basic chat its own view A reply that ran the agentic loop is now an Agent Trace: the component that renders it is ChatMessageAgentTrace, with matching class names and docs. A basic chat reply, with no tool calls, renders through the new ChatMessageAssistantResponse as its reasoning and its answer, without the trace's grouping, timer and permission handling. hasAgenticContent picks the view, so a live reply becomes a trace the moment its first tool call streams in. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/src/app.css | 24 + .../ChatAttachmentsList.svelte | 17 +- .../ChatMessageAssistant.svelte | 99 ++-- .../ChatMessageAssistantProcessingInfo.svelte | 24 +- .../ChatMessageAssistantResponse.svelte | 108 +++++ .../ChatMessageToolCallBlockDefault.svelte | 40 +- .../ChatMessageToolCallBlockEditFile.svelte | 48 +- ...essageToolCallBlockExecShellCommand.svelte | 174 ++++--- ...tMessageToolCallBlockFileGlobSearch.svelte | 6 +- ...ChatMessageToolCallBlockGetDatetime.svelte | 4 +- .../ChatMessageToolCallBlockGetInfo.svelte | 10 +- .../ChatMessageToolCallBlockGrepSearch.svelte | 4 +- .../ChatMessageToolCallBlockReadFile.svelte | 23 +- .../ChatMessageToolCallBlockReadMedia.svelte | 9 +- ...atMessageToolCallBlockRunJavascript.svelte | 4 +- ...atMessageToolCallBlockSearchResults.svelte | 17 +- .../ChatMessageToolCallBlockWriteFile.svelte | 25 +- .../ChatMessageToolCallGroup.svelte | 122 +++++ .../ChatMessageToolCall/ToolCallBlock.svelte | 124 +++-- .../ToolCallElapsed.svelte | 36 ++ .../ChatMessageToolCall/ToolCallTitle.svelte | 32 ++ .../ChatMessageToolCall/parsers/edit-file.ts | 39 +- .../parsers/tool-call-phrasing.ts | 445 ++++++++++++++++++ .../ChatMessageToolCall/tool-call-elapsed.ts | 28 ++ .../ChatMessageUser/ChatMessageUser.svelte | 28 +- .../ChatMessageUserBubble.svelte | 1 + .../ChatMessageUserPending.svelte | 2 +- .../ChatMessageActionCard.svelte | 10 +- ...tMessageActionCardPermissionRequest.svelte | 14 +- .../ChatMessages/ChatMessageAgentTrace.svelte | 410 ++++++++++++++++ .../ChatMessageAgenticContent.svelte | 273 ----------- .../ChatMessageReasoningBlock.svelte | 4 +- .../ChatMessageStatistics.svelte | 29 +- .../app/chat/ChatMessages/ChatMessages.svelte | 6 +- .../app/chat/ChatScreen/ChatScreen.svelte | 5 +- .../ChatScreenDialogsAndAlerts.svelte | 9 + .../chat/src/lib/components/app/chat/index.ts | 47 +- .../content/CollapsibleContentBlock.svelte | 57 ++- .../src/lib/components/app/content/index.ts | 4 + .../SettingsChat/SettingsChatToolsTab.svelte | 106 ++++- .../lib/constants/css-classes.constants.ts | 3 - ui/apps/chat/src/lib/constants/index.ts | 1 + .../lib/constants/settings-keys.constants.ts | 3 + .../src/lib/constants/settings.constants.ts | 29 +- .../constants/tool-call-phrasing.constants.ts | 175 +++++++ ui/apps/chat/src/lib/enums/index.ts | 1 + ui/apps/chat/src/lib/enums/tools.enums.ts | 13 + .../lib/hooks/use-stick-to-bottom.svelte.ts | 204 +++++++- .../src/lib/services/migration.service.ts | 37 +- .../src/lib/stores/agentic/gates.svelte.ts | 18 +- .../src/lib/stores/agentic/index.svelte.ts | 30 +- ui/apps/chat/src/lib/stores/index.ts | 3 + .../chat/src/lib/stores/mcp/index.svelte.ts | 1 + .../src/lib/stores/media-gallery.svelte.ts | 52 ++ ui/apps/chat/src/lib/types/agentic.d.ts | 14 +- ui/apps/chat/src/lib/types/chat.d.ts | 2 + ui/apps/chat/src/lib/types/index.ts | 3 + ui/apps/chat/src/lib/types/tools.d.ts | 31 +- ui/apps/chat/src/lib/utils/agentic.ts | 31 ++ ui/apps/chat/src/lib/utils/attachment-type.ts | 19 + ui/apps/chat/src/lib/utils/index.ts | 13 +- ui/apps/chat/src/lib/utils/memoize-bounded.ts | 28 ++ .../chat/src/lib/utils/tool-call-shown-arg.ts | 39 ++ ui/apps/chat/tests/client/README-perf.md | 2 +- .../client/agentic-stream.perf.svelte.test.ts | 2 +- .../client/assistant-response.svelte.test.ts | 63 +++ .../components/AgenticPerfWrapper.svelte | 4 +- ...xec-shell-command-streaming.svelte.test.ts | 48 +- .../tests/client/media-gallery.svelte.test.ts | 75 +++ .../permission-request-command.svelte.test.ts | 67 +++ .../client/stick-to-bottom.svelte.test.ts | 102 +++- .../tests/client/task-timer.svelte.test.ts | 84 ++++ .../tool-call-in-progress.svelte.test.ts | 16 +- .../ChatMessageToolCallBlock.stories.svelte | 5 + .../ChatMessageToolCallGroup.stories.svelte | 70 +++ .../messages/ToolCallGroupStoryHost.svelte | 46 ++ .../tests/stories/chat/messages/fixtures.ts | 67 +++ .../settings-tool-call-in-progress.test.ts | 6 +- .../tests/unit/tool-call-phrasing.test.ts | 344 ++++++++++++++ .../tests/unit/tool-call-shown-arg.test.ts | 38 ++ 80 files changed, 3595 insertions(+), 661 deletions(-) create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte delete mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte create mode 100644 ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts create mode 100644 ui/apps/chat/src/lib/stores/media-gallery.svelte.ts create mode 100644 ui/apps/chat/src/lib/utils/memoize-bounded.ts create mode 100644 ui/apps/chat/src/lib/utils/tool-call-shown-arg.ts create mode 100644 ui/apps/chat/tests/client/assistant-response.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/media-gallery.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/permission-request-command.svelte.test.ts create mode 100644 ui/apps/chat/tests/client/task-timer.svelte.test.ts create mode 100644 ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte create mode 100644 ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte create mode 100644 ui/apps/chat/tests/unit/tool-call-phrasing.test.ts create mode 100644 ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts diff --git a/ui/apps/chat/src/app.css b/ui/apps/chat/src/app.css index 24ba6cec44bb..03e0e7d27424 100644 --- a/ui/apps/chat/src/app.css +++ b/ui/apps/chat/src/app.css @@ -388,3 +388,27 @@ .stick-to-bottom-pin { height: 1px; } + +/* + * A message's stats and actions stay out of the way until the reader points at + * it or tabs into it. Only opacity changes, so their room is kept and nothing + * moves when they appear. Touch screens have no hover, so they keep them shown. + */ +@media (hover: hover) { + .message-meta { + opacity: 0; + transition: opacity 150ms ease-out; + } + + .chat-message-user:hover .message-meta, + .chat-message-assistant:hover .message-meta, + .message-meta:focus-within { + opacity: 1; + } +} + +@media (hover: hover) and (prefers-reduced-motion: reduce) { + .message-meta { + transition: none; + } +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte index cc9b940df6de..611e52a75e40 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsList/ChatAttachmentsList.svelte @@ -6,8 +6,14 @@ ScrollCarousel } from '#lib/components/app/index.ts'; import { ScrollCarouselVariant } from '#lib/enums/index.ts'; + import { mediaGalleryStore } from '#lib/stores/index.ts'; import type { DatabaseMessageExtraMcpResource } from '#lib/types/index.ts'; - import { getAttachmentDisplayItems, isMcpPrompt, isMcpResource } from '#lib/utils/index.ts'; + import { + getAttachmentDisplayItems, + isMcpPrompt, + isMcpResource, + isMediaExtra + } from '#lib/utils/index.ts'; interface Props { class?: string; @@ -26,12 +32,15 @@ limitToSingleRow?: boolean; // For vision modality check activeModelId?: string; + /** A message's attachments: media opens the conversation's slideshow at it */ + conversationGallery?: boolean; } let { activeModelId, attachments = [], class: className = '', + conversationGallery = false, // Default to small size for form previews imageClass = '', imageHeight = 'h-24', @@ -55,6 +64,12 @@ event?.stopPropagation(); event?.preventDefault(); + if (conversationGallery && item.attachment && isMediaExtra(item.attachment)) { + mediaGalleryStore.show(item.attachment); + + return; + } + // Find the index of the clicked item among non-MCP attachments const nonMcpItems = displayItems.filter((i) => !isMcpPrompt(i) && !isMcpResource(i)); const index = nonMcpItems.findIndex((i) => i.id === item.id); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte index 72679c8f1238..5a5b3cd92a5f 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistant.svelte @@ -1,20 +1,21 @@ -
-
- - {modelLoadingText ?? - processingState.getPromptProgressText() ?? - processingState.getProcessingMessage() ?? - 'Processing...'} - -
+
+ {text}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte new file mode 100644 index 000000000000..259da9a9a2f3 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageAssistant/ChatMessageAssistantResponse.svelte @@ -0,0 +1,108 @@ + + +
+ {#each sections as section, index (index)} + {#if section.type === AgenticSectionType.TEXT} +
+ +
+ {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING} + toggleExpanded(index, section)} + open={isExpanded(index, section)} + {section} + /> + {/if} + {/each} + + {#if showStatus} + + {/if} +
+ + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte index f959d00285db..0cbe86535a22 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte @@ -3,7 +3,9 @@ // Renders section.toolArgs / section.toolResult directly using the // shared chrome shell. + import { simpleToolArgFields } from './parsers/tool-call-phrasing'; import ToolCallBlock from './ToolCallBlock.svelte'; + import ToolCallTitle from './ToolCallTitle.svelte'; import { Loader2 } from '@lucide/svelte'; import { MarkdownContent, SyntaxHighlightedCode } from '#lib/components/app/index.ts'; import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts'; @@ -13,7 +15,6 @@ import { classifyToolResult, formatJsonPretty, - getToolUi, parseToolResultWithMedia } from '#lib/utils/index.ts'; @@ -27,14 +28,31 @@ let { attachments, isStreaming, onToggle, open, section }: Props = $props(); - const title = $derived(getToolUi(section.toolName)?.label ?? section.toolName ?? ''); + const argFields = $derived(simpleToolArgFields(section.toolArgs)); const outputKind = $derived(classifyToolResult(section.toolResult)); const parsedLines: ToolResultLine[] = $derived( section.toolResult ? parseToolResultWithMedia(section.toolResult, attachments) : [] ); - +{#snippet inputFields(fields: { label: string; value: string }[])} +
+ {#each fields as field, i (i)} +
{field.label}
+ +
{field.value}
+ {/each} +
+{/snippet} + + + {#snippet titleSnippet(phrase)} + + {/snippet} + {#snippet children(_meta, ctx)} {#if ctx.isStreamingCall}
@@ -70,12 +88,16 @@ Input
- + {#if argFields} + {@render inputFields(argFields)} + {:else} + + {/if} {/if}
- import { parseEditFileMeta, parseEditFileTitleMeta } from './parsers/edit-file'; + import { + editFileDiffStats, + parseEditFileMeta, + parseEditFileTitleMeta + } from './parsers/edit-file'; import ToolCallBlock from './ToolCallBlock.svelte'; + import ToolCallTitle from './ToolCallTitle.svelte'; import { XCircle } from '@lucide/svelte'; import { SyntaxHighlightedCode } from '#lib/components/app/index.ts'; import { MAX_HEIGHT_CODE_BLOCK, RESULT_STAT_SEPARATOR } from '#lib/constants/index.ts'; - import { FileTypeText } from '#lib/enums/index.ts'; + import { AgenticSectionType, FileTypeText } from '#lib/enums/index.ts'; import { toolsStore } from '#lib/stores/index.ts'; import type { AgenticSection } from '#lib/types/index.ts'; import { @@ -24,7 +29,7 @@ let { isStreaming, onToggle, open, section }: Props = $props(); const editFileMeta = $derived(parseEditFileTitleMeta(section)); - // body-only: the full meta parses the embedded edit strings, and these + // body-only: the full meta parses the embedded edit strings, and these two // deriveds are read solely from the children snippet, which renders only // while the block is expanded const editFileBody = $derived(parseEditFileMeta(section)); @@ -32,23 +37,36 @@ const editDiffs = $derived( (editFileBody?.edits ?? []).map((edit) => computeLineDiff(edit.oldText, edit.newText)) ); + + // Lines added and removed, for the title once the edit has applied. The + // title always renders and sections are rebuilt on every streamed chunk, + // so the parse and diff are remembered per call instead of re-run each time. + const diffStats = $derived( + section.type === AgenticSectionType.TOOL_CALL && section.toolResult + ? editFileDiffStats(section) + : null + ); - {#snippet titleSnippet()} - - Edit file - - - - {abbreviateHome(editFileMeta?.filePath ?? '', home)} + {#snippet titleSnippet(phrase)} + + {#if diffStats} + + +{diffStats.added} + + -{diffStats.removed} + {/if} - {#if editFileMeta?.errorMessage} - (failed) - {/if} - - + {#if editFileMeta?.errorMessage} + (failed) + {/if} + {/snippet} {#snippet children(_meta, ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte index 06d417f7aa41..d795356138cf 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockExecShellCommand.svelte @@ -1,15 +1,15 @@ -{#snippet execShellTitle()} +{#snippet promptLine()} {#if cwd} {wdDisplay} - - $ {/if} + $ + {#if highlightedCommandHtml} {@html highlightedCommandHtml} {:else} @@ -239,73 +239,98 @@ {onToggle} {open} {section} - spinIconWhenActive={true} - wrapper={CollapsibleTerminalBlock} > - {#snippet titleSnippet()} - {@render execShellTitle()} + {#snippet titleSnippet(phrase)} + + + {phrase.label} + + {#if execShellMeta?.command} + + {execShellMeta.command} + + {/if} + {/snippet} {#snippet children(_meta, ctx)} - {#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)} -
- - Executing command... -
- {:else if ctx.isInterrupted} -
- - - Command interrupted before it returned output +
+
+ {@render promptLine()}
- {:else if execShellError} -
- - {execShellError} -
- {:else if section.toolResult} -
- {#each outputLines as line, i (i)} -
{line.text}
- - {#if line.media?.type === AttachmentType.IMAGE} - {line.media.name} - {/if} - {/each} + {#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)} +
+ + Executing command... +
+ {:else if ctx.isInterrupted} +
+ + + Command interrupted before it returned output +
+ {:else if execShellError} +
+ + + {execShellError} +
+ {:else if section.toolResult} +
+ {#each outputLines as line, i (i)} +
+ {line.text} +
+ + {#if line.media?.type === AttachmentType.IMAGE} + {line.media.name} + {/if} + {/each} - {#if isExitCodeFinalLine && execShellExitStatus} -
- {#if execShellExitStatus.timedOut} - + {#if isExitCodeFinalLine && execShellExitStatus} +
+ {#if execShellExitStatus.timedOut} + - timed out + timed out - · + · - exit {execShellExitStatus.code} - {:else if execShellExitStatus.code === 0} - + exit {execShellExitStatus.code} + {:else if execShellExitStatus.code === 0} + - exit 0 - {:else} - + exit 0 + {:else} + - exit {execShellExitStatus.code} - {/if} -
- {/if} -
- {/if} + exit {execShellExitStatus.code} + {/if} +
+ {/if} +
+ {/if} +
{/snippet} @@ -343,6 +368,29 @@ } } + .exec-title-command { + color: var(--fg-muted); + font-size: 0.92em; + } + + .terminal-frame { + display: grid; + gap: 0.5rem; + min-width: 0; + padding: 0.625rem 0.75rem; + border-radius: var(--radius-md, 0.375rem); + background: var(--surface-code); + border: 1px solid color-mix(in oklch, var(--line-default) 30%, transparent); + } + + .exec-prompt-line { + word-break: break-word; + } + + .exec-prompt-line :global(.font-mono) { + white-space: pre-wrap; + } + .terminal-output.is-clamped { max-height: 28rem; overflow-y: auto; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte index 67c5e15c348d..f2da8cbf7e52 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockFileGlobSearch.svelte @@ -20,11 +20,9 @@ - {#snippet titleSnippet()} + {#snippet titleSnippet(phrase)} {#if fileGlobMeta} - {fileGlobMeta.include === '**' ? 'List files' : 'Search files'}  + {phrase.label}  {#if fileGlobMeta.include !== '**'} {fileGlobMeta.include} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte index efcec2a3fced..0b3486b7e479 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetDatetime.svelte @@ -1,5 +1,5 @@
- - {#if showSpinner} Current time diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte index 3b68a2d85d05..bfc1aff976f7 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockGetInfo.svelte @@ -48,15 +48,7 @@ const cwdDisplay = $derived(abbreviateHome(infoMeta.cwd ?? '', home)); - + {#snippet children(meta, _ctx)} {#if meta?.errorMessage}
- {#snippet titleSnippet()} + {#snippet titleSnippet(phrase)} {#if grepMeta} - Search for  + {phrase.label}  {grepMeta.pattern} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte index e8c424605b61..eefdc0021f88 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadFile.svelte @@ -1,6 +1,7 @@ - {#snippet titleSnippet()} - - Read file - - - {readFileMeta?.fileName} - - {#if readFileMeta?.lineRange} - - (lines {readFileMeta.lineRange.start}-{readFileMeta.lineRange.end}) - - {/if} - - + {#snippet titleSnippet(phrase)} + + {#if readFileMeta?.lineRange} + + (lines {readFileMeta.lineRange.start}-{readFileMeta.lineRange.end}) + + {/if} + {/snippet} {#snippet children(_meta, _ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte index 3961b86d0c2c..1091b8dcbbb9 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte @@ -1,6 +1,7 @@ - {#snippet titleSnippet()} - - Read media - - {readMediaMeta?.fileName} - + {#snippet titleSnippet(phrase)} + {/snippet} {#snippet children(_meta, _ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte index 2fd1866f3d29..e20a4f4bae3c 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockRunJavascript.svelte @@ -6,7 +6,6 @@ import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts'; import { FileTypeText } from '#lib/enums/index.ts'; import type { AgenticSection } from '#lib/types/index.ts'; - import { getToolUi } from '#lib/utils/index.ts'; interface Props { section: AgenticSection; @@ -18,10 +17,9 @@ let { isStreaming, onToggle, open, section }: Props = $props(); const runJsMeta = $derived(parseRunJavascriptMeta(section)); - const title = $derived(getToolUi(section.toolName)?.label ?? section.toolName ?? ''); - + {#snippet children(meta, ctx)} {#if ctx.isPending}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte index 78fba40f98f8..efbbde97446a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockSearchResults.svelte @@ -2,7 +2,6 @@ import * as HoverCard from '@ggml-org/llama-ui/ui/hover-card'; import { Globe, Loader2 } from '@lucide/svelte'; import { CollapsibleContentBlock } from '#lib/components/app/index.ts'; - import { ICON_CLASS_DEFAULT, ICON_CLASS_SPIN } from '#lib/constants/index.ts'; import { AgenticSectionType } from '#lib/enums/index.ts'; import { mcpStore } from '#lib/stores/index.ts'; import type { AgenticSection, SearchResult } from '#lib/types/index.ts'; @@ -30,13 +29,6 @@ const results = $derived(extractSearchResults(section.toolResult)); const query = $derived(extractSearchQuery(section.toolArgs)); - // Same icon-resolution chain as ChatMessageToolCallBlockDefault so - // MCP-server branding is consistent across both views. Spinner wins - // while the call is in flight so the user sees execution status. - const iconUrl = $derived(showSpinner ? null : mcpStore.getServerFaviconForTool(section.toolName)); - const icon = $derived(showSpinner ? Loader2 : undefined); - const iconClass = $derived(showSpinner ? ICON_CLASS_SPIN : ICON_CLASS_DEFAULT); - // Verb reflects state: "Searching" while the call is in flight, "Searched" // once results (or a definitive empty response) have arrived. Lets the // heading read as a live progress indicator rather than a completed @@ -154,7 +146,14 @@ {/if} {/snippet} - + {#if results.length > 0}
{#each results as result (result.url)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte index 394287ec1aca..c0fdfa8ed8db 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockWriteFile.svelte @@ -1,6 +1,7 @@ - {#snippet titleSnippet()} - - Write file - - - - {abbreviateHome(writeFileMeta?.filePath ?? '', home)} - - - {#if writeFileMeta?.errorMessage} - (failed) - {/if} - - + {#snippet titleSnippet(phrase)} + + {#if writeFileMeta?.errorMessage} + (failed) + {/if} + {/snippet} {#snippet children(_meta, ctx)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte new file mode 100644 index 000000000000..3f8acb39ec2e --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte @@ -0,0 +1,122 @@ + + +
+ + {#snippet titleSnippet()} + + + {summary} + + {/snippet} + + {#snippet titleSuffix()} + {#if elapsedStartedAt !== null} + + {/if} + {/snippet} + +
+ {@render children()} +
+
+ + + {#if images.length > 0 && !open} +
+ + {#each images as image, i (i)} + + {/each} + +
+ {/if} +
+ + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte index cafb077e5366..f8f9ee05be45 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte @@ -1,22 +1,27 @@ - + {#snippet titleSnippet()} + {#if blockTitle} + {@render blockTitle(phrase)} + {:else} + {title ?? formatToolCallLine(phrase)} + {/if} + {/snippet} + + {#snippet titleSuffix()} + {#if elapsedStart !== null} + + {/if} + + {#if images.length > 0 && !open} + + {#each images as image, i (i)} + + {/each} + + {/if} + {/snippet} + {@render children(meta, { isCodeStreaming, isInterrupted, @@ -148,4 +168,4 @@ isStreaming, isStreamingCall })} - + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte new file mode 100644 index 000000000000..b83c74933036 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte @@ -0,0 +1,36 @@ + + + + {label} + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte new file mode 100644 index 000000000000..c16e0cdd85fe --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallTitle.svelte @@ -0,0 +1,32 @@ + + + + {label} + + {#if target || children} + + {#if target} + {target} + {/if} + + {@render children?.()} + + {/if} + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts index 006ea186f405..72c1306a71af 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts @@ -11,14 +11,14 @@ import { parseToolArgs } from './_shared'; import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; -import { BuiltInTool } from '#lib/enums/index.ts'; +import { BuiltInTool, DiffLineKind } from '#lib/enums/index.ts'; import type { AgenticSection, EditFileEdit, EditFileMeta, EditFileTitleMeta } from '#lib/types/index.ts'; -import { tryParseToolResultObject } from '#lib/utils/index.ts'; +import { computeLineDiff, memoizeBounded, tryParseToolResultObject } from '#lib/utils/index.ts'; export function parseEditFileMeta(section: AgenticSection): EditFileMeta | null { const args = parseToolArgs(BuiltInTool.SERVER_EDIT_FILE, section, { partial: true }); @@ -112,3 +112,38 @@ export function parseEditFileTitleMeta(section: AgenticSection): EditFileTitleMe return { editsApplied, errorMessage, fileName, filePath, resultMessage }; } + +/** + * Lines added and removed by a finished `edit_file` call, or null when it + * failed or changed nothing. Memoized per call: the title that shows it + * renders for every row, while sections are rebuilt on every streamed chunk. + * The id names the call, so a call without one is computed uncached; the + * sizes guard against an id that another conversation reuses. + */ +export const editFileDiffStats = memoizeBounded( + buildEditFileDiffStats, + (section) => + section.toolCallId + ? `${section.toolCallId}:${section.toolArgs?.length ?? 0}:${section.toolResult?.length ?? 0}` + : null, + 64 +); + +function buildEditFileDiffStats( + section: AgenticSection +): { added: number; removed: number } | null { + const meta = parseEditFileMeta(section); + + if (!meta || meta.errorMessage || meta.edits.length === 0) return null; + + const stats = { added: 0, removed: 0 }; + + for (const edit of meta.edits) { + for (const line of computeLineDiff(edit.oldText, edit.newText)) { + if (line.kind === DiffLineKind.ADD) stats.added++; + else if (line.kind === DiffLineKind.REMOVE) stats.removed++; + } + } + + return stats; +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts new file mode 100644 index 000000000000..8792bc90aac4 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts @@ -0,0 +1,445 @@ +// Plain-language lines for tool calls: what one call did ("Read a file +// sheet_new.jpg"), what it is doing now ("Reading package.json") and what +// a run of calls did ("Ran 3 commands, read 2 files"). A call that has the +// arg the settings pick (`description` by default) shows it as the model +// wrote it. Otherwise built-in tools use TOOL_CALL_PHRASING, and MCP and +// unknown tools read as "Used " with their main argument. + +import { extractToolArgString, fileNameFromPath } from './_shared'; +import { + TOOL_ARG_PATH_KEYS, + TOOL_CALL_MAIN_ARG_KEYS, + TOOL_CALL_PHRASING, + TOOL_CALL_SHOWN_ARG_DEFAULT, + TOOL_CALL_SIMPLE_ARG_MAX_CHARS, + TOOL_CALL_SUMMARY, + TOOL_CALL_TARGET_MAX_CHARS, + TOOL_CALL_THINKING_LABEL, + TOOL_SEARCH_LOAD_PHRASING, + TOOL_SEARCH_PHRASING_NAME, + TOOL_SEARCH_PHRASING_SELECT_PREFIX, + TOOL_SEARCH_QUERY_PHRASING, + WEB_SEARCH_PHRASING +} from '#lib/constants/index.ts'; +import { AgenticSectionType, BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts'; +import type { AgenticSection, ToolCallDescription, ToolCallPhrasing } from '#lib/types/index.ts'; +import { isWebSearchToolName, memoizeBounded, parsePartialJsonArgs } from '#lib/utils/index.ts'; + +/** How many results each cache below holds. */ +const CACHE_MAX_SIZE = 256; +/** Args longer than this ( whole files ) are not worth holding as cache keys. */ +const CACHE_MAX_ARGS_CHARS = 2000; + +type ToolArgField = { label: string; value: string }; + +function shorten(text: string): string { + const oneLine = text.replace(/\s+/g, ' ').trim(); + + return oneLine.length > TOOL_CALL_TARGET_MAX_CHARS + ? `${oneLine.slice(0, TOOL_CALL_TARGET_MAX_CHARS - 3)}...` + : oneLine; +} + +function stringArg(args: Record | null, key: string): string | undefined { + const value = args?.[key]; + + return typeof value === 'string' && value.trim() ? value : undefined; +} + +function genericMainArg(args: Record | null): string | undefined { + if (!args) return undefined; + + for (const key of TOOL_CALL_MAIN_ARG_KEYS) { + const value = stringArg(args, key); + + if (value) return value; + } + + for (const value of Object.values(args)) { + if (typeof value === 'number') return String(value); + + if (typeof value === 'string' && value.trim() && value.length <= TOOL_CALL_TARGET_MAX_CHARS) { + return value; + } + } + + return undefined; +} + +function genericPhrasing(toolName: string): ToolCallPhrasing { + return { + object: toolName, + past: 'Used', + present: 'Using', + summary: ToolCallSummaryKind.OTHER, + targetObject: toolName + }; +} + +interface ResolvedCall { + phrasing: ToolCallPhrasing; + target?: string; + count?: number; +} + +function resolveCall(toolName: string, toolArgs: string): ResolvedCall { + // write_file and edit_file args hold whole files: read the path with a + // targeted match instead of parsing the blob + if ( + toolName === BuiltInTool.SERVER_READ_FILE || + toolName === BuiltInTool.SERVER_WRITE_FILE || + toolName === BuiltInTool.SERVER_EDIT_FILE || + toolName === BuiltInTool.BROWSER_READ_MEDIA + ) { + const path = + extractToolArgString(toolArgs, TOOL_ARG_PATH_KEYS) ?? + stringArg(parsePartialJsonArgs(toolArgs), 'path'); + + return { phrasing: TOOL_CALL_PHRASING[toolName], target: fileNameFromPath(path) }; + } + + const args = toolArgs ? parsePartialJsonArgs(toolArgs) : null; + + if (toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND) { + // the targeted match keeps the command in the line while a later arg + // is still streaming and the JSON does not parse + return { + phrasing: TOOL_CALL_PHRASING[toolName], + target: stringArg(args, 'command') ?? extractToolArgString(toolArgs, ['command']) + }; + } + + switch (toolName) { + case BuiltInTool.SERVER_GREP_SEARCH: + return { phrasing: TOOL_CALL_PHRASING[toolName], target: stringArg(args, 'pattern') }; + + case BuiltInTool.SERVER_FILE_GLOB_SEARCH: { + const include = stringArg(args, 'include'); + + return { + phrasing: TOOL_CALL_PHRASING[toolName], + target: include && include !== '**' ? include : undefined + }; + } + + case BuiltInTool.BROWSER_SEARCH_CHATS: { + const matches = Array.isArray(args?.by_matches) + ? args.by_matches.filter((m): m is string => typeof m === 'string' && m.trim() !== '') + : []; + + return { phrasing: TOOL_CALL_PHRASING[toolName], target: matches.join(', ') || undefined }; + } + + case TOOL_SEARCH_PHRASING_NAME: { + const query = stringArg(args, 'query')?.trim(); + + if (query?.startsWith(TOOL_SEARCH_PHRASING_SELECT_PREFIX)) { + const names = query + .slice(TOOL_SEARCH_PHRASING_SELECT_PREFIX.length) + .split(',') + .map((name) => name.trim()) + .filter(Boolean); + + return { + count: Math.max(names.length, 1), + phrasing: TOOL_SEARCH_LOAD_PHRASING, + target: names.join(', ') || undefined + }; + } + + return { phrasing: TOOL_SEARCH_QUERY_PHRASING, target: query }; + } + } + + if (isWebSearchToolName(toolName)) { + return { phrasing: WEB_SEARCH_PHRASING, target: stringArg(args, 'query') }; + } + + const known = TOOL_CALL_PHRASING[toolName]; + + if (known) return { phrasing: known }; + + return { phrasing: genericPhrasing(toolName), target: genericMainArg(args) }; +} + +/** An arg name the settings can pick: a plain key, so it is safe in a pattern. */ +const SHOWN_ARG_PATTERN = /^[\w-]+$/; + +/** + * The value of the arg a call's line shows, when the call has it. Whole-file + * args are not parsed for it: the targeted match reads it instead. + */ +function shownArgValue(toolArgs: string, shownArg: string | null): string | undefined { + if (!shownArg || !toolArgs || !SHOWN_ARG_PATTERN.test(shownArg)) return undefined; + + const value = + toolArgs.length <= CACHE_MAX_ARGS_CHARS + ? stringArg(parsePartialJsonArgs(toolArgs), shownArg) + : extractToolArgString(toolArgs, [shownArg]); + + return value?.trim() || undefined; +} + +/** + * Describe one tool call as a short sentence, in the past tense once it is + * done and the present tense while `running`. `shownArg` names the arg + * shown instead when the call has it ( null for none ). + */ +export function describeToolCall( + toolName: string | undefined, + toolArgs: string | undefined, + running = false, + shownArg: string | null = TOOL_CALL_SHOWN_ARG_DEFAULT +): ToolCallDescription { + return describeCached(toolName || 'a tool', toolArgs ?? '', running, shownArg ?? ''); +} + +// Sections are rebuilt on every streamed chunk, so the same finished call is +// described again and again: remember the answer for its args. Every caller +// of one call reads the same frozen object, so a title cannot edit the line +// out for the others. +const describeCached = memoizeBounded( + (name: string, args: string, running: boolean, shownArg: string) => + Object.freeze(buildDescription(name, args, running, shownArg || null)), + (name, args, running, shownArg) => + args.length <= CACHE_MAX_ARGS_CHARS + ? `${running ? 1 : 0}\0${shownArg}\0${name}\0${args}` + : null, + CACHE_MAX_SIZE +); + +function buildDescription( + name: string, + args: string, + running: boolean, + shownArg: string | null +): ToolCallDescription { + const { count = 1, phrasing, target } = resolveCall(name, args); + const shown = shownArgValue(args, shownArg); + // an arg the row already shows as its target ( a shell command ) would + // only repeat it + const described = shown && shown !== target?.trim() ? shown : undefined; + + if (described) { + return { + count, + described: true, + // shown as the model wrote it: rewriting its tense by rule mangles + // anything that does not start with a plain verb + label: shorten(described).replace(/[.\s]+$/, ''), + quoted: false, + summary: phrasing.summary + }; + } + + const verb = running ? phrasing.present : phrasing.past; + const shortTarget = target ? shorten(target) : undefined; + const object = shortTarget ? phrasing.targetObject : phrasing.object; + + return { + count, + label: object ? `${verb} ${object}` : verb, + quoted: Boolean(phrasing.quoteTarget && shortTarget), + summary: phrasing.summary, + target: shortTarget + }; +} + +/** One line of plain text for a description, e.g. `Searched for 'issue'`. */ +export function formatToolCallLine(description: ToolCallDescription): string { + if (!description.target) return description.label; + + const target = description.quoted ? `'${description.target}'` : description.target; + + return `${description.label} ${target}`; +} + +export function isToolCallSection(section: AgenticSection): boolean { + return ( + section.type === AgenticSectionType.TOOL_CALL || + section.type === AgenticSectionType.TOOL_CALL_PENDING || + section.type === AgenticSectionType.TOOL_CALL_STREAMING + ); +} + +/** True while the call has no result yet and the reply is still streaming. */ +export function isToolCallRunning(section: AgenticSection, isStreaming: boolean): boolean { + return ( + isStreaming && + (section.type === AgenticSectionType.TOOL_CALL_PENDING || + section.type === AgenticSectionType.TOOL_CALL_STREAMING) + ); +} + +/** + * Summarize a run of tool calls, e.g. "Ran 3 commands, read 2 files". + * Kinds keep the order they first appear in; other tools come last. + */ +export function summarizeToolCalls(sections: readonly AgenticSection[]): string { + const counts = new Map(); + + for (const section of sections) { + if (!isToolCallSection(section)) continue; + + const { count, summary } = describeToolCall(section.toolName, section.toolArgs); + + counts.set(summary, (counts.get(summary) ?? 0) + count); + } + + const other = counts.get(ToolCallSummaryKind.OTHER); + + if (other !== undefined) { + counts.delete(ToolCallSummaryKind.OTHER); + counts.set(ToolCallSummaryKind.OTHER, other); + } + + const clauses = [...counts].map(([kind, n]) => TOOL_CALL_SUMMARY[kind](n)); + const text = clauses.join(', '); + + return text.charAt(0).toUpperCase() + text.slice(1); +} + +/** + * What a run of calls is doing now, in user words ("Running a command", + * "Thinking"): the model thinking at its end, or the last call still + * running; null when neither is. + */ +export function describeToolActivity( + sections: readonly AgenticSection[], + isStreaming: boolean, + executingToolCallId?: string | null, + shownArgFor: (toolName: string | undefined) => string | null = () => TOOL_CALL_SHOWN_ARG_DEFAULT +): string | null { + // the model thinking at the end of the run, between calls or before its answer + if (isStreaming && sections.at(-1)?.type === AgenticSectionType.REASONING_PENDING) { + return TOOL_CALL_THINKING_LABEL; + } + + for (let i = sections.length - 1; i >= 0; i--) { + const section = sections[i]; + const executing = + section.toolCallId !== undefined && section.toolCallId === executingToolCallId; + + if (executing || isToolCallRunning(section, isStreaming)) { + return formatToolCallLine( + describeToolCall(section.toolName, section.toolArgs, true, shownArgFor(section.toolName)) + ); + } + } + + return null; +} + +/** + * Tool args as labelled fields when every value is a short, one-line + * scalar; null when the args need the JSON view instead. Memoized like + * describeToolCall: the row that shows them re-renders on every chunk. + */ +export function simpleToolArgFields(toolArgs: string | undefined): ToolArgField[] | null { + return toolArgs ? argFieldsCached(toolArgs) : null; +} + +const argFieldsCached = memoizeBounded( + buildSimpleToolArgFields, + (toolArgs) => (toolArgs.length <= CACHE_MAX_ARGS_CHARS ? toolArgs : null), + CACHE_MAX_SIZE +); + +function buildSimpleToolArgFields(toolArgs: string): ToolArgField[] | null { + let parsed: unknown; + + try { + parsed = JSON.parse(toolArgs); + } catch { + return null; + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; + + const entries = Object.entries(parsed as Record); + + if (entries.length === 0) return null; + + const fields: ToolArgField[] = []; + + for (const [key, value] of entries) { + if (value !== null && typeof value === 'object') return null; + + const text = String(value); + + if (text.length > TOOL_CALL_SIMPLE_ARG_MAX_CHARS || text.includes('\n')) return null; + + fields.push({ label: humanizeArgKey(key), value: text }); + } + + return fields; +} + +/** `max_results` / `maxResults` -> `Max results`. */ +export function humanizeArgKey(key: string): string { + const words = key + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/[_-]+/g, ' ') + .trim() + .toLowerCase(); + + return words.charAt(0).toUpperCase() + words.slice(1); +} + +export function isReasoningSection(section: AgenticSection): boolean { + return ( + section.type === AgenticSectionType.REASONING || + section.type === AgenticSectionType.REASONING_PENDING + ); +} + +/** + * Split section positions into single items and runs of tool work, e.g. + * [0, [1, 2, 3], 4]. A run is the calls and all the reasoning around them, + * up to the next text, so the answer follows the work as one row: it is + * grouped once it holds `minCalls` calls, or one call with reasoning beside + * it. Reasoning with no call in reach, and text, stay apart. + */ +export function groupToolCallRuns( + sections: readonly AgenticSection[], + indices: readonly number[], + minCalls: number +): (number | number[])[] { + const items: (number | number[])[] = []; + + let run: number[] = []; + let calls = 0; + // reasoning seen since the last call: it ends the run if text follows, + // and leads into it if another call does + let thinking: number[] = []; + + const flush = () => { + const whole = [...run, ...thinking]; + + if (calls >= minCalls || (calls > 0 && whole.length > calls)) items.push(whole); + else items.push(...whole); + + run = []; + thinking = []; + calls = 0; + }; + + for (const index of indices) { + const section = sections[index]; + + if (isToolCallSection(section)) { + run.push(...thinking, index); + thinking = []; + calls++; + } else if (isReasoningSection(section)) { + thinking.push(index); + } else { + flush(); + items.push(index); + } + } + + flush(); + + return items; +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts new file mode 100644 index 000000000000..89a5fd2ebb26 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/tool-call-elapsed.ts @@ -0,0 +1,28 @@ +// The live task timer sits at the end of the last tool row while a reply runs. +// The trace sets it once, naming that row's call, so the per-tool blocks need +// no extra prop. + +import { getContext, setContext } from 'svelte'; + +const KEY = Symbol('tool-call-elapsed'); + +/** The call that shows the timer and the task start (ms since epoch), or null for no timer. */ +type ElapsedTarget = { startedAt: number; toolCallId: string } | null; + +export function setToolCallElapsedContext(getTarget: () => ElapsedTarget): void { + setContext(KEY, getTarget); +} + +/** + * Call during component init. Returns a reader of the task start for a call: + * its start when that call shows the timer, null otherwise. + */ +export function useToolCallElapsed(): (toolCallId: string | undefined) => number | null { + const getTarget = getContext<(() => ElapsedTarget) | undefined>(KEY); + + return (toolCallId) => { + const target = getTarget?.(); + + return target && target.toolCallId === toolCallId ? target.startedAt : null; + }; +} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte index 1101287c767a..4c4df7ba9763 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUser.svelte @@ -6,6 +6,7 @@ ChatMessageStatistics, ChatMessageUserBubble } from '#lib/components/app/chat/index.ts'; + import { SETTINGS_KEYS } from '#lib/constants/index.ts'; import { getChatMessageEditContext } from '#lib/contexts/index.ts'; import { ChatMessageStatisticsMode, MessageRole } from '#lib/enums/index.ts'; import { useProcessingState } from '#lib/hooks/use-processing-state.svelte.ts'; @@ -50,6 +51,12 @@ }; }); + // the latest exchange keeps its stats and actions in view; earlier messages + // show them on hover, and the setting can keep their stats in view as well + let hidesStatsUntilHover = $derived( + !isLastUserMessage && !currentConfig[SETTINGS_KEYS.ALWAYS_SHOW_MESSAGE_STATS] + ); + let showStoredReadingStats = $derived( Boolean(currentConfig.showMessageStats) && storedReadingStats !== null ); @@ -67,7 +74,7 @@
{#if editCtx.isEditing} @@ -83,7 +90,12 @@ {#if showStoredReadingStats} -
+
@@ -96,8 +108,10 @@
{:else if showLiveReadingStats} {@const liveStats = processingState.getLiveProcessingStats()} - {#if liveStats} -
+ +
+ {#if liveStats}
@@ -108,12 +122,12 @@ promptTokens={liveStats.tokensProcessed} />
-
- {/if} + {/if} +
{/if} {#if message.timestamp} -
+
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte index c4f823886354..4419454cae75 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageUser/ChatMessageUserBubble.svelte @@ -56,6 +56,7 @@
{#if editCtx.isEditing} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte index 452effa1e150..796f2a4d2a53 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCard.svelte @@ -5,10 +5,12 @@ interface Props { icon: Component<{ class?: string }>; message: Snippet; + /** What the decision is about, shown in full between the question and the actions. */ + detail?: Snippet; actions: Snippet; } - let { actions, icon: IconComponent, message }: Props = $props(); + let { actions, detail, icon: IconComponent, message }: Props = $props();
@@ -20,6 +22,12 @@
+ {#if detail} +
+ {@render detail()} +
+ {/if} +
{@render actions()}
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte index 42561a63b564..9e50951e353d 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte @@ -12,10 +12,15 @@ interface Props { toolName: string; serverLabel: string; + /** + * The shell command the call would run, shown in full: the trace row may + * show the model's own description of it, which is not what gets executed. + */ + command?: string; onDecision: (decision: ToolPermissionDecision) => void; } - let { onDecision, serverLabel, toolName }: Props = $props(); + let { command, onDecision, serverLabel, toolName }: Props = $props(); @@ -24,6 +29,13 @@  from {serverLabel}{/if}? {/snippet} + {#snippet detail()} + {#if command} +
{command}
+ {/if} + {/snippet} + {#snippet actions()} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte new file mode 100644 index 000000000000..f0e7bffde8dd --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte @@ -0,0 +1,410 @@ + + +{#snippet renderSection(section: AgenticSection, index: number, inOpenGroup = false)} + {#if section.type === AgenticSectionType.TEXT} +
+ +
+ {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING} + toggleExpanded(index, section)} + open={isExpanded(index, section)} + {section} + /> + {:else if section.type === AgenticSectionType.TOOL_CALL || section.type === AgenticSectionType.TOOL_CALL_PENDING || section.type === AgenticSectionType.TOOL_CALL_STREAMING} + toggleExpanded(index, section, inOpenGroup)} + open={isExpanded(index, section, inOpenGroup)} + {section} + /> + {/if} +{/snippet} + +{#snippet renderItem(item: TraceItem)} + {#if Array.isArray(item)} + {@const groupOpen = isGroupExpanded(item)} + toggleGroupExpanded(item)} + open={groupOpen} + sections={item.map((i) => sections[i])} + status={statusInGroup && item === lastItem ? statusText || REPLY_STATUS_FALLBACK : null} + > + {#each item as index (index)} + {@render renderSection(sections[index], index, groupOpen)} + {/each} + + {:else} + {@render renderSection(sections[item], item)} + {/if} +{/snippet} + +{#snippet renderItems(items: TraceItem[])} + {#each items as item (Array.isArray(item) ? `g${item[0]}` : item)} + {@render renderItem(item)} + {/each} +{/snippet} + +
+ {#each turns as items, turnIndex (turnIndex)} + {#if showTurnStats} + {@const turnStats = message?.timings?.agentic?.perTurn?.[turnIndex]} + +
+ {@render renderItems(items)} + + {#if turnStats} +
+ 0 + ? buildTurnAgenticTimings(turnStats) + : undefined} + hideSummary + initialView={ChatMessageStatsView.GENERATION} + predictedMs={turnStats.llm.predicted_ms} + predictedTokens={turnStats.llm.predicted_n} + promptMs={turnStats.llm.prompt_ms} + promptTokens={turnStats.llm.prompt_n} + /> +
+ {/if} +
+ {:else} + {@render renderItems(items)} + {/if} + {/each} + + {#if visiblePermission} + + {/if} + + {#if showContinue} + + {/if} + + {#if showStatus && !statusInGroup} + + {/if} +
+ + diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte deleted file mode 100644 index fa97fcde3411..000000000000 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte +++ /dev/null @@ -1,273 +0,0 @@ - - -{#snippet renderSection(section: AgenticSection, index: number)} - {#if section.type === AgenticSectionType.TEXT} -
- -
- {:else if section.type === AgenticSectionType.REASONING || section.type === AgenticSectionType.REASONING_PENDING} - toggleExpanded(index, section)} - open={isExpanded(index, section)} - {section} - /> - {:else if section.type === AgenticSectionType.TOOL_CALL || section.type === AgenticSectionType.TOOL_CALL_PENDING || section.type === AgenticSectionType.TOOL_CALL_STREAMING} - toggleExpanded(index, section)} - open={isExpanded(index, section)} - {section} - /> - {/if} -{/snippet} - -
- {#if turnGroups.length > 1} - {#each turnGroups as turn, turnIndex (turnIndex)} - {@const turnStats = message?.timings?.agentic?.perTurn?.[turnIndex]} - -
- {#each turn.sections as section, sIdx (turn.flatIndices[sIdx])} - {@render renderSection(section, turn.flatIndices[sIdx])} - {/each} - - {#if turnStats && showAgenticTurnStats} -
- 0 - ? buildTurnAgenticTimings(turnStats) - : undefined} - hideSummary - initialView={ChatMessageStatsView.GENERATION} - predictedMs={turnStats.llm.predicted_ms} - predictedTokens={turnStats.llm.predicted_n} - promptMs={turnStats.llm.prompt_ms} - promptTokens={turnStats.llm.prompt_n} - /> -
- {/if} -
- {/each} - {:else} - {#each sections as section, index (index)} - {@render renderSection(section, index)} - {/each} - {/if} - - {#if visiblePermission} - - {/if} - - {#if showContinue} - - {/if} -
- - diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte index f084d6cd6e97..b417f425602a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageReasoningBlock.svelte @@ -1,5 +1,4 @@ {#if perfState.message} - { }); it('streams the partial command into the title with a cursor', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git sta'), @@ -89,16 +94,15 @@ describe('exec_shell_command streaming title', () => { await tick(); - const title = triggerText(container); - - expect(title).toContain('git sta'); - expect(title).toContain('$'); - expect(title).toContain(CWD); + expect(triggerText(container)).toContain('git sta'); + expect(promptText(container)).toContain('git sta'); + expect(promptText(container)).toContain('$'); + expect(promptText(container)).toContain(CWD); expect(hasCursor(container)).toBe(true); }); it('drops the cursor once the args JSON is complete', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git sta'), @@ -122,7 +126,7 @@ describe('exec_shell_command streaming title', () => { }); it('switches the prompt from the conversation cwd to the persisted one', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git status"}'), @@ -131,7 +135,7 @@ describe('exec_shell_command streaming title', () => { await tick(); - expect(triggerText(screen.container)).toContain(CWD); + expect(promptText(screen.container)).toContain(CWD); // Result message lands: its x-tool-cwd takes over the prompt. screen.rerender({ @@ -142,12 +146,12 @@ describe('exec_shell_command streaming title', () => { }); await tick(); - expect(triggerText(screen.container)).toContain('/other/dir'); - expect(triggerText(screen.container)).not.toContain(CWD); + expect(promptText(screen.container)).toContain('/other/dir'); + expect(promptText(screen.container)).not.toContain(CWD); }); it('shows the executing label only after the command finishes streaming', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: messageWithArgs('{"command":"git sta'), @@ -198,7 +202,7 @@ describe('exec_shell_command streaming title', () => { // writes growing toolCalls strings into the same store row per delta. conversationsStore.activeMessages = [messageWithArgs('')]; - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: conversationsStore.activeMessages[0]!, @@ -232,7 +236,7 @@ describe('exec_shell_command interrupted call', () => { }); it('marks a call without a result as interrupted once streaming stops', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: false, message: messageWithArgs('{"command":"git status"}'), @@ -249,7 +253,7 @@ describe('exec_shell_command interrupted call', () => { it('marks a command stopped before any output as interrupted', async () => { // exec_shell_command creates its result message before running, so a // stop mid-run leaves an empty result rather than none. - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: false, message: messageWithArgs('{"command":"sleep 40"}'), @@ -263,7 +267,7 @@ describe('exec_shell_command interrupted call', () => { }); it('does not keep spinning in an earlier message while a newer reply streams', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: false, isStreaming: true, message: messageWithArgs('{"command":"git status"}'), diff --git a/ui/apps/chat/tests/client/media-gallery.svelte.test.ts b/ui/apps/chat/tests/client/media-gallery.svelte.test.ts new file mode 100644 index 000000000000..3a6279c259b6 --- /dev/null +++ b/ui/apps/chat/tests/client/media-gallery.svelte.test.ts @@ -0,0 +1,75 @@ +// Guards the conversation slideshow: a thumbnail opens every image, audio clip +// and video in the open thread, in thread order, at the item that was clicked, +// whether it came from a user attachment or a tool result. + +import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts'; +import { conversationsStore, mediaGalleryStore } from '#lib/stores/index.ts'; +import type { DatabaseMessage, DatabaseMessageExtra } from '#lib/types/index.ts'; +import { afterEach, describe, expect, it } from 'vitest'; + +function image(name: string): DatabaseMessageExtra { + return { base64Url: `data:image/png;base64,${name}`, name, type: AttachmentType.IMAGE }; +} + +function message(id: string, role: MessageRole, extra: DatabaseMessageExtra[]): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv-1', + extra, + id, + parent: null, + role, + timestamp: 0, + toolCalls: '', + type: MessageType.TEXT + }; +} + +afterEach(() => { + conversationsStore.activeMessages = []; + mediaGalleryStore.open = false; +}); + +describe('mediaGalleryStore', () => { + it('opens the media of the whole thread at the clicked item', () => { + const pasted = image('pasted'); + const shot = image('shot'); + const text: DatabaseMessageExtra = { + content: 'x', + name: 'notes.txt', + type: AttachmentType.TEXT + }; + + conversationsStore.activeMessages = [ + message('u1', MessageRole.USER, [pasted, text]), + message('t1', MessageRole.TOOL, [shot]) + ]; + + mediaGalleryStore.show(shot); + + expect(mediaGalleryStore.open).toBe(true); + expect(mediaGalleryStore.items).toEqual([pasted, shot]); + expect(mediaGalleryStore.index).toBe(1); + }); + + it('finds an item passed as a copy of the stored one', () => { + conversationsStore.activeMessages = [message('t1', MessageRole.TOOL, [image('a'), image('b')])]; + + mediaGalleryStore.show({ ...image('b') }); + + expect(mediaGalleryStore.index).toBe(1); + expect(mediaGalleryStore.items).toHaveLength(2); + }); + + it('opens an item outside the thread on its own', () => { + conversationsStore.activeMessages = [message('t1', MessageRole.TOOL, [image('a')])]; + + const stray = image('elsewhere'); + + mediaGalleryStore.show(stray); + + expect(mediaGalleryStore.items).toEqual([stray]); + expect(mediaGalleryStore.index).toBe(0); + }); +}); diff --git a/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts new file mode 100644 index 000000000000..b804a991b7bb --- /dev/null +++ b/ui/apps/chat/tests/client/permission-request-command.svelte.test.ts @@ -0,0 +1,67 @@ +// Guards what the reader approves: the trace row of a shell call may show the +// model's own description of it, so the permission card must show the command +// that would actually run, and the row must keep the command beside the +// description. + +import ChatMessageActionCardPermissionRequest from '#lib/components/app/chat/ChatMessages/ChatMessageActions/ChatMessageActionCard/ChatMessageActionCardPermissionRequest.svelte'; +import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte'; +import { BuiltInTool, MessageRole, MessageType } from '#lib/enums/index.ts'; +import type { DatabaseMessage } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const COMMAND = 'rm -rf ./build'; +const DESCRIPTION = 'List files'; + +function shellCall(): DatabaseMessage { + return { + children: [], + content: '', + convId: 'conv-1', + id: 'assistant-1', + parent: null, + role: MessageRole.ASSISTANT, + timestamp: 0, + toolCalls: JSON.stringify([ + { + function: { + arguments: JSON.stringify({ command: COMMAND, description: DESCRIPTION }), + name: BuiltInTool.SERVER_EXEC_SHELL_COMMAND + }, + id: 'c1' + } + ]), + type: MessageType.TEXT + }; +} + +describe('approving a shell command', () => { + it('shows the command in the permission card', async () => { + const { container } = render(ChatMessageActionCardPermissionRequest, { + command: COMMAND, + onDecision: () => {}, + serverLabel: 'Server Tools', + toolName: BuiltInTool.SERVER_EXEC_SHELL_COMMAND + }); + + await tick(); + + expect(container.querySelector('pre')?.textContent).toBe(COMMAND); + }); + + it('keeps the command beside a model description in the collapsed row', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: true, + message: shellCall() + }); + + await tick(); + + const title = container.querySelector('[data-slot="collapsible-trigger"]')?.textContent ?? ''; + + expect(title).toContain(DESCRIPTION); + expect(title).toContain(COMMAND); + }); +}); diff --git a/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts b/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts index cc8589e444b2..d229bba0f023 100644 --- a/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts +++ b/ui/apps/chat/tests/client/stick-to-bottom.svelte.test.ts @@ -1,7 +1,8 @@ // Guards the follow rules of StickToBottom: right after a press, growth of the // content stays put (the reader expanded something), while growth of an element // passed to followSizeOf - the chat form expanding on the reader's click - is -// still followed, so the latest message stays in view above it. +// still followed, so the latest message stays in view above it. A send glides to +// the bottom: eased, never jumping, and handed back the moment the reader scrolls. import { createStickToBottom } from '#lib/hooks/use-stick-to-bottom.svelte.ts'; import { afterEach, describe, expect, it } from 'vitest'; @@ -47,6 +48,26 @@ async function resizeObserved() { await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); } +function frame() { + return new Promise((resolve) => requestAnimationFrame(resolve)); +} + +/** + * Waits until the container rests at its bottom. A glide counts animated + * time, not wall time, so a runner that drops frames takes longer to get + * there: the deadline is only a guard against a glide that never arrives, + * set far beyond what one can take. + */ +const SETTLE_DEADLINE_MS = 20_000; + +async function settled(container: HTMLElement) { + const deadline = performance.now() + SETTLE_DEADLINE_MS; + + while (distanceFromBottom(container) > 1 && performance.now() < deadline) { + await frame(); + } +} + function distanceFromBottom(el: HTMLElement) { return el.scrollHeight - el.clientHeight - el.scrollTop; } @@ -86,4 +107,83 @@ describe('StickToBottom', () => { expect(container.scrollTop).toBe(0); }); + + it('glides to the new bottom after a send instead of jumping there', async () => { + const { container, content, stick } = setup(); + + stick.glideToBottom(); + content.style.height = '1400px'; + + const tops: number[] = []; + + // the first frames after the growth are on their way, not there yet + await frame(); + tops.push(container.scrollTop); + await frame(); + tops.push(container.scrollTop); + + expect(distanceFromBottom(container)).toBeGreaterThan(200); + + await settled(container); + + for (let i = 0; i < 5; i++) { + tops.push(container.scrollTop); + await frame(); + } + + expect(distanceFromBottom(container)).toBeLessThanOrEqual(1); + // only ever down: no overshoot, no step back + expect(tops).toEqual([...tops].sort((a, b) => a - b)); + }); + + it('glides to layout that settles shortly after a send', async () => { + const { container, content, stick } = setup(); + + stick.glideToBottom(); + content.style.height = '1400px'; + await settled(container); + + content.style.height = '1700px'; + await resizeObserved(); + + expect(distanceFromBottom(container)).toBeGreaterThan(100); + + await settled(container); + + expect(distanceFromBottom(container)).toBeLessThanOrEqual(1); + }); + + it('hands the page back the moment the reader scrolls', async () => { + const { container, content, stick } = setup(); + + stick.glideToBottom(); + content.style.height = '1400px'; + await frame(); + await frame(); + window.dispatchEvent(new WheelEvent('wheel')); + + const top = container.scrollTop; + + await resizeObserved(); + await frame(); + + expect(container.scrollTop).toBe(top); + expect(distanceFromBottom(container)).toBeGreaterThan(200); + }); + + it('keeps gliding while the reader types the next message', async () => { + const { container, content, stick } = setup(); + const field = document.createElement('textarea'); + + document.body.append(field); + cleanup.push(() => field.remove()); + + stick.glideToBottom(); + content.style.height = '1400px'; + await frame(); + field.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: ' ' })); + await settled(container); + + expect(distanceFromBottom(container)).toBeLessThanOrEqual(1); + }); }); diff --git a/ui/apps/chat/tests/client/task-timer.svelte.test.ts b/ui/apps/chat/tests/client/task-timer.svelte.test.ts new file mode 100644 index 000000000000..5c248cc2f3d6 --- /dev/null +++ b/ui/apps/chat/tests/client/task-timer.svelte.test.ts @@ -0,0 +1,84 @@ +// Guards the live task timer: while a reply runs, the last tool row shows the +// time since the task started. A single call reads it from context by its id; +// a group takes it as a prop; a finished reply shows none. + +import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte'; +import { MessageRole, MessageType } from '#lib/enums/index.ts'; +import { agenticStore } from '#lib/stores/index.ts'; +import type { DatabaseMessage } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const CONV_ID = 'conv-timer'; +const TIMER = '[title="Time since the task started"]'; + +type SessionPatch = { startedAt: number | null }; +type WithSession = { updateSession(conversationId: string, patch: SessionPatch): void }; + +function reply(calls: number): DatabaseMessage { + return { + children: [], + content: '', + convId: CONV_ID, + id: 'assistant-1', + parent: null, + role: MessageRole.ASSISTANT, + timestamp: 0, + toolCalls: JSON.stringify( + Array.from({ length: calls }, (_, i) => ({ + function: { arguments: `{"path":"file-${i}.ts"}`, name: 'read_file' }, + id: `call-${i}` + })) + ), + type: MessageType.TEXT + }; +} + +function setStartedAt(startedAt: number | null) { + // the loop sets this when a flow starts; there is no public setter + (agenticStore as unknown as WithSession).updateSession(CONV_ID, { startedAt }); +} + +describe('task timer', () => { + beforeEach(() => setStartedAt(Date.now() - 5000)); + afterEach(() => setStartedAt(null)); + + it('shows on a single running call', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: true, + message: reply(1) + }); + + await tick(); + + expect(container.querySelectorAll(TIMER)).toHaveLength(1); + expect(container.querySelector(TIMER)?.textContent?.trim()).toMatch(/^\d+s$/); + }); + + it('shows once on a group, not on the calls inside it', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: true, + message: reply(2) + }); + + await tick(); + + expect(container.querySelectorAll(TIMER)).toHaveLength(1); + expect(container.querySelector('.tool-call-group')?.querySelector(TIMER)).not.toBeNull(); + }); + + it('shows nothing once the reply is not streaming', async () => { + const { container } = render(ChatMessageAgentTrace, { + isLastAssistantMessage: true, + isStreaming: false, + message: reply(1) + }); + + await tick(); + + expect(container.querySelectorAll(TIMER)).toHaveLength(0); + }); +}); diff --git a/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts b/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts index 3d8b350df0f3..25b3a164a53c 100644 --- a/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts +++ b/ui/apps/chat/tests/client/tool-call-in-progress.svelte.test.ts @@ -7,7 +7,7 @@ // finished calls open and wins on its own. A manual toggle always overrides the // default, in both directions. -import ChatMessageAgenticContent from '#lib/components/app/chat/ChatMessages/ChatMessageAgenticContent.svelte'; +import ChatMessageAgentTrace from '#lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte'; import { COLLAPSIBLE_TRANSITION_MS, SETTINGS_KEYS } from '#lib/constants/index.ts'; import { MessageRole, MessageType } from '#lib/enums/index.ts'; import { settingsStore } from '#lib/stores/index.ts'; @@ -94,7 +94,7 @@ describe('Show tool call in progress', () => { it('expands a call that is still executing when the setting is on', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -107,7 +107,7 @@ describe('Show tool call in progress', () => { }); it('keeps the call collapsed while executing when the setting is off', async () => { - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -124,7 +124,7 @@ describe('Show tool call in progress', () => { it('folds the call back when its result arrives', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -153,7 +153,7 @@ describe('Show tool call in progress', () => { it('keeps the manual choice once the result arrives', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -180,7 +180,7 @@ describe('Show tool call in progress', () => { it('still expands a finished call when "always show" is on', async () => { setSettings({ alwaysShow: true, inProgress: false }); - const { container } = render(ChatMessageAgenticContent, { + const { container } = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -195,7 +195,7 @@ describe('Show tool call in progress', () => { it('lets a manual collapse win over the in-progress default', async () => { setSettings({ alwaysShow: false, inProgress: true }); - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), @@ -213,7 +213,7 @@ describe('Show tool call in progress', () => { }); it('lets a manual expand win over the collapsed default', async () => { - const screen = render(ChatMessageAgenticContent, { + const screen = render(ChatMessageAgentTrace, { isLastAssistantMessage: true, isStreaming: true, message: assistantMessage(), diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte index 0d0accc04592..ca71b4862393 100644 --- a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallBlock.stories.svelte @@ -20,6 +20,7 @@ runJavascriptSection, searchResultsSection, seedChatStory, + toolSearchSection, writeFileSection } from './fixtures'; import { defineMeta } from '@storybook/addon-svelte-csf'; @@ -125,6 +126,10 @@ + + + + diff --git a/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte new file mode 100644 index 000000000000..848eac7d64d3 --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/messages/ChatMessageToolCallGroup.stories.svelte @@ -0,0 +1,70 @@ + + + seedChatStory()} name="States"> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte b/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte new file mode 100644 index 000000000000..dbbaa116316f --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/messages/ToolCallGroupStoryHost.svelte @@ -0,0 +1,46 @@ + + + (open = !open)} + {open} + {sections} +> + {#each sections as section, i (i)} + {@const executing = section.toolCallId === executingToolCallId} + (openCalls[i] = !(openCalls[i] ?? executing))} + open={openCalls[i] ?? executing} + {section} + /> + {/each} + diff --git a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts index 41aae1b3d582..a686c958f4fb 100644 --- a/ui/apps/chat/tests/stories/chat/messages/fixtures.ts +++ b/ui/apps/chat/tests/stories/chat/messages/fixtures.ts @@ -592,6 +592,73 @@ export const searchResultsSection = toolSection( ].join('\n') ); +export const toolSearchSection = toolSection( + 'tool_search', + { max_results: 1, query: 'select:Monitor' }, + 'Loaded 1 tool: Monitor' +); + +/* Tool call groups: runs of consecutive calls shown as one row */ + +function withId(section: AgenticSection, toolCallId: string): AgenticSection { + return { ...section, toolCallId }; +} + +const IMAGE_SECTION_COUNT = 4; + +export const toolGroupSections: AgenticSection[] = [ + withId(getInfoSection, 'group-info'), + withId(readFileSection, 'group-read'), + withId(grepSearchSection, 'group-grep'), + withId(editFileSection, 'group-edit'), + withId(execShellSection, 'group-exec'), + withId(writeFileSection, 'group-write') +]; + +export const toolGroupImageSections: AgenticSection[] = [ + withId(execShellSection, 'image-exec'), + ...Array.from({ length: IMAGE_SECTION_COUNT }, (_, i) => ({ + ...readMediaSection, + toolArgs: JSON.stringify({ path: `/home/user/charts/chart-${i + 1}.svg` }), + toolCallId: `image-media-${i}`, + toolResultExtras: [ + { + base64Url: i % 2 === 0 ? CHART_IMAGE_URL : SVG_IMAGE_URL, + name: 'mcp-attachment-usage.svg', + type: AttachmentType.IMAGE as const + } + ] + })) +]; + +export const toolGroupRunningSections: AgenticSection[] = [ + withId(readFileSection, 'running-read'), + withId(grepSearchSection, 'running-grep'), + toolSection( + BuiltInTool.SERVER_READ_FILE, + { path: 'package.json' }, + undefined, + AgenticSectionType.TOOL_CALL_PENDING + ) +]; + +export const TOOL_GROUP_EXECUTING_ID = 'running-exec'; + +export const toolGroupShellRunningSections: AgenticSection[] = [ + withId(readFileSection, 'shell-read'), + { + ...withId(execShellPendingSection, TOOL_GROUP_EXECUTING_ID), + toolResult: '> app@0.1.0 build\n> vite build\n\nvite v7.0.0 building for production...\n', + type: AgenticSectionType.TOOL_CALL + } +]; + +export const toolGroupMcpSections: AgenticSection[] = [ + withId(toolSearchSection, 'mcp-search'), + withId(defaultToolSection, 'mcp-weather'), + withId(defaultToolMarkdownSection, 'mcp-issue') +]; + /* Reasoning sections */ export const reasoningSection: AgenticSection = { diff --git a/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts b/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts index 792239f76d29..5c11b43f0b64 100644 --- a/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts +++ b/ui/apps/chat/tests/unit/settings-tool-call-in-progress.test.ts @@ -27,9 +27,9 @@ describe('showToolCallInProgress setting', () => { expect(field?.label).toBe('Show tool call in progress'); }); - it('ships enabled, like "Show thought in progress"', () => { - expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS]).toBe(true); - expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS]).toBe(true); + it('ships disabled, like "Show thought in progress", so the trace stays collapsed', () => { + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_TOOL_CALL_IN_PROGRESS]).toBe(false); + expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.SHOW_THOUGHT_IN_PROGRESS]).toBe(false); }); it('is listed next to its "always show" counterpart', () => { diff --git a/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts new file mode 100644 index 000000000000..1433d32250cd --- /dev/null +++ b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts @@ -0,0 +1,344 @@ +import { + describeToolActivity, + describeToolCall, + formatToolCallLine, + groupToolCallRuns, + humanizeArgKey, + simpleToolArgFields, + summarizeToolCalls +} from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts'; +import { AgenticSectionType, BuiltInTool } from '#lib/enums/index.ts'; +import type { AgenticSection } from '#lib/types/index.ts'; +import { describe, expect, it } from 'vitest'; + +function call( + toolName: string, + args: Record | string = {}, + type = AgenticSectionType.TOOL_CALL, + toolCallId?: string +): AgenticSection { + return { + content: '', + toolArgs: typeof args === 'string' ? args : JSON.stringify(args), + toolCallId, + toolName, + toolResult: type === AgenticSectionType.TOOL_CALL ? 'ok' : undefined, + type + }; +} + +function line(toolName: string, args: Record | string = {}, running = false) { + return formatToolCallLine( + describeToolCall(toolName, typeof args === 'string' ? args : JSON.stringify(args), running) + ); +} + +describe('describeToolCall', () => { + it('phrases built-in tools in the past tense', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'git status' })).toBe( + 'Ran git status' + ); + expect(line(BuiltInTool.SERVER_READ_FILE, { path: '/tmp/x/sheet_new.jpg' })).toBe( + 'Read sheet_new.jpg' + ); + expect(line(BuiltInTool.SERVER_EDIT_FILE, { edits: [], path: 'a/harness-roadmap.html' })).toBe( + 'Edited harness-roadmap.html' + ); + expect(line(BuiltInTool.SERVER_WRITE_FILE, { content: 'x', file_path: 'b/notes.md' })).toBe( + 'Wrote notes.md' + ); + expect(line(BuiltInTool.SERVER_GREP_SEARCH, { path: '.', pattern: 'issue' })).toBe( + "Searched for 'issue'" + ); + expect(line(BuiltInTool.SERVER_FILE_GLOB_SEARCH, { include: '*.ts', path: '.' })).toBe( + "Listed files matching '*.ts'" + ); + expect(line(BuiltInTool.SERVER_FILE_GLOB_SEARCH, { include: '**', path: '.' })).toBe( + 'Listed files' + ); + expect(line(BuiltInTool.BROWSER_SEARCH_CHATS, { by_matches: ['llama', 'gguf'] })).toBe( + "Searched chats for 'llama, gguf'" + ); + expect(line(BuiltInTool.SERVER_GET_INFO)).toBe('Checked runtime info'); + expect(line(BuiltInTool.BROWSER_RUN_JAVASCRIPT, { code: '1+1' })).toBe('Ran JavaScript'); + }); + + it('uses the present tense while running', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'ls' }, true)).toBe('Running ls'); + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, '{"comm', true)).toBe('Running a command'); + expect(line(BuiltInTool.SERVER_READ_FILE, { path: 'package.json' }, true)).toBe( + 'Reading package.json' + ); + expect(line(BuiltInTool.BROWSER_SEARCH_CHATS, {}, true)).toBe('Searching chats'); + }); + + it('falls back to the object when the target has not streamed yet', () => { + expect(line(BuiltInTool.SERVER_READ_FILE, '{"pa', true)).toBe('Reading a file'); + expect(line(BuiltInTool.SERVER_GREP_SEARCH, '')).toBe('Searched files'); + }); + + it('reads a path from partial args', () => { + expect( + line(BuiltInTool.SERVER_WRITE_FILE, '{"path": "src/app.ts", "content": "abc', true) + ).toBe('Writing app.ts'); + }); + + it('phrases tool_search select queries as loading tools', () => { + expect(line('tool_search', { query: 'select:Monitor' })).toBe('Loaded tools Monitor'); + expect(line('tool_search', { query: 'select:a, b' }, true)).toBe('Loading tools a, b'); + expect(line('tool_search', { query: 'slack messages' })).toBe( + "Searched tools for 'slack messages'" + ); + }); + + it('phrases web search tools', () => { + expect(line('web_search_exa', { query: 'llama.cpp' })).toBe("Searched the web for 'llama.cpp'"); + }); + + it('gives MCP and unknown tools a generic line with their main argument', () => { + expect(line('get_weather', { city: 'Warsaw' })).toBe('Used get_weather Warsaw'); + expect(line('fetch_page', { timeout: 5, url: 'https://example.com' })).toBe( + 'Used fetch_page https://example.com' + ); + expect(line('list_things', {})).toBe('Used list_things'); + expect(line('summarize_issue', { issue: 31273 })).toBe('Used summarize_issue 31273'); + expect(line('list_things', {}, true)).toBe('Using list_things'); + }); + + it('shortens long targets to one line', () => { + const text = describeToolCall('my_tool', JSON.stringify({ query: 'word '.repeat(40) })).target; + + expect(text?.length).toBe(60); + expect(text?.endsWith('...')).toBe(true); + expect(text).not.toContain('\n'); + }); +}); + +describe('the shown argument', () => { + const args = { command: 'git status', description: 'Check which files changed.' }; + + it('shows the description as the model wrote it, in both tenses', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, args)).toBe('Check which files changed'); + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, args, true)).toBe( + 'Check which files changed' + ); + expect( + describeToolCall(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, JSON.stringify(args)).described + ).toBe(true); + }); + + it('does not rewrite a description that starts with something other than a verb', () => { + const nouns = { command: 'ls', description: 'All files in src' }; + + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, nouns)).toBe('All files in src'); + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, nouns, true)).toBe('All files in src'); + }); + + it('keeps the command in the line while a later arg is still streaming', () => { + expect(line(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, '{"command":"date","timeout":', true)).toBe( + 'Running date' + ); + }); + + it('works for any tool that has the argument, MCP ones included', () => { + expect(line('get_weather', { city: 'Warsaw', description: 'Check the weather' })).toBe( + 'Check the weather' + ); + }); + + it('falls back to the sentence when the call does not have it', () => { + expect(line('get_weather', { city: 'Warsaw' })).toBe('Used get_weather Warsaw'); + }); + + it('reads the argument the settings pick, or none', () => { + const weather = JSON.stringify({ + city: 'Warsaw', + description: 'Check the weather', + units: 'metric' + }); + + expect(formatToolCallLine(describeToolCall('get_weather', weather, false, 'units'))).toBe( + 'metric' + ); + expect(formatToolCallLine(describeToolCall('get_weather', weather, false, null))).toBe( + 'Used get_weather Warsaw' + ); + }); + + it('does not repeat the target the row already shows', () => { + expect( + formatToolCallLine( + describeToolCall( + BuiltInTool.SERVER_EXEC_SHELL_COMMAND, + JSON.stringify(args), + false, + 'command' + ) + ) + ).toBe('Ran git status'); + }); + + it('ignores an argument name that is not a plain key', () => { + expect( + formatToolCallLine( + describeToolCall('get_weather', JSON.stringify({ city: 'Warsaw' }), false, '.*') + ) + ).toBe('Used get_weather Warsaw'); + }); +}); + +describe('summarizeToolCalls', () => { + it('counts calls per kind in first-seen order', () => { + const sections = [ + call(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'a' }), + call(BuiltInTool.SERVER_READ_FILE, { path: 'a' }), + call(BuiltInTool.SERVER_EXEC_SHELL_COMMAND, { command: 'b' }), + call(BuiltInTool.SERVER_WRITE_FILE, { path: 'c' }), + call(BuiltInTool.SERVER_WRITE_FILE, { path: 'd' }), + call(BuiltInTool.SERVER_READ_FILE, { path: 'b' }) + ]; + + expect(summarizeToolCalls(sections)).toBe('Ran 2 commands, read 2 files, wrote 2 files'); + }); + + it('uses singular forms and merges search tools', () => { + const sections = [ + call(BuiltInTool.SERVER_EDIT_FILE, { path: 'a' }), + call(BuiltInTool.SERVER_GREP_SEARCH, { pattern: 'x' }), + call(BuiltInTool.BROWSER_SEARCH_CHATS, { by_matches: ['y'] }) + ]; + + expect(summarizeToolCalls(sections)).toBe('Edited 1 file, searched 2 times'); + expect(summarizeToolCalls([call(BuiltInTool.SERVER_GREP_SEARCH)])).toBe('Searched once'); + }); + + it('puts other tools last', () => { + const sections = [call(BuiltInTool.SERVER_GET_INFO), call(BuiltInTool.SERVER_READ_FILE)]; + + expect(summarizeToolCalls(sections)).toBe('Read 1 file, used 1 tool'); + }); + + it('counts each tool a select query loads', () => { + const sections = [ + call('tool_search', { query: 'select:Monitor,Notebook' }), + call('get_weather', { city: 'x' }), + call('get_time') + ]; + + expect(summarizeToolCalls(sections)).toBe('Loaded 2 tools, used 2 tools'); + }); +}); + +describe('describeToolActivity', () => { + it('describes the last running call', () => { + const sections = [ + call(BuiltInTool.SERVER_READ_FILE, { path: 'a.ts' }), + call( + BuiltInTool.SERVER_READ_FILE, + { path: 'package.json' }, + AgenticSectionType.TOOL_CALL_PENDING + ) + ]; + + expect(describeToolActivity(sections, true)).toBe('Reading package.json'); + }); + + it('returns null when nothing runs or the reply stopped', () => { + const pending = [call(BuiltInTool.SERVER_READ_FILE, {}, AgenticSectionType.TOOL_CALL_PENDING)]; + + expect(describeToolActivity([call(BuiltInTool.SERVER_READ_FILE)], true)).toBeNull(); + expect(describeToolActivity(pending, false)).toBeNull(); + }); + + it('says the model is thinking while reasoning streams at the end of the run', () => { + const thinking: AgenticSection = { + content: '', + type: AgenticSectionType.REASONING_PENDING + }; + const sections = [call(BuiltInTool.SERVER_READ_FILE, { path: 'a.ts' }), thinking]; + + expect(describeToolActivity(sections, true)).toBe('Thinking'); + expect(describeToolActivity(sections, false)).toBeNull(); + }); + + it('treats the executing call as running even once its result exists', () => { + const sections = [ + call( + BuiltInTool.SERVER_EXEC_SHELL_COMMAND, + { command: 'ls' }, + AgenticSectionType.TOOL_CALL, + 'c1' + ) + ]; + + expect(describeToolActivity(sections, true, 'c1')).toBe('Running ls'); + }); +}); + +describe('simpleToolArgFields', () => { + it('lists short scalar args as labelled fields', () => { + expect( + simpleToolArgFields(JSON.stringify({ max_results: 1, query: 'select:Monitor' })) + ).toEqual([ + { label: 'Max results', value: '1' }, + { label: 'Query', value: 'select:Monitor' } + ]); + }); + + it('returns null for nested, multi-line, long or invalid args', () => { + expect(simpleToolArgFields(JSON.stringify({ a: { b: 1 } }))).toBeNull(); + expect(simpleToolArgFields(JSON.stringify({ a: 'x\ny' }))).toBeNull(); + expect(simpleToolArgFields(JSON.stringify({ a: 'x'.repeat(300) }))).toBeNull(); + expect(simpleToolArgFields('{"a":')).toBeNull(); + expect(simpleToolArgFields('{}')).toBeNull(); + expect(simpleToolArgFields(undefined)).toBeNull(); + }); +}); + +describe('humanizeArgKey', () => { + it('turns snake and camel case into words', () => { + expect(humanizeArgKey('max_results')).toBe('Max results'); + expect(humanizeArgKey('filePath')).toBe('File path'); + expect(humanizeArgKey('q')).toBe('Q'); + }); +}); + +describe('groupToolCallRuns', () => { + const text: AgenticSection = { content: 'hi', type: AgenticSectionType.TEXT }; + const tool = call(BuiltInTool.SERVER_READ_FILE); + + it('groups runs of consecutive calls and keeps single calls apart', () => { + const sections = [text, tool, tool, tool, text, tool, text]; + + expect(groupToolCallRuns(sections, [0, 1, 2, 3, 4, 5, 6], 2)).toEqual([0, [1, 2, 3], 4, 5, 6]); + }); + + const think: AgenticSection = { content: 'hm', type: AgenticSectionType.REASONING }; + + it('takes in all the reasoning around the calls, up to the answer', () => { + // think, call, think, call, think, text + const sections = [think, tool, think, tool, think, text]; + + expect(groupToolCallRuns(sections, [0, 1, 2, 3, 4, 5], 2)).toEqual([[0, 1, 2, 3, 4], 5]); + }); + + it('groups one call with reasoning beside it', () => { + expect(groupToolCallRuns([think, tool, think, text], [0, 1, 2, 3], 2)).toEqual([[0, 1, 2], 3]); + expect(groupToolCallRuns([text, tool, think], [0, 1, 2], 2)).toEqual([0, [1, 2]]); + }); + + it('keeps a lone call, and reasoning with no call in reach, apart', () => { + expect(groupToolCallRuns([text, tool, text], [0, 1, 2], 2)).toEqual([0, 1, 2]); + expect(groupToolCallRuns([think, text, think], [0, 1, 2], 2)).toEqual([0, 1, 2]); + }); + + it('does not count reasoning as a call in the summary', () => { + expect(summarizeToolCalls([think, tool, think, tool])).toBe('Read 2 files'); + }); + + it('works on a subset of indices and a trailing run', () => { + const sections = [text, text, tool, tool]; + + expect(groupToolCallRuns(sections, [1, 2, 3], 2)).toEqual([1, [2, 3]]); + }); +}); diff --git a/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts b/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts new file mode 100644 index 000000000000..7bc63725933c --- /dev/null +++ b/ui/apps/chat/tests/unit/tool-call-shown-arg.test.ts @@ -0,0 +1,38 @@ +import { SETTINGS_KEYS } from '#lib/constants/index.ts'; +import { parseToolCallShownArgOverrides, toolCallShownArg } from '#lib/utils/index.ts'; +import { describe, expect, it } from 'vitest'; + +function config(shownArg: string, overrides: Record | string = {}) { + return { + [SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG]: shownArg, + [SETTINGS_KEYS.TOOL_CALL_SHOWN_ARG_OVERRIDES]: + typeof overrides === 'string' ? overrides : JSON.stringify(overrides) + }; +} + +describe('toolCallShownArg', () => { + it('uses the global argument for a tool without its own', () => { + expect(toolCallShownArg(config('description'), 'get_weather')).toBe('description'); + }); + + it("prefers the tool's own argument", () => { + expect(toolCallShownArg(config('description', { get_weather: 'city' }), 'get_weather')).toBe( + 'city' + ); + expect(toolCallShownArg(config('description', { get_weather: 'city' }), 'other')).toBe( + 'description' + ); + }); + + it('returns null for none, globally or per tool', () => { + expect(toolCallShownArg(config(''), 'get_weather')).toBeNull(); + expect(toolCallShownArg(config('description', { get_weather: '' }), 'get_weather')).toBeNull(); + }); + + it('reads unreadable overrides as none', () => { + expect(parseToolCallShownArgOverrides('not json')).toEqual({}); + expect(parseToolCallShownArgOverrides('[1]')).toEqual({}); + expect(parseToolCallShownArgOverrides('{"a":"x","b":1}')).toEqual({ a: 'x' }); + expect(toolCallShownArg(config('description', 'not json'), 'get_weather')).toBe('description'); + }); +}); From 1d3aad2fd811a2a5efdd4eeb192eaefc1764519c Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 17:28:56 +0100 Subject: [PATCH 072/401] server: ask exec_shell_command for a short description of the command (#32894) The shell tool's schema gains a required `description` argument, listed first: a short plain-language line on what the command does. The tool ignores it, as before; clients can show it in place of the raw command while the call streams and in their logs. Calls without it still run. Assisted-by: Claude (Opus 5.5 Medium) --- tools/server/server-tools.cpp | 4 +++- tools/server/tests/unit/test_tools_builtin.py | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tools/server/server-tools.cpp b/tools/server/server-tools.cpp index 060361968c59..7f4650157ec1 100644 --- a/tools/server/server-tools.cpp +++ b/tools/server/server-tools.cpp @@ -1274,11 +1274,13 @@ struct server_tool_exec_shell_command : server_tool { {"parameters", { {"type", "object"}, {"properties", { + // first, so a client can show it while the command still streams; the tool ignores it + {"description", {{"type", "string"}, {"description", "Short plain-language description of what this command does, starting with a verb, e.g. 'List files in the project root'. 3 to 10 words. Shown to the user."}}}, {"command", {{"type", "string"}, {"description", "Shell command to execute"}}}, {"timeout", {{"type", "integer"}, {"description", string_format("Timeout in seconds (default 10, max %d)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_TIMEOUT)}}}, {"max_output_size", {{"type", "integer"}, {"description", string_format("Maximum output size in bytes (default %zu)", SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE)}}}, }}, - {"required", json::array({"command"})}, + {"required", json::array({"description", "command"})}, }}, }}, }; diff --git a/tools/server/tests/unit/test_tools_builtin.py b/tools/server/tests/unit/test_tools_builtin.py index c830b0642f63..486ba8481700 100755 --- a/tools/server/tests/unit/test_tools_builtin.py +++ b/tools/server/tests/unit/test_tools_builtin.py @@ -191,6 +191,23 @@ def test_tools_builtin_edit_file_rejects_non_unique_old_text(tmp_path): os.remove(log_path) +def test_tools_builtin_exec_shell_command_asks_for_a_description(): + global server + server.start() + + res = server.make_request("GET", "/tools") + assert res.status_code == 200, res.body + tool = next(t for t in res.body if t["tool"] == "exec_shell_command") + params = tool["definition"]["function"]["parameters"] + # first, so a client can show it while the command still streams + assert list(params["properties"])[0] == "description" + assert "description" in params["required"] + + # the tool runs without it, as before + res = call_tool("exec_shell_command", {"command": "echo hi"}) + assert "hi" in res["plain_text_response"] + + def test_tools_builtin_exec_shell_command_stream(): global server server.start() From 87f816e87f35f91c8a6f7e561b1f1a7899bee254 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Mon, 23 Nov 2026 18:46:12 +0200 Subject: [PATCH 073/401] metal : support BF16/F32 src1 for MUL_MAT and MUL_MAT_ID (#32677) * llama, metal : support BF16 src1 for MUL_MAT and MUL_MAT_ID Add GGML_PREC_BF16 handling for src1 on the Metal backend when the tensor API is available: MUL_MAT with an F32 src0 stages the A tile as bfloat, and MUL_MAT_ID stages src1 as bfloat instead of F16. The tensor path keeps src1 in F32 when it reads the operand directly. Add a temporary LLAMA_MOE_AMAX_SKIP env var that disables the graph-level amax rescaling for the MoE down projection and sets the BF16 src1 hint instead. Apply the hint inside build_lora_mm_id so it reaches the matmul before the per-expert scale and LoRA nodes wrap it. Add MUL_MAT_ID src1 BF16 test cases to test-backend-ops. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : support BF16 src1 without the tensor API Allow GGML_PREC_BF16 when the device has bfloat, not only when it has the Metal4 tensor API. Add legacy _prec_bf16 kernels for MUL_MAT and MUL_MAT_ID that stage src1 as bfloat in the threadgroup and run the simdgroup multiply with bfloat A and B. The F16 MUL_MAT_ID kernel uses half A on the tensor path and bfloat A on the legacy path. Cast the quantized dequantize outputs to the destination element type: the older Metal compiler on M2 rejects implicit float to bfloat. Tested on M2 Ultra (legacy): MUL_MAT_PREC_SRC1 24/24 and MUL_MAT_ID_PREC_SRC1_BF16 30/30. Flint Q4_K_M with LLAMA_MOE_AMAX_SKIP=1: pp512 -2.1%, tg128 +25.5% vs master. On M5 Max: pp512 +2.1%, tg128 +22.2%. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : derive matrix types with value_type helpers Add value_type_4x4/value_type_2x4/value_type_8x8 helpers and use them in the MUL_MAT and MUL_MAT_ID kernels so the templates take only the underlying types and derive the matrix types. Add TODOs for the remaining kernels. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : derive matrix types in the remaining kernels Use the value_type_* helpers in the flash-attention, top-k-mask, mul-mv and count-equal kernels to derive the matrix/vector types from the underlying scalar types, and simplify the FA_TYPES macros. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : enable BF16 in the tensor API metallib The tensor API requires macOS 26, where bfloat is always available, so define GGML_METAL_HAS_BF16 when compiling the tensor metallib. This makes the bfloat specializations of the value_type helpers visible to fa_tensor.metal and includes the prec_bf16 kernels in the prebuilt tensor metallib. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : support GGML_PREC_F32 for src1 in MUL_MAT and MUL_MAT_ID Split the tensor-API and legacy simdgroup mul_mm/mul_mm_id kernels into separate files and library kinds, following the fa_tensor.metal example. The legacy kernels, including the new _prec_f32 variants that stage src0 and src1 as float in shared memory, are compiled into the default mul_mm library; the tensor variants live in a separate mul_mm_tensor library kind and carry a _tensor host-name infix. Tensor devices run F32 src1 matmuls on the simdgroup path instead of the tensor API, which rounds float operands to a reduced precision. This removes the MUL_MM_SG kind and the #undef GGML_METAL_HAS_TENSOR compile. Add MUL_MAT_ID_PREC_SRC1_F32 tests. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * cont : indentation * llama : move the MoE amax skip into the precision policy Add llm_arch_mmid_down_bf16() for the architectures whose MoE down projection uses the graph-level amax rescaling. Extract the precision policy setup from load_tensors() into llama_model_base::load_prec_policy(), and move the LLAMA_MOE_AMAX_SKIP handling there: it sets prec_src1 = BF16 for ffn_down_exps before the per-tensor policy is loaded. build_moe_ffn() now skips the amax rescaling when the policy requests BF16. Apply the policy with the original weight so cached experts get it, drop the prec_src1 parameter from build_lora_mm_id(), and remove the prec_src1 serialization from the model saver. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * cont : minor --- ggml/src/ggml-metal/CMakeLists.txt | 11 +- ggml/src/ggml-metal/ggml-metal-device.cpp | 36 +- ggml/src/ggml-metal/ggml-metal-device.m | 13 +- ggml/src/ggml-metal/kernels/common.h | 43 ++ ggml/src/ggml-metal/kernels/dequantize.h | 76 +-- ggml/src/ggml-metal/kernels/fa_common.metal | 44 +- ggml/src/ggml-metal/kernels/fa_f16.metal | 39 +- ggml/src/ggml-metal/kernels/fa_f32.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q4_0.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q4_1.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q5_0.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q5_1.metal | 39 +- ggml/src/ggml-metal/kernels/fa_q8_0.metal | 39 +- ggml/src/ggml-metal/kernels/fa_tensor.metal | 33 +- .../ggml-metal/kernels/fa_vec_common.metal | 19 +- ggml/src/ggml-metal/kernels/fa_vec_f16.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_f32.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal | 24 +- ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal | 24 +- ggml/src/ggml-metal/kernels/misc.metal | 26 +- ggml/src/ggml-metal/kernels/mul_mm.metal | 624 +++++++----------- .../ggml-metal/kernels/mul_mm_tensor.metal | 537 +++++++++++++++ ggml/src/ggml-metal/kernels/mul_mv.metal | 41 +- src/llama-arch.cpp | 12 + src/llama-arch.h | 1 + src/llama-graph.cpp | 10 +- src/llama-model-saver.cpp | 12 - src/llama-model.cpp | 48 +- src/llama-model.h | 14 +- tests/test-backend-ops.cpp | 90 +++ 33 files changed, 1367 insertions(+), 764 deletions(-) create mode 100644 ggml/src/ggml-metal/kernels/mul_mm_tensor.metal diff --git a/ggml/src/ggml-metal/CMakeLists.txt b/ggml/src/ggml-metal/CMakeLists.txt index 91691b223669..0ecc07c45fff 100644 --- a/ggml/src/ggml-metal/CMakeLists.txt +++ b/ggml/src/ggml-metal/CMakeLists.txt @@ -56,6 +56,7 @@ set(METALLIB_KERNEL_SOURCES kernels/mul_mv.metal kernels/mul_mv_mma.metal kernels/mul_mm.metal + kernels/mul_mm_tensor.metal kernels/quantize.metal kernels/softmax.metal kernels/norm.metal @@ -223,21 +224,21 @@ else() # the tensor API kernels go in a separate metallib, loaded only where supported if (GGML_METAL_HAS_TENSOR_LIB) - set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor.air") + set(AIR_MM_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/mul_mm_tensor_tensor.air") # the tensor API needs OS 26+ set(XC_FLAGS_TENSOR ${XC_FLAGS} -mtargetos=${GGML_METAL_TARGET_OS}26.0${METAL_TARGET_SIM}) add_custom_command( OUTPUT ${AIR_MM_TENSOR} - COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm.metal -o ${AIR_MM_TENSOR} - DEPENDS kernels/mul_mm.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h - COMMENT "Compiling kernels/mul_mm.metal (tensor API)" + COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/mul_mm_tensor.metal -o ${AIR_MM_TENSOR} + DEPENDS kernels/mul_mm_tensor.metal kernels/common.h kernels/dequantize.h ${METALLIB_COMMON} ggml-metal-impl.h + COMMENT "Compiling kernels/mul_mm_tensor.metal (tensor API)" VERBATIM ) set(AIR_FA_TENSOR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/fa_tensor_tensor.air") add_custom_command( OUTPUT ${AIR_FA_TENSOR} - COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR} + COMMAND xcrun -sdk ${METAL_SDK} metal ${XC_FLAGS_TENSOR} -DGGML_METAL_HAS_TENSOR -DGGML_METAL_HAS_BF16 -I ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} -c ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/kernels/fa_tensor.metal -o ${AIR_FA_TENSOR} DEPENDS kernels/fa_tensor.metal kernels/common.h ${METALLIB_COMMON} ggml-metal-impl.h COMMENT "Compiling kernels/fa_tensor.metal (tensor API)" VERBATIM diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index cd9e0785053c..88ca0b832738 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -974,7 +974,15 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; - const bool has_tensor = ggml_metal_device_get_props(ggml_metal_library_get_device(lib))->has_tensor; + const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib)); + + const bool has_tensor = props_dev->has_tensor; + + const bool prec_bf16 = props_dev->has_bfloat && + ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 && + (has_tensor ? tsrc0 == GGML_TYPE_F32 : tsrc0 != GGML_TYPE_BF16); + + const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32; const bool bc_out = has_tensor ? (op->ne[0] % NRA != 0 || op->ne[1] % NRB != 0) @@ -986,7 +994,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta const int16_t r2 = (int16_t) (ne12 / op->src[0]->ne[2]); const int16_t r3 = (int16_t) (ne13 / op->src[0]->ne[3]); - snprintf(base, 256, "kernel_mul_mm_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1)); + const bool use_tensor = has_tensor && !prec_f32; + + const char * infix = use_tensor ? "_tensor" : ""; + const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : ""); + snprintf(base, 256, "kernel_mul_mm%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix); snprintf(name, 256, "%s_bci=%d_bco=%d_ne12=%d_ne13=%d_r2=%d_r3=%d", base, bc_inp, bc_out, ne12, ne13, r2, r3); @@ -1006,7 +1018,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta ggml_metal_cv_free(cv); } - if (has_tensor) { + if (use_tensor) { res.nr0 = NRA; res.nr1 = NRB; @@ -1016,7 +1028,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm(ggml_meta res.nr0 = 64; res.nr1 = 32; - res.smem = bc_out ? 8192 : (4096 + 2048); + res.smem = prec_f32 ? 12288 : (bc_out ? 8192 : (4096 + 2048)); } res.nsg = N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; @@ -1305,9 +1317,21 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m const ggml_type tsrc0 = op->src[0]->type; const ggml_type tsrc1 = op->src[1]->type; + const ggml_metal_device_props * props_dev = ggml_metal_device_get_props(ggml_metal_library_get_device(lib)); + + const bool prec_bf16 = props_dev->has_bfloat && + ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 && + tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4; + + const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32; + const bool bc_inp = op->src[0]->ne[0] % 32 != 0; - snprintf(base, 256, "kernel_mul_mm_id_%s_%s", ggml_type_name(tsrc0), ggml_type_name(tsrc1)); + const bool use_tensor = props_dev->has_tensor && !prec_f32; + + const char * infix = use_tensor ? "_tensor" : ""; + const char * suffix = prec_f32 ? "_prec_f32" : (prec_bf16 ? "_prec_bf16" : ""); + snprintf(base, 256, "kernel_mul_mm_id%s_%s_%s%s", infix, ggml_type_name(tsrc0), ggml_type_name(tsrc1), suffix); snprintf(name, 256, "%s_bci=%d", base, bc_inp); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); @@ -1321,7 +1345,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m ggml_metal_cv_free(cv); } - res.smem = 8192; + res.smem = prec_f32 ? 12288 : 8192; return res; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 2e085453adb9..293400ff256f 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -129,6 +129,7 @@ int ggml_metal_pipeline_max_theads_per_threadgroup(struct ggml_metal_pipeline_wi X(MUL_MV, mul_mv) \ X(MUL_MV_MMA, mul_mv_mma) \ X(MUL_MM, mul_mm) \ + X(MUL_MM_TENSOR, mul_mm_tensor) \ X(QUANTIZE, quantize) \ X(SOFTMAX, softmax) \ X(NORM, norm) \ @@ -1510,14 +1511,16 @@ void ggml_metal_device_get_memory(ggml_metal_device_t dev, size_t * free, size_t } } -static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_tensor) { +static bool ggml_metal_supports_mul_mat_src1_prec(const struct ggml_tensor * op, bool has_bfloat) { + GGML_ASSERT(op->op == GGML_OP_MUL_MAT || op->op == GGML_OP_MUL_MAT_ID); + const enum ggml_prec prec = ggml_prec_get_src(op, 1); if (prec == GGML_PREC_F32) { - return false; + return true; } if (prec == GGML_PREC_BF16) { - return has_tensor && op->op == GGML_OP_MUL_MAT && op->src[0]->type != GGML_TYPE_F32; + return has_bfloat && op->src[1]->type == GGML_TYPE_F32; } return true; } @@ -1907,7 +1910,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_OP_SOLVE_TRI: return has_simdgroup_reduction && op->src[0]->type == GGML_TYPE_F32; case GGML_OP_MUL_MAT: - if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) { + if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) { return false; } // the FWHT kernels read an F16 source directly; every other F16 src1 path @@ -1920,7 +1923,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te has_simdgroup_reduction, op, true, ggml_metal_op_mul_mat_use_mm(op, has_simdgroup_mm)); case GGML_OP_MUL_MAT_ID: - if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_tensor)) { + if (!ggml_metal_supports_mul_mat_src1_prec(op, dev->props.has_bfloat)) { return false; } return ggml_metal_supports_mul_mat_op( diff --git a/ggml/src/ggml-metal/kernels/common.h b/ggml/src/ggml-metal/kernels/common.h index c4d674394480..551a4d7c8e81 100644 --- a/ggml/src/ggml-metal/kernels/common.h +++ b/ggml/src/ggml-metal/kernels/common.h @@ -124,3 +124,46 @@ template<> inline float4 elu_approx(float4 x) { return res; } + +template struct value_type; +template <> struct value_type { typedef float type; }; +template <> struct value_type { typedef half type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type { typedef bfloat type; }; +#endif + +template struct value_type_4x4; +template <> struct value_type_4x4 { typedef float4x4 type; }; +template <> struct value_type_4x4 { typedef half4x4 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_4x4 { typedef bfloat4x4 type; }; +#endif + +template struct value_type_2x4; +template <> struct value_type_2x4 { typedef float2x4 type; }; +template <> struct value_type_2x4 { typedef half2x4 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_2x4 { typedef bfloat2x4 type; }; +#endif + +template struct value_type_8x8; +template <> struct value_type_8x8 { typedef simdgroup_float8x8 type; }; +template <> struct value_type_8x8 { typedef simdgroup_half8x8 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_8x8 { typedef simdgroup_bfloat8x8 type; }; +#endif + +template struct value_type_4; +template <> struct value_type_4 { typedef float4 type; }; +template <> struct value_type_4 { typedef half4 type; }; +template <> struct value_type_4 { typedef int4 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_4 { typedef bfloat4 type; }; +#endif + +template struct value_type_2; +template <> struct value_type_2 { typedef float2 type; }; +template <> struct value_type_2 { typedef half2 type; }; +#if defined(GGML_METAL_HAS_BF16) +template <> struct value_type_2 { typedef bfloat2 type; }; +#endif diff --git a/ggml/src/ggml-metal/kernels/dequantize.h b/ggml/src/ggml-metal/kernels/dequantize.h index 54e00faf6f00..96b16d7fb442 100644 --- a/ggml/src/ggml-metal/kernels/dequantize.h +++ b/ggml/src/ggml-metal/kernels/dequantize.h @@ -393,7 +393,7 @@ void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg uchar mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3); dl = d * (sc & 0xF) * coef, ml = min * (sc >> 4); for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * (q[i] & mask) - ml; + reg[i/4][i%4] = (typename value_type::type) (dl * (q[i] & mask) - ml); } } @@ -422,7 +422,7 @@ void dequantize_q3_K(device const block_q3_K *xb, short il, thread type4x4 & reg dl *= coef; for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * (q[i] & mask) - (h[i] & m ? 0 : ml); + reg[i/4][i%4] = (typename value_type::type) (dl * (q[i] & mask) - (h[i] & m ? 0 : ml)); } } @@ -446,7 +446,7 @@ void dequantize_q4_K(device const block_q4_K * xb, short il, thread type4x4 & re const ushort mask = il < 2 ? 0x0F : 0xF0; for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * (q[i] & mask) - ml; + reg[i/4][i%4] = (typename value_type::type) (dl * (q[i] & mask) - ml); } } @@ -469,7 +469,7 @@ void dequantize_q5_K(device const block_q5_K *xb, short il, thread type4x4 & reg const ushort mask = il<2 ? 0x0F : 0xF0; const float qh_val = il<2 ? 16.f : 256.f; for (int i = 0; i < 16; ++i) { - reg[i/4][i%4] = dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml; + reg[i/4][i%4] = (typename value_type::type) (dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml); } } @@ -499,10 +499,10 @@ void dequantize_q6_K(device const block_q6_K *xb, short il, thread type4x4 & reg const uint32_t low = (ql[2*i] | (uint32_t)(ql[2*i+1] << 16)) & kmask2; const uint32_t high = (qh[2*i] | (uint32_t)(qh[2*i+1] << 16)) & kmask1; const uint32_t q = ((high << shl_h) >> shr_h) | (low >> shr_l); - reg[i][0] = dl0 * ((half)(q & 0xFF)) - ml; - reg[i][1] = dl1 * ((float)(q & 0xFF00)) - ml; - reg[i][2] = dl2 * ((float)(q & 0xFF0000)) - ml; - reg[i][3] = dl3 * ((float)(q & 0xFF000000)) - ml; + reg[i][0] = (typename value_type::type) (dl0 * ((half)(q & 0xFF)) - ml); + reg[i][1] = (typename value_type::type) (dl1 * ((float)(q & 0xFF00)) - ml); + reg[i][2] = (typename value_type::type) (dl2 * ((float)(q & 0xFF0000)) - ml); + reg[i][3] = (typename value_type::type) (dl3 * ((float)(q & 0xFF000000)) - ml); } } @@ -522,12 +522,12 @@ void dequantize_iq2_xxs(device const block_iq2_xxs * xb, short il, thread type4x constant uint8_t * grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+0]); uint8_t signs = ksigns_iq2xs[(aux32_s >> 14*il) & 127]; for (int i = 0; i < 8; ++i) { - reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+1]); signs = ksigns_iq2xs[(aux32_s >> (14*il+7)) & 127]; for (int i = 0; i < 8; ++i) { - reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[2+i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } } @@ -543,12 +543,12 @@ void dequantize_iq2_xs(device const block_iq2_xs * xb, short il, thread type4x4 constant uint8_t * grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+0] & 511)); uint8_t signs = ksigns_iq2xs[q2[2*il+0] >> 9]; for (int i = 0; i < 8; ++i) { - reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+1] & 511)); signs = ksigns_iq2xs[q2[2*il+1] >> 9]; for (int i = 0; i < 8; ++i) { - reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); + reg[2+i/4][i%4] = (typename value_type::type) (dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f)); } } @@ -567,15 +567,15 @@ void dequantize_iq3_xxs(device const block_iq3_xxs * xb, short il, thread type4x constant uint8_t * grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+1]); uint8_t signs = ksigns_iq2xs[(aux32 >> 14*il) & 127]; for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f); - reg[1][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f); + reg[0][i] = (typename value_type::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f)); + reg[1][i] = (typename value_type::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f)); } grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+2]); grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+3]); signs = ksigns_iq2xs[(aux32 >> (14*il+7)) & 127]; for (int i = 0; i < 4; ++i) { - reg[2][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f); - reg[3][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f); + reg[2][i] = (typename value_type::type) (dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f)); + reg[3][i] = (typename value_type::type) (dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f)); } } @@ -593,14 +593,14 @@ void dequantize_iq3_s(device const block_iq3_s * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+0] | ((qh << 8) & 256))); constant uint8_t * grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+1] | ((qh << 7) & 256))); for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]); - reg[1][i] = dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]); + reg[0][i] = (typename value_type::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0])); + reg[1][i] = (typename value_type::type) (dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4])); } grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+2] | ((qh << 6) & 256))); grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+3] | ((qh << 5) & 256))); for (int i = 0; i < 4; ++i) { - reg[2][i] = dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]); - reg[3][i] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]); + reg[2][i] = (typename value_type::type) (dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0])); + reg[3][i] = (typename value_type::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4])); } } @@ -618,8 +618,8 @@ void dequantize_iq2_s(device const block_iq2_s * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[0] | ((qh << 8) & 0x300))); constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[1] | ((qh << 6) & 0x300))); for (int i = 0; i < 8; ++i) { - reg[i/4+0][i%4] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]); - reg[i/4+2][i%4] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]); + reg[i/4+0][i%4] = (typename value_type::type) (dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i])); + reg[i/4+2][i%4] = (typename value_type::type) (dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i])); } } @@ -637,10 +637,10 @@ void dequantize_iq1_s(device const block_iq1_s * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((h << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((h << 5) & 0x700))); for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * (grid1[i] & 0xf) + ml; - reg[1][i] = dl * (grid1[i] >> 4) + ml; - reg[2][i] = dl * (grid2[i] & 0xf) + ml; - reg[3][i] = dl * (grid2[i] >> 4) + ml; + reg[0][i] = (typename value_type::type) (dl * (grid1[i] & 0xf) + ml); + reg[1][i] = (typename value_type::type) (dl * (grid1[i] >> 4) + ml); + reg[2][i] = (typename value_type::type) (dl * (grid2[i] & 0xf) + ml); + reg[3][i] = (typename value_type::type) (dl * (grid2[i] >> 4) + ml); } } @@ -664,10 +664,10 @@ void dequantize_iq1_m(device const block_iq1_m * xb, short il, thread type4x4 & constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700))); for (int i = 0; i < 4; ++i) { - reg[0][i] = dl * (grid1[i] & 0xf) + ml1; - reg[1][i] = dl * (grid1[i] >> 4) + ml1; - reg[2][i] = dl * (grid2[i] & 0xf) + ml2; - reg[3][i] = dl * (grid2[i] >> 4) + ml2; + reg[0][i] = (typename value_type::type) (dl * (grid1[i] & 0xf) + ml1); + reg[1][i] = (typename value_type::type) (dl * (grid1[i] >> 4) + ml1); + reg[2][i] = (typename value_type::type) (dl * (grid2[i] & 0xf) + ml2); + reg[3][i] = (typename value_type::type) (dl * (grid2[i] >> 4) + ml2); } } @@ -679,10 +679,10 @@ void dequantize_iq4_nl(device const block_iq4_nl * xb, short il, thread type4x4 thread const uint8_t * q8 = (thread const uint8_t *)&aux32; for (int i = 0; i < 4; ++i) { aux32 = ((q4[2*i] | (q4[2*i+1] << 16)) >> 4*il) & 0x0f0f0f0f; - reg[i][0] = d * kvalues_iq4nl_f[q8[0]]; - reg[i][1] = d * kvalues_iq4nl_f[q8[1]]; - reg[i][2] = d * kvalues_iq4nl_f[q8[2]]; - reg[i][3] = d * kvalues_iq4nl_f[q8[3]]; + reg[i][0] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[0]]); + reg[i][1] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[1]]); + reg[i][2] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[2]]); + reg[i][3] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[3]]); } } @@ -712,10 +712,10 @@ void dequantize_iq4_xs(device const block_iq4_xs * xb, short il, thread type4x4 thread const uint8_t * q8 = (thread const uint8_t *)&aux32; for (int i = 0; i < 4; ++i) { aux32 = (q4[i] >> 4*il) & 0x0f0f0f0f; - reg[i][0] = d * kvalues_iq4nl_f[q8[0]]; - reg[i][1] = d * kvalues_iq4nl_f[q8[1]]; - reg[i][2] = d * kvalues_iq4nl_f[q8[2]]; - reg[i][3] = d * kvalues_iq4nl_f[q8[3]]; + reg[i][0] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[0]]); + reg[i][1] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[1]]); + reg[i][2] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[2]]); + reg[i][3] = (typename value_type::type) (d * kvalues_iq4nl_f[q8[3]]); } } diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index 5e08bf85fa89..35265bb1b7ee 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -17,28 +17,17 @@ constant int32_t FC_flash_attn_ext_nsg [[function_constant(FC_FLASH_ATTN_EXT + // ref: https://arxiv.org/pdf/2307.08691.pdf template< typename q_t, // query types in shared memory - typename q4_t, - typename q8x8_t, typename k_t, // key types in shared memory - typename k4x4_t, - typename k8x8_t, typename v_t, // value types in shared memory - typename v4x4_t, - typename v8x8_t, typename qk_t, // Q*K types - typename qk8x8_t, typename s_t, // soft-max types - typename s2_t, - typename s8x8_t, typename o_t, // attention accumulation types - typename o4_t, - typename o8x8_t, typename kd4x4_t, // key type in device memory short nl_k, - void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &), + void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4::type &), typename vd4x4_t, // value type in device memory short nl_v, - void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &), + void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4::type &), short DK, // K head size short DV, // V head size short Q, // queries per threadgroup @@ -58,6 +47,18 @@ void kernel_flash_attn_ext_impl( uint3 tgpig, ushort tiisg, ushort sgitg) { + using q4_t = typename value_type_4 ::type; + using q8x8_t = typename value_type_8x8 ::type; + using k4x4_t = typename value_type_4x4 ::type; + using k8x8_t = typename value_type_8x8 ::type; + using v4x4_t = typename value_type_4x4 ::type; + using v8x8_t = typename value_type_8x8 ::type; + using qk8x8_t = typename value_type_8x8::type; + using s2_t = typename value_type_2 ::type; + using s8x8_t = typename value_type_8x8 ::type; + using o4_t = typename value_type_4 ::type; + using o8x8_t = typename value_type_8x8 ::type; + const ushort iq3 = tgpig[2]; const ushort iq2 = tgpig[1]; const ushort iq1 = tgpig[0]*Q; @@ -656,28 +657,17 @@ void kernel_flash_attn_ext_impl( template< typename q_t, // query types in shared memory - typename q4_t, - typename q8x8_t, typename k_t, // key types in shared memory - typename k4x4_t, - typename k8x8_t, typename v_t, // value types in shared memory - typename v4x4_t, - typename v8x8_t, typename qk_t, // Q*K types - typename qk8x8_t, typename s_t, // soft-max types - typename s2_t, - typename s8x8_t, typename o_t, // attention accumulation types - typename o4_t, - typename o8x8_t, typename kd4x4_t, // key type in device memory short nl_k, - void (*deq_k)(device const kd4x4_t *, short, thread k4x4_t &), + void (*deq_k)(device const kd4x4_t *, short, thread typename value_type_4x4::type &), typename vd4x4_t, // value type in device memory short nl_v, - void (*deq_v)(device const vd4x4_t *, short, thread v4x4_t &), + void (*deq_v)(device const vd4x4_t *, short, thread typename value_type_4x4::type &), short DK, // K head size short DV, // V head size short Q = OP_FLASH_ATTN_EXT_NQPSG, // queries per threadgroup @@ -696,7 +686,7 @@ kernel void kernel_flash_attn_ext( uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { -#define FWD_TMPL q_t, q4_t, q8x8_t, k_t, k4x4_t, k8x8_t, v_t, v4x4_t, v8x8_t, qk_t, qk8x8_t, s_t, s2_t, s8x8_t, o_t, o4_t, o8x8_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C +#define FWD_TMPL q_t, k_t, v_t, qk_t, s_t, o_t, kd4x4_t, nl_k, deq_k, vd4x4_t, nl_v, deq_v, DK, DV, Q, C #define FWD_ARGS args, q, k, v, mask, sinks, pad, blk, dst, shmem_f16, tgpig, tiisg, sgitg switch (FC_flash_attn_ext_nsg) { // note: disabled cases to reduce library load time diff --git a/ggml/src/ggml-metal/kernels/fa_f16.metal b/ggml/src/ggml-metal/kernels/fa_f16.metal index 6e30b09e3a5a..616b9377acfc 100644 --- a/ggml/src/ggml-metal/kernels/fa_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_f16.metal @@ -6,31 +6,28 @@ // template to be able to explore different combinations #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_f32.metal b/ggml/src/ggml-metal/kernels/fa_f32.metal index 449079e8f6e5..15e499cbf00c 100644 --- a/ggml/src/ggml-metal/kernels/fa_f32.metal +++ b/ggml/src/ggml-metal/kernels/fa_f32.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q4_0.metal b/ggml/src/ggml-metal/kernels/fa_q4_0.metal index 6b05b5df6bdf..812f1f25ec79 100644 --- a/ggml/src/ggml-metal/kernels/fa_q4_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q4_0.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q4_1.metal b/ggml/src/ggml-metal/kernels/fa_q4_1.metal index 87fac701ea92..10f5c7946fae 100644 --- a/ggml/src/ggml-metal/kernels/fa_q4_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_q4_1.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q5_0.metal b/ggml/src/ggml-metal/kernels/fa_q5_0.metal index cd0e31f715a7..d0ce34ea931f 100644 --- a/ggml/src/ggml-metal/kernels/fa_q5_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q5_0.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q5_1.metal b/ggml/src/ggml-metal/kernels/fa_q5_1.metal index 4d74951acc5f..dee7fee1b2b2 100644 --- a/ggml/src/ggml-metal/kernels/fa_q5_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_q5_1.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_q8_0.metal b/ggml/src/ggml-metal/kernels/fa_q8_0.metal index bb29a262c1ea..52ad4fe6489d 100644 --- a/ggml/src/ggml-metal/kernels/fa_q8_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_q8_0.metal @@ -3,31 +3,28 @@ #include "fa_common.metal" #define FA_TYPES \ - half, half4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - half, half4x4, simdgroup_half8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_BF \ - bfloat, bfloat4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - bfloat, bfloat4x4, simdgroup_bfloat8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - half, half4, simdgroup_half8x8 - //float, float4, simdgroup_float8x8 + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + half #define FA_TYPES_F32 \ - half, half4, simdgroup_half8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, float4x4, simdgroup_float8x8, \ - float, simdgroup_float8x8, \ - float, float2, simdgroup_float8x8, \ - float, float4, simdgroup_float8x8 - //half, half4, simdgroup_half8x8 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext) flash_attn_ext_t; diff --git a/ggml/src/ggml-metal/kernels/fa_tensor.metal b/ggml/src/ggml-metal/kernels/fa_tensor.metal index 4a9ed30e3b25..8fba8f63b5a9 100644 --- a/ggml/src/ggml-metal/kernels/fa_tensor.metal +++ b/ggml/src/ggml-metal/kernels/fa_tensor.metal @@ -10,7 +10,6 @@ constant bool FC_flash_attn_ext_tensor_has_scap [[function_constant(FC_FLASH_AT // ref: https://arxiv.org/pdf/2307.08691.pdf template< typename T, // Q, K, V and P types - typename T4, short DK, // K head size short DV, // V head size short Q = OP_FLASH_ATTN_EXT_TENSOR_NQPSG, // queries per threadgroup @@ -29,6 +28,8 @@ kernel void kernel_flash_attn_ext_tensor( uint3 tgpig [[threadgroup_position_in_grid]], ushort tiisg [[thread_index_in_simdgroup]], ushort sgitg [[simdgroup_index_in_threadgroup]]) { + using T4 = typename value_type_4::type; + constexpr short NW = N_SIMDWIDTH; constexpr short NT = NW*NSG; constexpr short NQ = Q/NSG; @@ -279,20 +280,20 @@ kernel void kernel_flash_attn_ext_tensor( co.store(td); } -typedef decltype(kernel_flash_attn_ext_tensor) flash_attn_ext_tensor_t; - -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; - -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; -template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +typedef decltype(kernel_flash_attn_ext_tensor) flash_attn_ext_tensor_t; + +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_f16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; + +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk64_dv64" )]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk128_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk192_dv128")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk256_dv256")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk512_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; +template [[host_name("kernel_flash_attn_ext_tensor_bf16_dk576_dv512")]] kernel flash_attn_ext_tensor_t kernel_flash_attn_ext_tensor; #endif // GGML_METAL_HAS_TENSOR diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal index 1a96c6f7ec8b..cf37e492442b 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -15,19 +15,18 @@ constant int32_t FC_flash_attn_ext_vec_nwg [[function_constant(FC_FLASH_ATTN_EX constant bool FC_flash_attn_ext_vec_has_sparse [[function_constant(FC_FLASH_ATTN_EXT_VEC + 5)]]; constant bool FC_flash_attn_ext_vec_has_rows [[function_constant(FC_FLASH_ATTN_EXT_VEC + 6)]]; template< - typename q4_t, // query types in shared memory - typename k4_t, // key types in shared memory - typename v4_t, // value types in shared memory + typename q_t, // query types in shared memory + typename k_t, // key types in shared memory + typename v_t, // value types in shared memory typename qk_t, // Q*K types typename s_t, // soft-max types - typename s4_t, - typename o4_t, // attention accumulation types + typename o_t, // attention accumulation types typename kd4_t, // key type in device memory short nl_k, - void (*deq_k_t4)(device const kd4_t *, short, thread k4_t &), + void (*deq_k_t4)(device const kd4_t *, short, thread typename value_type_4::type &), typename vd4_t, // value type in device memory short nl_v, - void (*deq_v_t4)(device const vd4_t *, short, thread v4_t &), + void (*deq_v_t4)(device const vd4_t *, short, thread typename value_type_4::type &), short DK, // K head size short DV, // V head size short NE = 4, // head elements per thread @@ -48,6 +47,12 @@ kernel void kernel_flash_attn_ext_vec( uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { + using q4_t = typename value_type_4::type; + using k4_t = typename value_type_4::type; + using v4_t = typename value_type_4::type; + using s4_t = typename value_type_4::type; + using o4_t = typename value_type_4::type; + static_assert(DK % 32 == 0, "DK must be divisible by 32"); static_assert(DV % 32 == 0, "DV must be divisible by 32"); diff --git a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal index bea54f9f73fd..94377e39fef5 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_f32.metal b/ggml/src/ggml-metal/kernels/fa_vec_f32.metal index 18f862966a78..ebc0b4791c26 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_f32.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_f32.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal index 6bf5fad75cf1..3a496f313f3f 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q4_0.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal b/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal index 37277ee10203..5c7424665893 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q4_1.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal index 26868a228a40..509f0f1b34d1 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q5_0.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal b/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal index 9d39dc58a8d5..77cd8131e53b 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q5_1.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal b/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal index 7686ccc00126..dd789c89d710 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_q8_0.metal @@ -3,20 +3,20 @@ #include "fa_vec_common.metal" #define FA_TYPES \ - half4, \ - half4, \ - half4, \ - float, \ - float, float4, \ - float4 + half, \ + half, \ + half, \ + float, \ + float, \ + float #define FA_TYPES_F32 \ - half4, \ - float4, \ - float4, \ - float, \ - float, float4, \ - float4 + half, \ + float, \ + float, \ + float, \ + float, \ + float typedef decltype(kernel_flash_attn_ext_vec) flash_attn_ext_vec_t; diff --git a/ggml/src/ggml-metal/kernels/misc.metal b/ggml/src/ggml-metal/kernels/misc.metal index 5dfd4a60c3ab..51b435aeb47f 100644 --- a/ggml/src/ggml-metal/kernels/misc.metal +++ b/ggml/src/ggml-metal/kernels/misc.metal @@ -465,6 +465,8 @@ kernel void kernel_count_equal( ushort sgitg[[simdgroup_index_in_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort3 ntg[[threads_per_threadgroup]]) { + using T4 = typename value_type_4::type; + const short NSG = FC_count_equal_nsg; const int i3 = tgpig.z; @@ -913,12 +915,14 @@ constant bool FC_top_k_mask_has_extra [[function_constant(FC_TOP_K_MASK + 2)]]; constant bool FC_top_k_mask_vec [[function_constant(FC_TOP_K_MASK + 3)]]; // the fill runs before the scatter, both are fully parallel over the whole dst and over the picks of one row -template +template kernel void kernel_top_k_mask_fill( constant ggml_metal_kargs_top_k_mask & args, device char * dst, uint tid[[thread_position_in_grid]], uint ntot[[threads_per_grid]]) { + using T4 = typename value_type_4::type; + const T ninf = T(-INFINITY); if (FC_top_k_mask_vec) { @@ -934,14 +938,14 @@ kernel void kernel_top_k_mask_fill( } } -typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_h_t; -typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_f_t; +typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_h_t; +typedef decltype(kernel_top_k_mask_fill) kernel_top_k_mask_fill_f_t; -template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill; -template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill; +template [[host_name("kernel_top_k_mask_fill_f16")]] kernel kernel_top_k_mask_fill_h_t kernel_top_k_mask_fill; +template [[host_name("kernel_top_k_mask_fill_f32")]] kernel kernel_top_k_mask_fill_f_t kernel_top_k_mask_fill; // one threadgroup per row: copy the mask cells of the live picks and of the extra cells over the fill -template +template kernel void kernel_top_k_mask( constant ggml_metal_kargs_top_k_mask & args, device const char * mask, @@ -953,6 +957,8 @@ kernel void kernel_top_k_mask( uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg_max[[threads_per_threadgroup]]) { + using T4 = typename value_type_4::type; + const int i1 = tgpig.x; const int i2 = tgpig.y; const int i3 = tgpig.z; @@ -997,8 +1003,8 @@ kernel void kernel_top_k_mask( } } -typedef decltype(kernel_top_k_mask) kernel_top_k_mask_h_t; -typedef decltype(kernel_top_k_mask) kernel_top_k_mask_f_t; +typedef decltype(kernel_top_k_mask) kernel_top_k_mask_h_t; +typedef decltype(kernel_top_k_mask) kernel_top_k_mask_f_t; -template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask; -template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask; +template [[host_name("kernel_top_k_mask_f16")]] kernel kernel_top_k_mask_h_t kernel_top_k_mask; +template [[host_name("kernel_top_k_mask_f32")]] kernel kernel_top_k_mask_f_t kernel_top_k_mask; diff --git a/ggml/src/ggml-metal/kernels/mul_mm.metal b/ggml/src/ggml-metal/kernels/mul_mm.metal index fab720097399..e16a8ec79649 100644 --- a/ggml/src/ggml-metal/kernels/mul_mm.metal +++ b/ggml/src/ggml-metal/kernels/mul_mm.metal @@ -1,157 +1,20 @@ #include "common.h" #include "dequantize.h" -constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]]; -constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]]; -constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]]; -constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]]; -constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]]; -constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]]; +constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]]; +constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]]; +constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]]; +constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]]; +constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]]; +constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]]; constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]]; // each block_q contains 16*nl weights -#ifdef GGML_METAL_HAS_TENSOR -template< - typename SA, typename SA_4x4, typename SA_8x8, - typename SB, typename SB_2x4, typename SB_8x8, - typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread SA_4x4 &), - typename T0, typename T0_4x4, typename T1, typename T1_2x4> -kernel void kernel_mul_mm( - constant ggml_metal_kargs_mul_mm & args, - device const char * srcA, - device const char * srcB, - device char * dst, - threadgroup char * shmem [[threadgroup(0)]], - uint3 tgpig [[threadgroup_position_in_grid]], - ushort tiitg [[thread_index_in_threadgroup]], - ushort sgitg [[simdgroup_index_in_threadgroup]]) { - (void) sgitg; - - // Matrix dimensions: A(M,K) x B(K,N) -> C(M,N) - const int K = args.ne00; - const int M = args.ne0; - const int N = args.ne1; - - // Batch dimension handling - const int im = tgpig.z; - const int i12 = im % FC_mul_mm_ne12; - const int i13 = im / FC_mul_mm_ne12; - - // Batch offsets for srcA and srcB - const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03; - - // Tile dimensions - constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; - constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; - - // Tile offsets in output matrix - const int ra = tgpig.y * NRA; - const int rb = tgpig.x * NRB; - - // Threadgroup memory for dequantized A tile only - threadgroup SA * sa = (threadgroup SA *)(shmem); - - // Work-item count for A loading - constexpr int A_WORK_ITEMS = NRA * N_MM_NK; - constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; - - // tA wraps threadgroup memory - auto tA = tensor(sa, dextents(N_MM_NK_TOTAL, NRA)); - - // tB wraps device memory directly - device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13); - const int strideB = args.nb11 / sizeof(T1); - auto tB = tensor(ptrB, dextents(K, N), array({1, strideB})); - - // Configure matmul operation - // note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static - // N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0 - // ref: https://github.com/ggml-org/llama.cpp/pull/27064 - mpp::tensor_ops::matmul2d< - mpp::tensor_ops::matmul2d_descriptor( - NRB, NRA, static_cast(dynamic_extent), false, true, true, - mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), - execution_simdgroups> mm; - - auto cT = mm.get_destination_cooperative_tensor(); - - // Accumulate partial results over K dimension - for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) { - // === PHASE 1: Dequantization of A into threadgroup memory === - for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) { - const int row = work / N_MM_NK; - const int k_chunk = work % N_MM_NK; - const int k_pos = loop_k + k_chunk * 16; - const short k_base = k_chunk * 16; - - // Bounds check: skip device read if row is out of matrix bounds - if (ra + row < M) { - if (is_same::value && FC_mul_mm_bc_inp) { - // Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4). - // MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd, - // nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned. - // Mirrors the legacy kernel's existing guard. - device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0); - - FOR_UNROLL (short i = 0; i < 16; i++) { - sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0; - } - } else { - const int block_idx = k_pos / (16 * nl); - const short il = (k_pos / 16) % nl; - - device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0); - - SA_4x4 temp_a; - dequantize_func(row_ptr + block_idx, il, temp_a); - - FOR_UNROLL (short i = 0; i < 16; i++) { - // Zero-pad A for K positions beyond valid range (handles partial K iterations) - sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0; - } - } - } else { - // Zero-pad rows beyond matrix bounds - FOR_UNROLL (short i = 0; i < 16; i++) { - sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0; - } - } - } - - threadgroup_barrier(mem_flags::mem_threadgroup); - - // === PHASE 2: Tensor matmul === - // Clamp the K extent of both operand tensors to the remaining valid K range so - // the dynamic-K op never reads past the K extent of src1 (or the staged A tile). - const int kExt = min(N_MM_NK_TOTAL, K - loop_k); - - auto tAv = tensor(sa, dextents(kExt, NRA), array({1, N_MM_NK_TOTAL})); - auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents(kExt, N - rb), array({1, strideB})); - - mm.run(tBv, tAv, cT); - - threadgroup_barrier(mem_flags::mem_threadgroup); - } - - // Store result tile to output matrix (with batch offset) - // a slice is not used because its byte offset is int32 and wraps at 2 GiB - // ref: https://github.com/ggml-org/llama.cpp/pull/28748 - const int tileM = min(NRA, M - ra); - const int tileN = min(NRB, N - rb); - - device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra; - - auto tD = tensor(dstTile, dextents(tileM, tileN), array({1, M})); - cT.store(tD); -} - -#else template< - typename S0, typename S0_4x4, typename S0_8x8, - typename S1, typename S1_2x4, typename S1_8x8, - typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread S0_4x4 &), - typename T0, typename T0_4x4, typename T1, typename T1_2x4> + typename S0, typename S1, + typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4::type &), + typename T0, typename T1> kernel void kernel_mul_mm( constant ggml_metal_kargs_mul_mm & args, device const char * src0, @@ -162,8 +25,12 @@ kernel void kernel_mul_mm( ushort tiitg[[thread_index_in_threadgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { - threadgroup S0 * sa = (threadgroup S0 *)(shmem); - threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096); + using S0_4x4 = typename value_type_4x4::type; + using S0_8x8 = typename value_type_8x8::type; + using S1_2x4 = typename value_type_2x4::type; + using S1_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; constexpr int NR0 = 64; constexpr int NR1 = 32; @@ -172,6 +39,9 @@ kernel void kernel_mul_mm( constexpr int NL0 = NK/16; constexpr int NL1 = NK/8; + threadgroup S0 * sa = (threadgroup S0 *)(shmem); + threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0)); + const int im = tgpig.z; const int r0 = tgpig.y*NR0; const int r1 = tgpig.x*NR1; @@ -362,7 +232,6 @@ kernel void kernel_mul_mm( } } -#endif // GGML_METAL_HAS_TENSOR template // n_expert_used kernel void kernel_mul_mm_id_map0( @@ -544,8 +413,7 @@ template [[host_name("kernel_mul_mm_id_map0_ne20_10")]] kernel kernel_mul_mm_id_ template [[host_name("kernel_mul_mm_id_map0_ne20_16")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<16>; template [[host_name("kernel_mul_mm_id_map0_ne20_22")]] kernel kernel_mul_mm_id_map0_t kernel_mul_mm_id_map0<22>; -// TODO: refactor into two seperate functions to avoid ifdef branching: with and without tensor support -template +template::type &), typename T0, typename T1> kernel void kernel_mul_mm_id( constant ggml_metal_kargs_mul_mm_id & args, device const char * src0, @@ -558,12 +426,12 @@ kernel void kernel_mul_mm_id( ushort tiitg[[thread_index_in_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { - threadgroup S0 * sa = (threadgroup S0 *)(shmem); - threadgroup S1 * sb = (threadgroup S1 *)(shmem + 4096); - -#ifdef GGML_METAL_HAS_TENSOR - threadgroup float * sc = (threadgroup float *)(shmem); -#endif + using S0_4x4 = typename value_type_4x4::type; + using S0_8x8 = typename value_type_8x8::type; + using S1_2x4 = typename value_type_2x4::type; + using S1_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; constexpr int NR0 = 64; constexpr int NR1 = 32; @@ -572,6 +440,10 @@ kernel void kernel_mul_mm_id( constexpr int NL0 = NK/16; constexpr int NL1 = NK/8; + threadgroup S0 * sa = (threadgroup S0 *)(shmem); + threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0)); + + const int tile = tgpig.x; // entry tile, described by the prepass const int r0 = tgpig.y*NR0; @@ -608,23 +480,10 @@ kernel void kernel_mul_mm_id( // skip the upper half of the token tile when the expert did not fill it constexpr short NR1H = NR1/2; -#ifndef GGML_METAL_HAS_TENSOR S0_8x8 ma[4]; S1_8x8 mb[2]; simdgroup_float8x8 mc[8]; -#else - auto tA = tensor, tensor_inline>(sa, dextents(NK, NR0)); - - // sb is [NR1][NK] row-major - auto tB0 = tensor, tensor_inline>(sb, dextents(NK, NR1H)); - auto tB1 = tensor, tensor_inline>(sb + NR1H*NK, dextents(NK, NR1H)); - - mpp::tensor_ops::matmul2d< - mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), - execution_simdgroups<4>> mm; - -#endif const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31 @@ -645,20 +504,14 @@ kernel void kernel_mul_mm_id( const bool has_hi = nr1 > NR1H; -#ifndef GGML_METAL_HAS_TENSOR for (short i = 0; i < 8; i++){ mc[i] = make_filled_simdgroup_matrix(0.f); } // simdgroups 2,3 own rows NR1H..NR1-1 const bool sg_active = has_hi || sgitg < 2; -#else - auto cT0 = mm.get_destination_cooperative_tensor(); - auto cT1 = mm.get_destination_cooperative_tensor(); -#endif for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) { -#ifndef GGML_METAL_HAS_TENSOR // load data and store to threadgroup memory if (is_same::value && FC_mul_mm_bc_inp) { threadgroup_barrier(mem_flags::mem_threadgroup); @@ -728,66 +581,6 @@ kernel void kernel_mul_mm_id( *(threadgroup S1_2x4 *)(sb + 64*ib + 8*ly) = (S1_2x4)(*((device T1_2x4 *) y)); } -#else - // load data and store to threadgroup memory - if (is_same::value && FC_mul_mm_bc_inp) { - threadgroup_barrier(mem_flags::mem_threadgroup); - - // no need for dequantization - for (short i = 0; i < 16; i++) { - const short sx = 2*il0 + i/8; - const short sy = (tiitg/NL0)/8; - - const short lx = i%8; - const short ly = (tiitg/NL0)%8; - //const short lx = (tiitg/NL0)%8; - //const short ly = i%8; - - *(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0; - } - } else { - S0_4x4 temp_a; - dequantize_func(x, il, temp_a); - - threadgroup_barrier(mem_flags::mem_threadgroup); - - FOR_UNROLL (short i = 0; i < 16; i++) { - const short sx = 2*il0 + i/8; - const short sy = (tiitg/NL0)/8; - - const short lx = i%8; - const short ly = (tiitg/NL0)%8; - //const short lx = (tiitg/NL0)%8; - //const short ly = i%8; - - *(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4]; - } - } - - if (FC_mul_mm_bc_inp) { - for (short i = 0; i < 8; ++i) { - const short sx = (tiitg%NL1); - const short sy = (tiitg/NL1)/8; - - const short lx = i; - const short ly = (tiitg/NL1)%8; - //const short lx = (tiitg/NL1)%8; - //const short ly = i; - - *(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0; - } - } else { - const short sx = (tiitg%NL1); - const short sy = (tiitg/NL1)/8; - - //const short lx = i; - const short ly = (tiitg/NL1)%8; - //const short lx = (tiitg/NL1)%8; - //const short ly = i; - - *(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y)); - } -#endif il = (il + 2 < nl) ? il + 2 : il % 2; x = (il < 2) ? x + (2 + nl - 1)/nl : x; @@ -796,7 +589,6 @@ kernel void kernel_mul_mm_id( threadgroup_barrier(mem_flags::mem_threadgroup); -#ifndef GGML_METAL_HAS_TENSOR if (sg_active) { // load matrices from threadgroup memory and conduct outer products threadgroup const S0 * lsma = (sa + 4*64*(sgitg%2)); @@ -825,32 +617,11 @@ kernel void kernel_mul_mm_id( lsmb += 4*64; } } -#else - auto sA = tA.slice(0, 0); - auto sB0 = tB0.slice(0, 0); - - mm.run(sB0, sA, cT0); - - if (has_hi) { - auto sB1 = tB1.slice(0, 0); - - mm.run(sB1, sA, cT1); - } -#endif } // block is smaller than 64x32, we should avoid writing data outside of the matrix threadgroup_barrier(mem_flags::mem_threadgroup); -#ifdef GGML_METAL_HAS_TENSOR - auto tC0 = tensor, tensor_inline>(sc, dextents(NR0, NR1H)); - cT0.store(tC0); - - if (has_hi) { - auto tC1 = tensor, tensor_inline>(sc + NR1H*NR0, dextents(NR0, NR1H)); - cT1.store(tC1); - } -#else if (sg_active) { threadgroup float * temp_str = ((threadgroup float *) shmem) + 32*(sgitg&1) + (16*(sgitg >> 1))*NR0; @@ -858,7 +629,6 @@ kernel void kernel_mul_mm_id( simdgroup_store(mc[i], temp_str + 8*(i%4) + 8*NR0*(i/4), NR0, 0, false); } } -#endif threadgroup_barrier(mem_flags::mem_threadgroup); @@ -886,133 +656,249 @@ kernel void kernel_mul_mm_id( } } -// // matrix-matrix multiplication // -typedef decltype(kernel_mul_mm) mul_mm_t; +typedef decltype(kernel_mul_mm) mul_mm_t; + +template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_f32_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +#endif + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_f16_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +#endif +template [[host_name("kernel_mul_mm_f32_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_f16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_f32_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_f16_f32")]] kernel mul_mm_t kernel_mul_mm; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_bf16_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_bf16_bf16")]] kernel mul_mm_t kernel_mul_mm; #endif -template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm; - -template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm; -template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f32")]] kernel mul_mm_t kernel_mul_mm; + +template [[host_name("kernel_mul_mm_f32_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_f16_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q1_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_1_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q5_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_q6_K_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_xs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_xxs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq3_s_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq2_s_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_s_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq1_m_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_nl_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_iq4_xs_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_tq2_0_f16")]] kernel mul_mm_t kernel_mul_mm; // // indirect matrix-matrix multiplication // -typedef decltype(kernel_mul_mm_id) mul_mm_id; +typedef decltype(kernel_mul_mm_id) mul_mm_id; -template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_bf16_f32")]] kernel mul_mm_id kernel_mul_mm_id; #endif -template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #else -template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #endif -template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; - -template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_f32_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +#endif + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_f16_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_bf16")]] kernel mul_mm_id kernel_mul_mm_id; +#endif + +template [[host_name("kernel_mul_mm_id_f32_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f32_prec_f32")]]kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_bf16_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +#endif + +template [[host_name("kernel_mul_mm_id_f32_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_f16_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q1_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #else -template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #endif -template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; -template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q4_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q5_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_q6_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_xxs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq3_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq2_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_s_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq1_m_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_nl_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_iq4_xs_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_tq2_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; diff --git a/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal new file mode 100644 index 000000000000..9c1aee0c5690 --- /dev/null +++ b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal @@ -0,0 +1,537 @@ +#include "common.h" +#include "dequantize.h" + +#ifdef GGML_METAL_HAS_TENSOR + +constant bool FC_mul_mm_bc_inp [[function_constant(FC_MUL_MM + 0)]]; +constant bool FC_mul_mm_bc_out [[function_constant(FC_MUL_MM + 1)]]; +constant short FC_mul_mm_ne12 [[function_constant(FC_MUL_MM + 2)]]; +constant short FC_mul_mm_ne13 [[function_constant(FC_MUL_MM + 3)]]; +constant short FC_mul_mm_r2 [[function_constant(FC_MUL_MM + 4)]]; +constant short FC_mul_mm_r3 [[function_constant(FC_MUL_MM + 5)]]; +constant int32_t FC_mul_mm_id_map0_ne02 [[function_constant(FC_MUL_MM + 7)]]; + +// each block_q contains 16*nl weights +template< + typename SA, typename SB, + typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread typename value_type_4x4::type &), + typename T0, typename T1> +kernel void kernel_mul_mm_tensor( + constant ggml_metal_kargs_mul_mm & args, + device const char * srcA, + device const char * srcB, + device char * dst, + threadgroup char * shmem [[threadgroup(0)]], + uint3 tgpig [[threadgroup_position_in_grid]], + ushort tiitg [[thread_index_in_threadgroup]], + ushort sgitg [[simdgroup_index_in_threadgroup]]) { + using SA_4x4 = typename value_type_4x4::type; + using SA_8x8 = typename value_type_8x8::type; + using SB_2x4 = typename value_type_2x4::type; + using SB_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; + + (void) sgitg; + + // Matrix dimensions: A(M,K) x B(K,N) -> C(M,N) + const int K = args.ne00; + const int M = args.ne0; + const int N = args.ne1; + + // Batch dimension handling + const int im = tgpig.z; + const int i12 = im % FC_mul_mm_ne12; + const int i13 = im / FC_mul_mm_ne12; + + // Batch offsets for srcA and srcB + const uint64_t offset0 = (i12/FC_mul_mm_r2)*args.nb02 + (i13/FC_mul_mm_r3)*args.nb03; + + // Tile dimensions + constexpr int NRB = SZ_SIMDGROUP * N_MM_BLOCK_X * N_MM_SIMD_GROUP_X; + constexpr int NRA = SZ_SIMDGROUP * N_MM_BLOCK_Y * N_MM_SIMD_GROUP_Y; + + // Tile offsets in output matrix + const int ra = tgpig.y * NRA; + const int rb = tgpig.x * NRB; + + // Threadgroup memory for dequantized A tile only + threadgroup SA * sa = (threadgroup SA *)(shmem); + + // Work-item count for A loading + constexpr int A_WORK_ITEMS = NRA * N_MM_NK; + constexpr int NUM_THREADS = N_SIMDWIDTH * N_MM_SIMD_GROUP_X * N_MM_SIMD_GROUP_Y; + + // tA wraps threadgroup memory + auto tA = tensor(sa, dextents(N_MM_NK_TOTAL, NRA)); + + // tB wraps device memory directly + device T1 * ptrB = (device T1 *)(srcB + args.nb12*i12 + args.nb13*i13); + const int strideB = args.nb11 / sizeof(T1); + auto tB = tensor(ptrB, dextents(K, N), array({1, strideB})); + + // Configure matmul operation + // note: K is dynamic_extent (clamped to the valid range in PHASE 2), since a static + // N_MM_NK_TOTAL K tile would read src1 out of bounds when K % N_MM_NK_TOTAL != 0 + // ref: https://github.com/ggml-org/llama.cpp/pull/27064 + mpp::tensor_ops::matmul2d< + mpp::tensor_ops::matmul2d_descriptor( + NRB, NRA, static_cast(dynamic_extent), false, true, true, + mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), + execution_simdgroups> mm; + + auto cT = mm.get_destination_cooperative_tensor(); + + // Accumulate partial results over K dimension + for (int loop_k = 0; loop_k < K; loop_k += N_MM_NK_TOTAL) { + // === PHASE 1: Dequantization of A into threadgroup memory === + for (int work = tiitg; work < A_WORK_ITEMS; work += NUM_THREADS) { + const int row = work / N_MM_NK; + const int k_chunk = work % N_MM_NK; + const int k_pos = loop_k + k_chunk * 16; + const short k_base = k_chunk * 16; + + // Bounds check: skip device read if row is out of matrix bounds + if (ra + row < M) { + if (is_same::value && FC_mul_mm_bc_inp) { + // Element-wise reads when K is not aligned (nb01 not aligned for half4x4/float4x4). + // MSL spec Table 2.5: half4x4 requires 8-byte alignment. When K is odd, + // nb01 = K*2 is not 8-byte aligned, so odd-row pointers are misaligned. + // Mirrors the legacy kernel's existing guard. + device const T0 * row_ptr = (device const T0 *)(srcA + args.nb01 * (ra + row) + offset0); + + FOR_UNROLL (short i = 0; i < 16; i++) { + sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? (SA) row_ptr[k_pos + i] : (SA)0; + } + } else { + const int block_idx = k_pos / (16 * nl); + const short il = (k_pos / 16) % nl; + + device const block_q * row_ptr = (device const block_q *)(srcA + args.nb01 * (ra + row) + offset0); + + SA_4x4 temp_a; + dequantize_func(row_ptr + block_idx, il, temp_a); + + FOR_UNROLL (short i = 0; i < 16; i++) { + // Zero-pad A for K positions beyond valid range (handles partial K iterations) + sa[row * N_MM_NK_TOTAL + (k_base + i)] = (k_pos + i < K) ? temp_a[i/4][i%4] : (SA)0; + } + } + } else { + // Zero-pad rows beyond matrix bounds + FOR_UNROLL (short i = 0; i < 16; i++) { + sa[row * N_MM_NK_TOTAL + (k_base + i)] = (SA)0; + } + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // === PHASE 2: Tensor matmul === + // Clamp the K extent of both operand tensors to the remaining valid K range so + // the dynamic-K op never reads past the K extent of src1 (or the staged A tile). + const int kExt = min(N_MM_NK_TOTAL, K - loop_k); + + auto tAv = tensor(sa, dextents(kExt, NRA), array({1, N_MM_NK_TOTAL})); + auto tBv = tensor(ptrB + loop_k + rb * strideB, dextents(kExt, N - rb), array({1, strideB})); + + mm.run(tBv, tAv, cT); + + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // Store result tile to output matrix (with batch offset) + // a slice is not used because its byte offset is int32 and wraps at 2 GiB + // ref: https://github.com/ggml-org/llama.cpp/pull/28748 + const int tileM = min(NRA, M - ra); + const int tileN = min(NRB, N - rb); + + device float * dstTile = (device float *)dst + (uint64_t) im * N * M + (uint64_t) rb * M + ra; + + auto tD = tensor(dstTile, dextents(tileM, tileN), array({1, M})); + cT.store(tD); +} + +template::type &), typename T0, typename T1> +kernel void kernel_mul_mm_id_tensor( + constant ggml_metal_kargs_mul_mm_id & args, + device const char * src0, + device const char * src1, + device const char * htpe, + device const char * hids, + device char * dst, + threadgroup char * shmem [[threadgroup(0)]], + uint3 tgpig[[threadgroup_position_in_grid]], + ushort tiitg[[thread_index_in_threadgroup]], + ushort tiisg[[thread_index_in_simdgroup]], + ushort sgitg[[simdgroup_index_in_threadgroup]]) { + using S0_4x4 = typename value_type_4x4::type; + using S0_8x8 = typename value_type_8x8::type; + using S1_2x4 = typename value_type_2x4::type; + using S1_8x8 = typename value_type_8x8::type; + using T0_4x4 = typename value_type_4x4::type; + using T1_2x4 = typename value_type_2x4::type; + + constexpr int NR0 = 64; + constexpr int NR1 = 32; + + constexpr int NK = 32; + constexpr int NL0 = NK/16; + constexpr int NL1 = NK/8; + + threadgroup S0 * sa = (threadgroup S0 *)(shmem); + threadgroup S1 * sb = (threadgroup S1 *)(shmem + NR0*NK*sizeof(S0)); + + threadgroup float * sc = (threadgroup float *)(shmem); + + const int tile = tgpig.x; // entry tile, described by the prepass + const int r0 = tgpig.y*NR0; + + device const uint32_t * tpe_u32 = (device const uint32_t *) (htpe); + device const int32_t * ids_i32 = (device const int32_t *) (hids); + + // the prepass emits one (expert, first entry, valid rows) descriptor per tile that has + // work - the grid is sized by a static upper bound, so the tail early exits + if (tile >= (int) tpe_u32[0]) { + return; + } + + const int im = tpe_u32[1 + 3*tile]; // expert + const int idb = tpe_u32[1 + 3*tile + 1]; // first entry of this tile in hids + + // number of entries in this tile, always <= NR1 + const short nr1 = (short) ((tpe_u32[1 + 3*tile + 2] < NR1) ? tpe_u32[1 + 3*tile + 2] : NR1); + + // if this block is of 64x32 shape or smaller + const short nr0 = (args.ne0 - r0 < NR0) ? (args.ne0 - r0) : NR0; + + // a thread shouldn't load data outside of the matrix + const short lr0 = ((short)tiitg/NL0) < nr0 ? ((short)tiitg/NL0) : nr0 - 1; // 0 .. 63 + + const short il0 = (tiitg % NL0); + + const short i13 = 0; + + const uint64_t offset0 = im*args.nb02 + i13*args.nb03; + const short offset1 = il0/nl; + + const short iy = 8*(tiitg % NL1); + + // skip the upper half of the token tile when the expert did not fill it + constexpr short NR1H = NR1/2; + + auto tA = tensor, tensor_inline>(sa, dextents(NK, NR0)); + + // sb is [NR1][NK] row-major + auto tB0 = tensor, tensor_inline>(sb, dextents(NK, NR1H)); + auto tB1 = tensor, tensor_inline>(sb + NR1H*NK, dextents(NK, NR1H)); + + mpp::tensor_ops::matmul2d< + mpp::tensor_ops::matmul2d_descriptor(NR1H, NR0, NK, false, true, false, mpp::tensor_ops::matmul2d_descriptor::mode::multiply_accumulate), + execution_simdgroups<4>> mm; + + + const short lr1 = ((short)tiitg/NL1) < nr1 ? ((short)tiitg/NL1) : nr1 - 1; // 0 .. 31 + + short il = il0; + + const int id = ids_i32[idb + lr1]; + + const short i11 = (id % args.ne20) % args.ne11; + const int i12 = (id / args.ne20); + + device const block_q * x = (device const block_q *)(src0 + args.nb01*(r0 + lr0) + offset0) + offset1; + + device const T1 * y = (device const T1 *)(src1 + + args.nb13*i13 + + args.nb12*i12 + + args.nb11*i11 + + args.nb10*iy); + + const bool has_hi = nr1 > NR1H; + + auto cT0 = mm.get_destination_cooperative_tensor(); + auto cT1 = mm.get_destination_cooperative_tensor(); + + for (int loop_k = 0; loop_k < args.ne00; loop_k += NK) { + // load data and store to threadgroup memory + if (is_same::value && FC_mul_mm_bc_inp) { + threadgroup_barrier(mem_flags::mem_threadgroup); + + // no need for dequantization + for (short i = 0; i < 16; i++) { + const short sx = 2*il0 + i/8; + const short sy = (tiitg/NL0)/8; + + const short lx = i%8; + const short ly = (tiitg/NL0)%8; + //const short lx = (tiitg/NL0)%8; + //const short ly = i%8; + + *(sa + NK*(8*sy + ly) + 8*sx + lx) = loop_k + 16*il + i < args.ne00 ? (S0) *((device T0 *) x + i) : 0; + } + } else { + S0_4x4 temp_a; + dequantize_func(x, il, temp_a); + + threadgroup_barrier(mem_flags::mem_threadgroup); + + FOR_UNROLL (short i = 0; i < 16; i++) { + const short sx = 2*il0 + i/8; + const short sy = (tiitg/NL0)/8; + + const short lx = i%8; + const short ly = (tiitg/NL0)%8; + //const short lx = (tiitg/NL0)%8; + //const short ly = i%8; + + *(sa + NK*(8*sy + ly) + 8*sx + lx) = temp_a[i/4][i%4]; + } + } + + if (FC_mul_mm_bc_inp) { + for (short i = 0; i < 8; ++i) { + const short sx = (tiitg%NL1); + const short sy = (tiitg/NL1)/8; + + const short lx = i; + const short ly = (tiitg/NL1)%8; + //const short lx = (tiitg/NL1)%8; + //const short ly = i; + + *(sb + NK*(8*sy + ly) + 8*sx + lx) = loop_k + iy + i < args.ne00 ? (S1) *((device T1 *) y + i) : 0; + } + } else { + const short sx = (tiitg%NL1); + const short sy = (tiitg/NL1)/8; + + //const short lx = i; + const short ly = (tiitg/NL1)%8; + //const short lx = (tiitg/NL1)%8; + //const short ly = i; + + *(threadgroup S1_2x4 *)(sb + NK*(8*sy + ly) + 8*sx) = (S1_2x4)(*((device T1_2x4 *) y)); + } + + il = (il + 2 < nl) ? il + 2 : il % 2; + x = (il < 2) ? x + (2 + nl - 1)/nl : x; + + y += NK; + + threadgroup_barrier(mem_flags::mem_threadgroup); + + auto sA = tA.slice(0, 0); + auto sB0 = tB0.slice(0, 0); + + mm.run(sB0, sA, cT0); + + if (has_hi) { + auto sB1 = tB1.slice(0, 0); + + mm.run(sB1, sA, cT1); + } + } + + // block is smaller than 64x32, we should avoid writing data outside of the matrix + threadgroup_barrier(mem_flags::mem_threadgroup); + + auto tC0 = tensor, tensor_inline>(sc, dextents(NR0, NR1H)); + cT0.store(tC0); + + if (has_hi) { + auto tC1 = tensor, tensor_inline>(sc + NR1H*NR0, dextents(NR0, NR1H)); + cT1.store(tC1); + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + for (short j = sgitg; j < nr1; j += 4) { + const int id = ids_i32[idb + j]; + + const short ide = id % args.ne20; + const int idt = id / args.ne20; + + device float * D = (device float *) dst + r0 + (uint64_t) ide*args.ne0 + (uint64_t) idt*args.ne1*args.ne0; + device float4 * D4 = (device float4 *) D; + + threadgroup float * C = (threadgroup float *) shmem + j*NR0; + threadgroup float4 * C4 = (threadgroup float4 *) C; + + int i = tiisg; + for (; i < nr0/4; i += 32) { + *(D4 + i) = *(C4 + i); + } + + i = (4*(nr0/4)) + tiisg; + for (; i < nr0; i += 32) { + *(D + i) = *(C + i); + } + } +} + +// matrix-matrix multiplication +// + +typedef decltype(kernel_mul_mm_tensor) mul_mm_tensor_t; + +template [[host_name("kernel_mul_mm_tensor_f32_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_f16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_tensor_f32_f32_prec_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +#endif + + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_tensor_bf16_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_bf16_bf16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +#endif +template [[host_name("kernel_mul_mm_tensor_q1_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q8_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_mxfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q3_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q6_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_s_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_m_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_nl_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_xs_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_tq2_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; + +template [[host_name("kernel_mul_mm_tensor_f32_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_f16_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q1_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q8_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_mxfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q2_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q3_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q4_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q5_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_q6_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_xxs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq3_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq2_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_s_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq1_m_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_nl_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_iq4_xs_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_tq2_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; + +// +// indirect matrix-matrix multiplication +// + +typedef decltype(kernel_mul_mm_id_tensor) mul_mm_id_tensor_t; + +template [[host_name("kernel_mul_mm_id_tensor_f32_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_f16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_bf16_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif +template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#else +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif +template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_f32_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_f16_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q1_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q6_K_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f32_prec_bf16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif + +template [[host_name("kernel_mul_mm_id_tensor_f32_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_f16_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q1_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_1_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q8_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#else +template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +#endif +template [[host_name("kernel_mul_mm_id_tensor_q2_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q3_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q4_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q5_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_q6_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_xxs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq3_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq2_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_s_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq1_m_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_nl_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_iq4_xs_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_tq2_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; + +#endif // GGML_METAL_HAS_TENSOR diff --git a/ggml/src/ggml-metal/kernels/mul_mv.metal b/ggml/src/ggml-metal/kernels/mul_mv.metal index de9d76ff60dd..95e9515d5a23 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv.metal @@ -1046,7 +1046,7 @@ template [[host_name("kernel_mul_mv_bf16_bf16")]] kernel mul_mv_t_t kernel_mul_m template [[host_name("kernel_mul_mv_f32_bf16")]] kernel mul_mv_t_t kernel_mul_mv_t_t; #endif -template +template void kernel_mul_mv_t_t_4_impl( args_t args, device const char * src0, @@ -1056,6 +1056,9 @@ void kernel_mul_mv_t_t_4_impl( uint3 tgpig, ushort tiisg, ushort sgitg) { + using T04 = typename value_type_4::type; + using T14 = typename value_type_4::type; + const short NSG = FC_mul_mv_nsg; constexpr short NW = N_SIMDWIDTH; @@ -1129,7 +1132,7 @@ void kernel_mul_mv_t_t_4_impl( helper_mv_reduce_and_write(dst_f32, sumf, r0, args.ne01, tiisg, sgitg, shmem); } -template +template void kernel_mul_mv_t_t_4_disp( args_t args, device const char * src0, @@ -1140,14 +1143,14 @@ void kernel_mul_mv_t_t_4_disp( ushort tiisg, ushort sgitg) { switch (args.nr0) { - //case 1: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; - case 2: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; - //case 3: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; - //case 4: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + //case 1: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + case 2: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + //case 3: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; + //case 4: kernel_mul_mv_t_t_4_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); break; }; } -template +template kernel void kernel_mul_mv_t_t_4( constant ggml_metal_kargs_mul_mv & args, device const char * src0, @@ -1157,18 +1160,18 @@ kernel void kernel_mul_mv_t_t_4( uint3 tgpig[[threadgroup_position_in_grid]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { - kernel_mul_mv_t_t_4_disp(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); + kernel_mul_mv_t_t_4_disp(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); } -typedef decltype(kernel_mul_mv_t_t_4) mul_mv_t_t_4; +typedef decltype(kernel_mul_mv_t_t_4) mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f32_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f16_f16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; -template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_bf16_f32_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_bf16_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; +template [[host_name("kernel_mul_mv_f32_bf16_4")]] kernel mul_mv_t_t_4 kernel_mul_mv_t_t_4; #endif template @@ -3389,17 +3392,17 @@ kernel void kernel_mul_mv_id( typedef decltype(kernel_mul_mv_id>>) kernel_mul_mv_id_t; -typedef decltype(kernel_mul_mv_id>>) kernel_mul_mv_id_4_t; +typedef decltype(kernel_mul_mv_id>>) kernel_mul_mv_id_4_t; template [[host_name("kernel_mul_mv_id_f32_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_f16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mv_id_bf16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; #endif -template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; -template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_f32_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_f16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_bf16_f32_4")]] kernel kernel_mul_mv_id_4_t kernel_mul_mv_id>>; #endif template [[host_name("kernel_mul_mv_id_q8_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index cdb1f3794fe1..9019fb26d20e 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -1592,6 +1592,18 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) { } } +bool llm_arch_mmid_down_bf16(const llm_arch & arch) { + switch (arch) { + case LLM_ARCH_MISTRAL4: + case LLM_ARCH_MELLUM: + case LLM_ARCH_FLINT: + case LLM_ARCH_LAGUNA: + return true; + default: + return false; + } +} + bool llama_arch_supports_save(llm_arch arch) { switch (arch) { case LLM_ARCH_SENSENOVA_U1: diff --git a/src/llama-arch.h b/src/llama-arch.h index 6517a3ea7ea9..45ef8bc093cc 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -1037,3 +1037,4 @@ bool llm_arch_is_diffusion (const llm_arch & arch); bool llm_arch_supports_sm_tensor(const llm_arch & arch); bool llm_arch_supports_rs_rollback(const llm_arch & arch); bool llm_arch_supports_mixed_batch(const llm_arch & arch); +bool llm_arch_mmid_down_bf16(const llm_arch & arch); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 1bd3f8d0f85e..862476a5f60a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -1823,7 +1823,7 @@ ggml_tensor * llm_graph_context::build_lora_mm( } - prec_policy.apply(res); + prec_policy.apply(res, w); if (w_s) { res = ggml_mul(ctx0, res, w_s); @@ -1894,7 +1894,6 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( ggml_tensor * slots, bool cached) const { ggml_tensor * w_s = model.get_w_scale(w); - // as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur` ggml_tensor * cur_mm = build_hadamard_input(w, cur); // the experts in the MoE cache are selected by their slots @@ -1907,7 +1906,7 @@ ggml_tensor * llm_graph_context::build_lora_mm_id( } // after the NVFP4 default, so that the policy can request a higher precision - prec_policy.apply(res); + prec_policy.apply(res, w); if (w_s) { const int64_t n_expert = w_s->ne[0]; @@ -2656,15 +2655,16 @@ ggml_tensor * llm_graph_context::build_moe_ffn( // ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // the amax op cannot be split across devices, so these architectures are denied -sm tensor [TAG_MOE_AMAX_SCALE] // ref: https://github.com/ggml-org/llama.cpp/pull/30656#issuecomment-6269597922 + const bool use_amax = llm_arch_mmid_down_bf16(arch) && prec_policy.get_src1(down_exps) != GGML_PREC_BF16; + llm_graph_amax_src1 amax_src1 = { nullptr, nullptr }; - if (arch == LLM_ARCH_MISTRAL4 || arch == LLM_ARCH_MELLUM || arch == LLM_ARCH_FLINT || arch == LLM_ARCH_LAGUNA) { + if (use_amax) { amax_src1 = build_amax_src1_f16(cur); cur = amax_src1.res; } ggml_tensor * experts = build_lora_mm_id(down_exps, cur, ids, mm_ids, cached); // [n_embd, n_expert_used, n_tokens] - //ggml_prec_set_src(experts, GGML_PREC_BF16, 1); // (see TODO above) cb(experts, "ffn_moe_down", il); if (amax_src1.scale_s) { diff --git a/src/llama-model-saver.cpp b/src/llama-model-saver.cpp index c01d4dd51b5f..4a62064e7dc6 100644 --- a/src/llama-model-saver.cpp +++ b/src/llama-model-saver.cpp @@ -173,18 +173,6 @@ void llama_model_saver::add_kv_from_model() { // add_kv(LLM_KV_GENERAL_SAMPLING_MIROSTAT_ETA, ???); add_kv(LLM_KV_GENERAL_NAME, model->name); - if (!model->prec_policy.prec_src1.empty()) { - std::vector tensor_names; - std::vector values; - tensor_names.reserve(model->prec_policy.prec_src1.size()); - values.reserve(model->prec_policy.prec_src1.size()); - for (const auto & [w, prec] : model->prec_policy.prec_src1) { - tensor_names.push_back(ggml_get_name(w)); - values.push_back(prec == GGML_PREC_Q8 ? 0 : 1); - } - add_kv(LLM_KV_GENERAL_TENSOR_EXTRA_NAME, tensor_names); - gguf_set_arr_data(gguf_ctx, llm_kv(LLM_KV_GENERAL_TENSOR_EXTRA_PREC_A4).c_str(), GGUF_TYPE_BOOL, values.data(), values.size()); - } // add_kv(LLM_KV_GENERAL_AUTHOR, ???); // add_kv(LLM_KV_GENERAL_VERSION, ???); // add_kv(LLM_KV_GENERAL_URL, ???); diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 06eb7c929281..fa20378aa6d2 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -1405,19 +1406,24 @@ struct llama_model::impl { std::vector tensor_split_owned; }; -bool llama_prec_policy::apply(ggml_tensor * res) const { - if (!res || !res->src[0]) { +bool llama_prec_policy::apply(ggml_tensor * res, const ggml_tensor * w) const { + if (!res) { + return false; + } + + const ggml_tensor * key = w ? w : res->src[0]; + if (!key) { return false; } bool applied = false; - const auto it_acc = prec_acc.find(res->src[0]); + const auto it_acc = prec_acc.find(key); if (it_acc != prec_acc.end()) { applied |= ggml_prec_set_acc(res, it_acc->second); } - const auto it_src1 = prec_src1.find(res->src[0]); + const auto it_src1 = prec_src1.find(key); if (it_src1 != prec_src1.end()) { applied |= ggml_prec_set_src(res, it_src1->second, 1); } @@ -1724,6 +1730,30 @@ void llama_model_base::load_vocab(llama_model_loader & ml) { vocab.load(ml, kv); } +void llama_model_base::load_prec_policy(llama_model_loader & ml) { + // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 + if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { + for (const auto & layer : layers) { + prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); + } + } + + if (getenv("LLAMA_MOE_AMAX_SKIP") != nullptr) { + LLAMA_LOG_WARN("LLAMA_MOE_AMAX_SKIP is set - the MoE amax rescaling is disabled\n"); + + if (llm_arch_mmid_down_bf16(arch)) { + for (const auto & layer : layers) { + if (layer.ffn_down_exps) { + prec_policy.set_src1(layer.ffn_down_exps, GGML_PREC_BF16); + } + } + } + } + + // per-tensor activation precision policy + prec_policy.load(ml, *this); +} + bool llama_model_base::load_tensors(llama_model_loader & ml) { const auto & split_mode = params.split_mode; const bool use_mlock = params.load_mode == LLAMA_LOAD_MODE_MLOCK || params.load_mode == LLAMA_LOAD_MODE_MMAP_MLOCK; @@ -2080,15 +2110,7 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) { } } - // the reference computes the router in F32: https://huggingface.co/deepseek-ai/DeepSeek-V4-Flash/blob/60d8d70770c6776ff598c94bb586a859a38244f1/inference/model.py#L565 - if (hparams.expert_gating_func == LLAMA_EXPERT_GATING_FUNC_TYPE_SQRT_SOFTPLUS || hparams.expert_router_f32) { - for (const auto & layer : layers) { - prec_policy.set_acc(layer.ffn_gate_inp, GGML_PREC_F32); - } - } - - // per-tensor activation precision policy - prec_policy.load(ml, *this); + load_prec_policy(ml); ml.init_mappings(true, use_mlock ? &pimpl->mlock_mmaps : nullptr); pimpl->mappings.reserve(ml.mappings.size()); diff --git a/src/llama-model.h b/src/llama-model.h index eae5c68486ab..d7285d226173 100644 --- a/src/llama-model.h +++ b/src/llama-model.h @@ -743,7 +743,7 @@ struct llama_prec_policy { // the key is the weight tensor `res->src[0]`, stores the recommended activation precision type std::unordered_map prec_src1; - bool apply(ggml_tensor * res) const; + bool apply(ggml_tensor * res, const ggml_tensor * w = nullptr) const; void set_acc(const ggml_tensor * w, ggml_prec prec) { if (w) { @@ -751,6 +751,17 @@ struct llama_prec_policy { } } + void set_src1(const ggml_tensor * w, ggml_prec prec) { + if (w) { + prec_src1[w] = prec; + } + } + + ggml_prec get_src1(const ggml_tensor * w) const { + const auto it = prec_src1.find(w); + return it != prec_src1.end() ? it->second : GGML_PREC_UNDEFINED; + } + void load(llama_model_loader & ml, const llama_model & model); }; @@ -1146,6 +1157,7 @@ struct llama_model_base : public llama_model { void load_hparams(llama_model_loader & ml) override; void load_vocab (llama_model_loader & ml) override; bool load_tensors(llama_model_loader & ml) override; + void load_prec_policy(llama_model_loader & ml); // model must define these void load_arch_hparams(llama_model_loader & ml) override = 0; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 53961f776ef1..318225c8509a 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -6161,6 +6161,79 @@ struct test_mul_mat_id_w4a8 : public test_mul_mat_id { } }; +// src1 GGML_PREC_BF16: the implementation may keep src1 in F32 or BF16, but must not convert it down to F16 +struct test_mul_mat_id_prec_src1_bf16 : public test_mul_mat_id { + test_mul_mat_id_prec_src1_bf16(ggml_type type_a = GGML_TYPE_F32, + int n_mats = 8, int n_used = 2, bool b = false, + int64_t m = 32, int64_t n = 32, int64_t k = 256) + : test_mul_mat_id(type_a, GGML_TYPE_F32, n_mats, n_used, b, m, n, k) {} + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * out = test_mul_mat_id::build_graph(ctx); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->op == GGML_OP_MUL_MAT_ID) { + ggml_prec_set_src(t, GGML_PREC_BF16, 1); + } + } + return out; + } + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->type == GGML_TYPE_I32) { + continue; + } + if (strcmp(t->name, "b") == 0) { + init_tensor_uniform(t, -1e6f, 1e6f); + } else { + init_tensor_uniform(t); + } + } + init_mul_mat_id_ids(ctx, n_mats, skip); + } + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "MUL_MAT_ID_PREC_SRC1_BF16"; + } +}; + +struct test_mul_mat_id_prec_src1_f32 : public test_mul_mat_id { + test_mul_mat_id_prec_src1_f32(ggml_type type_a = GGML_TYPE_F32, + int n_mats = 8, int n_used = 2, bool b = false, + int64_t m = 32, int64_t n = 32, int64_t k = 256) + : test_mul_mat_id(type_a, GGML_TYPE_F32, n_mats, n_used, b, m, n, k) {} + double max_nmse_err() override { + if (type_a == GGML_TYPE_F32 || type_a == GGML_TYPE_F16) { + return 1e-10; + } + return test_mul_mat_id::max_nmse_err(); + } + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * out = test_mul_mat_id::build_graph(ctx); + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->op == GGML_OP_MUL_MAT_ID) { + ggml_prec_set_src(t, GGML_PREC_F32, 1); + } + } + return out; + } + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (t->type == GGML_TYPE_I32) { + continue; + } + if (strcmp(t->name, "b") == 0) { + init_tensor_uniform(t, -1e6f, 1e6f); + } else { + init_tensor_uniform(t); + } + } + init_mul_mat_id_ids(ctx, n_mats, skip); + } + std::string op_desc(ggml_tensor * t) override { + GGML_UNUSED(t); + return "MUL_MAT_ID_PREC_SRC1_F32"; + } +}; + // FP4 native W4A4 path on the MoE path (default precision) struct test_mul_mat_id_w4a4 : public test_mul_mat_id { test_mul_mat_id_w4a4(ggml_type type_a = GGML_TYPE_NVFP4, ggml_type type_b = GGML_TYPE_F32, @@ -12125,6 +12198,23 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_mul_mat_prec_src1_bf16_src0(GGML_TYPE_F32, 67, 33, 100)); test_cases.emplace_back(new test_mul_mat_prec_src1_bf16_src0(GGML_TYPE_F32, 64, 32, 256, {2, 3}, {2, 1})); + // src1 precision on the MoE path: mm_id (n >= 32) and mv_id (n < 32), broadcast and partial K + for (ggml_type type_a : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K, GGML_TYPE_MXFP4}) { + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 1, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 32, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 8, 2, false, 64, 512, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 16, 4, true, 72, 33, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_bf16(type_a, 4, 2, false, 67, 100, 256)); + } + + for (ggml_type type_a : {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_K, GGML_TYPE_MXFP4}) { + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 1, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 32, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 8, 2, false, 64, 512, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 16, 4, true, 72, 33, 256)); + test_cases.emplace_back(new test_mul_mat_id_prec_src1_f32(type_a, 4, 2, false, 67, 100, 256)); + } + // FP4 activation precision (default = native W4A4, src1 GGML_PREC_Q8 = W4A8) test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 32, 1, 256)); test_cases.emplace_back(new test_mul_mat_w4a8(GGML_TYPE_NVFP4, GGML_TYPE_F32, 32, 32, 256)); From 30ec35ae2e27f1eca486af02b9d3d53fa7a26950 Mon Sep 17 00:00:00 2001 From: Ed Addario <29247825+EAddario@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:06:26 +0000 Subject: [PATCH 074/401] quantize: add option to automatically choose optimal quant types to reach a file/bpw target size at lowest error (#15550) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Refactor pareto optimise and convexify * Refactor lagrange_penalty() * Refactor quantisation checks into its own function * Exit loop if no better solution found * Replace slope with cross product * Adjust for small vector size * Simplify candidates sorting * Add comments to explain magic numbers * Increase scale multiplier * Move is_iq() into a lambda and remove unused variables * Combine quant types * Reduce bpw range * Refactor outlier trimming * Tighten worker allocator * Check for direction reversal * Simplify dequantisation * Calculate bpw over all tensors * Compute rows based on tensor shape and slice count * Prioritise important tensors * Select quantization type if target_bpw is set unless user specifies type and threads * Relax lambda clamping * Add signal handler * Add save_bpw_state() * Add load_bpw_state() * Add delete_bpw_state() * Persist progress * Uninstall signal handler and cleanup * Fix trimming logic * Generate model ID hash * Remove bias mode computation * Remove --no-bias option * Automatically determine if bias error is significant * Reduce compute time by parallelising tensor processing - courtesy of https://github.com/ddh0 * Add quant types * Add --keep-bpw-state option * Refactor signal handlers * Update quant types * Minor refactoring * Add tensor type and depth heuristics * Add option to override bpw state file name * Minor refactoring * Finetune heuristics * Update usage * Fix lambda capture * Update epsilon specifier * Finetune heuristics * Simplify tensor selection * Read statistics from imatrix * Add Euclidean-Cosine score to identify important tensors * Improved is_important() logic * Fix lambda capture bug in Windows and initialise candidate_types struct * Remove processing statistics_data * Add --disable-tensor-importance option * Use more descriptive option naming * Relax target bpw range * Increase importance boost for final pass * Add B/F16 to get_ftype() * Process bpw targets up to B/F16 * Improve state checkpoint filename * Add code comments * Update usage() * Update README.md * Change checkpoint file magic * Prepare for future optimization algorithms * Add parse_target_size() * Add --target-size option * Implement target_size logic * Update usage() * Refactor parameter names * Refactor option names * Update parameter names * Improve file handling * Remove file deletion * Refactor variable names * Update usage() * Add use_wce option * Read statistics_data from imatrix * Add experimental entropy-modulated weighted cosine error (WCE) * Performance optimisations (AI assisted) * Memory optimisations (AI assisted) * Update output log * Fix state file name generation and simplify_pareto() lambda capture * Change tensor importance score logic * Refactor is_quantizable() * Improve WCE to be magnitude-aware * Expected Output Error MSE * Fix scale factor overwrite bug * Test removing unused headers * Remove wce flag * Angle-aware/Magnitude-aware (MSE/WCE) hybrid error estimation * Revert to weighted cosine error estimation * Enhanced scaling factor * Use centered‑normalized importance scaling factor (CNIF) * Remove redundant logs * Improve state file handling * Update usage instructions * Update ftype parsing logic * Flag experimental features subject to future removal * Fix --target-size description * Fix "casts away qualifiers" compiler warning * Exclude user defined tensors (--tensor-type) from the Lagrangian optimization (courtesy of https://github.com/AesSedai) * TurboQuant bias factor for inner-product sensitive tensors * TurboQuant outlier mitigation * Refactor TurboQuant improvements * Fix remap tensor bug * Remove --importance-pct option * Refactor llama_model_quantize_params to expose a pure C interface * Consolidate load/save process and remove --save-state flag * Minor log output changes * Use the tensor statistics' schema * Add quant types * Release finished tensors mmap allocation * Reuse sample buffers * Fix C2327 error when target compilation is a MS platform * Minor refactoring and AI assisted optimizations * Add uv.lock * Minor refactoring and AI assisted optimizations * Add Halko, Martinsson & Tropp randomized SVD condition number estimator * Add kappa squashing functio * Remove unnecessary includes * Add required include * Update python dependencies * Fine-tune kappa mapping parameters * Fine-tune CNIF beta parameters * Fix fallback counter error * Move to libllama and unmap weights offloaded to backend * Remove unmap weights offloaded to backend * Add winsorization * Add adaptive tensor boosting * Minor cosmetic changes * Refactor processing of unused kv tensors * Minor cosmetic change * Implement --max-buffer-size in target_bpw_type() * Fix 32-block fallback case * tensor_type_override_for() DRY refactoring * Fix typo and remove unused option * Fix #28491 linking bug when compiling with BUILD_SHARED_LIBS=OFF * Remove GGML_USE_METAL conditional macro and let the optimizer decide\ * Add --target-exclude * Remove and ignore uv.lock * Fix pinned tensors safety limits calculation * Fix truncation error * Add downwards greedy upgrade * Add target bpw/size tests * Guard imatrix schema * Update --target-bpw/size descriptions and README.md * Harden state checkpoint's file operations * Link model and imatrix to state checkpoint * Enforce and consume stats schema data * Add stats schema tests * Refactor signal handlers out of lib and harden the logic * Improve handling of pinned tensors * Add tests * Add include to keep ubuntu-webgpu happy * Moving new API entries to prevent brittle downstream apps failing * Fix miscellaneous issues --- common/imatrix-loader.cpp | 27 + common/imatrix-loader.h | 2 + include/llama.h | 9 + src/llama-ext.h | 2 +- src/llama-quant.cpp | 3516 ++++++++++++++++++++++++++------ tests/CMakeLists.txt | 1 + tests/test-quantize-target.cpp | 938 +++++++++ tools/quantize/README.md | 107 +- tools/quantize/quantize.cpp | 477 ++++- 9 files changed, 4307 insertions(+), 772 deletions(-) create mode 100644 tests/test-quantize-target.cpp diff --git a/common/imatrix-loader.cpp b/common/imatrix-loader.cpp index ec057cac2d40..ece91ff0951f 100644 --- a/common/imatrix-loader.cpp +++ b/common/imatrix-loader.cpp @@ -117,14 +117,32 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { imatrix.chunk_size = chunk_size_key != -1 ? gguf_get_val_u32(ctx_gguf, chunk_size_key) : 0; imatrix.n_layer_nextn = nextn_key != -1 ? gguf_get_val_u32(ctx_gguf, nextn_key) : 0; + const int64_t schema_idx = gguf_find_key(ctx_gguf, LLM_KV_IMATRIX_STATS_SCHEMA); + if (schema_idx != -1 && gguf_get_kv_type(ctx_gguf, schema_idx) == GGUF_TYPE_ARRAY && + gguf_get_arr_type(ctx_gguf, schema_idx) == GGUF_TYPE_STRING) { + const int64_t n_schema = gguf_get_arr_n(ctx_gguf, schema_idx); + imatrix.stats_schema.resize(n_schema); + for (int64_t i = 0; i < n_schema; ++i) { imatrix.stats_schema[i] = gguf_get_arr_str(ctx_gguf, schema_idx, i); } + } else { + if (schema_idx != -1) { + LOG_WRN("%s: %s in %s is not an array of strings, using the default order\n", __func__, LLM_KV_IMATRIX_STATS_SCHEMA, fname.c_str()); + } + + imatrix.stats_schema = { + "sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance", + }; + } + const std::string in_sum_suffix{ ".in_sum" }; const std::string in_sum2_suffix{ ".in_sum2" }; const std::string counts_suffix{ ".counts" }; + const std::string stats_suffix{ ".stats" }; struct sum_tensors { struct ggml_tensor * in_sum = nullptr; struct ggml_tensor * in_sum2 = nullptr; struct ggml_tensor * counts = nullptr; + struct ggml_tensor * stats = nullptr; }; std::map sums_counts_for; @@ -138,6 +156,8 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { sums_counts_for[std::move(name)].in_sum2 = cur; } else if (string_remove_suffix(name, counts_suffix)) { sums_counts_for[std::move(name)].counts = cur; + } else if (string_remove_suffix(name, stats_suffix)) { + sums_counts_for[std::move(name)].stats = cur; } } @@ -146,6 +166,7 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { const struct ggml_tensor * in_sum = sc.second.in_sum; const struct ggml_tensor * in_sum2 = sc.second.in_sum2; const struct ggml_tensor * counts = sc.second.counts; + const struct ggml_tensor * stats = sc.second.stats; if (!in_sum2 || !counts || (in_sum != nullptr && ggml_nelements(in_sum) != ggml_nelements(in_sum2))) { LOG_ERR("%s: mismatched sums and counts for %s\n", __func__, name.c_str()); @@ -182,6 +203,12 @@ bool common_imatrix_load(const std::string & fname, common_imatrix & imatrix) { e.activations[j] = ((const float *) in_sum->data)[j]; } } + + if (stats && stats->type == GGML_TYPE_F32) { + const int64_t n_stats = ggml_nelements(stats); + e.stats.resize(n_stats); + for (int64_t j = 0; j < n_stats; ++j) { e.stats[j] = ((const float *) stats->data)[j]; } + } } gguf_free(ctx_gguf); diff --git a/common/imatrix-loader.h b/common/imatrix-loader.h index d4616bf304af..1b6d8c4c0436 100644 --- a/common/imatrix-loader.h +++ b/common/imatrix-loader.h @@ -15,11 +15,13 @@ struct common_imatrix_entry { std::vector sums; std::vector activations; std::vector counts; + std::vector stats; }; struct common_imatrix { std::map entries; std::vector datasets; + std::vector stats_schema; int32_t chunk_count = 0; int32_t chunk_size = 0; int32_t n_layer_nextn = 0; diff --git a/include/llama.h b/include/llama.h index 7122143e5c61..9cc17a82b529 100644 --- a/include/llama.h +++ b/include/llama.h @@ -466,6 +466,15 @@ extern "C" { const struct llama_model_tensor_override * tt_overrides; // pointer to tensor overrides const int32_t * prune_layers; // pointer to layer indices to prune size_t max_buf_size; // max bytes of tensor rows kept in memory at once, 0 = default (8 GiB) + const struct llama_model_imatrix_data * activations; // pointer to activations data + const struct llama_model_imatrix_data * statistics; // pointer to statistics data + const char * const * stats_schema; // pointer to statistics schema names + float target_bpw; // target bits per weight (bpw) + int64_t target_size; // target file size in bytes + const char * state_file; // pointer to bpw state file + const enum ggml_type * target_exclude; // pointer to excluded GGML_TYPEs + ggml_abort_callback abort_callback; // callback to abort quantization + void * abort_callback_data; // pointer to user data for abort_callback } llama_model_quantize_params; typedef struct llama_logit_bias { diff --git a/src/llama-ext.h b/src/llama-ext.h index b8b7fba0bf77..a77b2f40948a 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -51,7 +51,7 @@ LLAMA_API quantize_state_impl * llama_quant_init( const llama_model * model, const llama_model_quantize_params * params); -LLAMA_API void llama_quant_free(quantize_state_impl * qs); +LLAMA_API void llama_quant_free(const quantize_state_impl * qs); // Descriptor for constructing a mock model for quantization testing. struct llama_quant_model_desc { diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 0515756dcee9..c66f060f621e 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -2,58 +2,63 @@ #include "llama-model.h" #include "llama-model-loader.h" #include "llama-ext.h" -#include "llama.h" +#include "llama-quant.h" #include -#include -#include +#include +#include +#include #include +#include +#include +#include #include #include +#include +#include +#include +#include #include #include #include +#include // result of parsing --tensor-type option // (changes to this struct must be reflected in tools/quantize/quantize.cpp) struct tensor_type_option { std::string name; - ggml_type type = GGML_TYPE_COUNT; + ggml_type type = GGML_TYPE_COUNT; }; // tensor categorization - used to avoid repeated string matching in quantization logic. // this is different from LLM_TN - we want broad categories, not specific tensor names per arch. -enum class tensor_category { - TOKEN_EMBD, - ATTENTION_Q, - ATTENTION_V, - ATTENTION_K, - ATTENTION_QKV, - ATTENTION_KV_B, - ATTENTION_OUTPUT, - ATTENTION_GATE, - FFN_UP, - FFN_GATE, - FFN_DOWN, - FFN_LATENT, - OUTPUT, - OTHER +enum tensor_category { + TENSOR_CATEGORY_TOKEN_EMBD, + TENSOR_CATEGORY_ATTENTION_Q, + TENSOR_CATEGORY_ATTENTION_V, + TENSOR_CATEGORY_ATTENTION_K, + TENSOR_CATEGORY_ATTENTION_QKV, + TENSOR_CATEGORY_ATTENTION_KV_B, + TENSOR_CATEGORY_ATTENTION_OUTPUT, + TENSOR_CATEGORY_ATTENTION_GATE, + TENSOR_CATEGORY_FFN_UP, + TENSOR_CATEGORY_FFN_GATE, + TENSOR_CATEGORY_FFN_DOWN, + TENSOR_CATEGORY_FFN_LATENT, + TENSOR_CATEGORY_OUTPUT, + TENSOR_CATEGORY_OTHER }; // max amount of tensor data kept in memory while quantizing a single tensor static const size_t LLAMA_QUANT_MAX_BUF_SIZE = 8ull*1024*1024*1024; -static void zeros(std::ofstream & file, size_t n) { - char zero = 0; - for (size_t i = 0; i < n; ++i) { - file.write(&zero, 1); - } +static void zeros(std::ofstream & file, const size_t n) { + constexpr char zero = 0; + for (size_t i = 0; i < n; ++i) { file.write(& zero, 1); } } static std::string remap_layer(const std::string & orig_name, const std::vector & prune, std::map & mapped, int & next_id) { - if (prune.empty()) { - return orig_name; - } + if (prune.empty()) { return orig_name; } static const std::regex pattern(R"(blk\.(\d+)\.)"); if (std::smatch match; std::regex_search(orig_name, match, pattern)) { @@ -79,9 +84,7 @@ static std::string remap_layer(const std::string & orig_name, const std::vector< } static std::string remap_imatrix(const std::string & orig_name, const std::map & mapped) { - if (mapped.empty()) { - return orig_name; - } + if (mapped.empty()) { return orig_name; } static const std::regex pattern(R"(blk\.(\d+)\.)"); if (std::smatch match; std::regex_search(orig_name, match, pattern)) { @@ -89,20 +92,16 @@ static std::string remap_imatrix(const std::string & orig_name, const std::map= n_unused_from; } + + return false; +} + +// tensor categorization for quantization +static tensor_category tensor_get_category(const std::string & tensor_name) { + if (tensor_name_match_output_weight(tensor_name.c_str())) { return TENSOR_CATEGORY_OUTPUT; } + if (tensor_name_match_token_embd(tensor_name.c_str())) { return TENSOR_CATEGORY_TOKEN_EMBD; } // attn_qkv_gate is [attn_qkv | attn_gate] in one weight, the qkv rows decide its type - if (tensor_name.find("attn_qkv.weight") != std::string::npos || tensor_name.find("attn_qkv_gate.weight") != std::string::npos) { - return tensor_category::ATTENTION_QKV; - } - if (tensor_name.find("attn_kv_b.weight") != std::string::npos) { - return tensor_category::ATTENTION_KV_B; - } - if (tensor_name.find("attn_v.weight") != std::string::npos) { - return tensor_category::ATTENTION_V; - } - if (tensor_name.find("attn_k.weight") != std::string::npos) { - return tensor_category::ATTENTION_K; - } - if (tensor_name.find("attn_q.weight") != std::string::npos) { - return tensor_category::ATTENTION_Q; - } - if (tensor_name.find("attn_output.weight") != std::string::npos) { - return tensor_category::ATTENTION_OUTPUT; - } - if (tensor_name.find("ffn_up") != std::string::npos) { - return tensor_category::FFN_UP; - } - if (tensor_name.find("ffn_gate") != std::string::npos) { - return tensor_category::FFN_GATE; - } - if (tensor_name.find("ffn_latent") != std::string::npos) { - return tensor_category::FFN_LATENT; - } - if (tensor_name.find("attn_gate.weight") != std::string::npos) { - return tensor_category::ATTENTION_GATE; - } - if (tensor_name.find("ffn_down") != std::string::npos) { - return tensor_category::FFN_DOWN; - } - return tensor_category::OTHER; + if (tensor_name.find("attn_qkv.weight") != std::string::npos || tensor_name.find("attn_qkv_gate.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_QKV; } + if (tensor_name.find("attn_kv_b.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_KV_B; } + if (tensor_name.find("attn_v.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_V; } + if (tensor_name.find("attn_k.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_K; } + if (tensor_name.find("attn_q.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_Q; } + if (tensor_name.find("attn_output.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_OUTPUT; } + if (tensor_name.find("ffn_up") != std::string::npos) { return TENSOR_CATEGORY_FFN_UP; } + if (tensor_name.find("ffn_gate") != std::string::npos) { return TENSOR_CATEGORY_FFN_GATE; } + if (tensor_name.find("ffn_latent") != std::string::npos) { return TENSOR_CATEGORY_FFN_LATENT; } + if (tensor_name.find("attn_gate.weight") != std::string::npos) { return TENSOR_CATEGORY_ATTENTION_GATE; } + if (tensor_name.find("ffn_down") != std::string::npos) { return TENSOR_CATEGORY_FFN_DOWN; } + + return TENSOR_CATEGORY_OTHER; } // check if tensor is a MoE expert tensor (used by GGML_OP_MUL_MAT_ID) @@ -169,16 +150,11 @@ static bool tensor_is_expert(const std::string & tensor_name) { } // check if category is for attention-v-like tensors (more sensitive to quantization) -static bool category_is_attn_v(tensor_category cat) { - return cat == tensor_category::ATTENTION_V || - cat == tensor_category::ATTENTION_QKV || - cat == tensor_category::ATTENTION_KV_B; +static bool category_is_attn_v(const tensor_category cat) { + return cat == TENSOR_CATEGORY_ATTENTION_V || cat == TENSOR_CATEGORY_ATTENTION_QKV || cat == TENSOR_CATEGORY_ATTENTION_KV_B; } -// // quantization state -// - struct quantize_state_impl { const llama_model & model; const llama_model_quantize_params * params; @@ -191,29 +167,55 @@ struct quantize_state_impl { int i_ffn_down = 0; int i_ffn_gate = 0; int i_ffn_up = 0; - - int n_fallback = 0; - + int n_fallback = 0; bool has_imatrix = false; // used to figure out if a model has tied embeddings (tok_embd shares weights with output) bool has_tied_embeddings = true; // assume tied until we see output.weight + bool has_activations = false; - // tensor type override patterns (compiled once, used twice) - std::vector> tensor_type_patterns; + // tensor type override patterns (compiled once, queried via tensor_type_override_for()) + struct tensor_type_pattern { + std::string pattern; + std::regex regex; + ggml_type type; + }; - quantize_state_impl(const llama_model & model, const llama_model_quantize_params * params): - model(model), params(params) - { + std::vector tensor_type_patterns; + std::array ignored_types{}; + bool has_ignored_types = false; + + quantize_state_impl(const llama_model & model, const llama_model_quantize_params * params) : model(model), params(params) { // compile regex patterns once - they are expensive if (params->tt_overrides) { - for (const auto * p = params->tt_overrides; p->pattern != nullptr; p++) { - tensor_type_patterns.emplace_back(std::regex(p->pattern), p->type); + for (const auto * o = params->tt_overrides; o->pattern != nullptr; o++) { + tensor_type_patterns.push_back({o->pattern, std::regex(o->pattern), o->type}); + } + } + + if (params->target_exclude) { + for (const auto * t = params->target_exclude; * t != GGML_TYPE_COUNT; t++) { + if (* t >= 0 && * t < GGML_TYPE_COUNT) { + ignored_types[*t] = true; + has_ignored_types = true; + } } } } }; +// the --tensor-type override for the tensor or GGML_TYPE_COUNT if none +static ggml_type tensor_type_override_for(const quantize_state_impl & qs, const char * tensor_name) { + if (qs.tensor_type_patterns.empty()) { return GGML_TYPE_COUNT; } + + const std::string name(tensor_name); + for (const auto & p : qs.tensor_type_patterns) { + if (std::regex_search(name, p.regex)) { return p.type; } + } + + return GGML_TYPE_COUNT; +} + // per-tensor metadata, computed in the preliminary loop and used in the main loop struct tensor_metadata { std::string name; @@ -224,68 +226,55 @@ struct tensor_metadata { bool requires_imatrix; }; -// // dequantization -// - -static void llama_tensor_dequantize_impl( - ggml_type type, const void * data, float * f32_output, std::vector & workers, - const size_t nelements, const int nthread +static void llama_tensor_dequantize_impl(ggml_type type, + const void * data, + float * f32_output, + std::vector & workers, + const size_t nelements, + const int nthread ) { const ggml_type_traits * qtype = ggml_get_type_traits(type); if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { - if (qtype->to_float == NULL) { + if (qtype->to_float == nullptr) { throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(type))); } - } else if (type != GGML_TYPE_F16 && - type != GGML_TYPE_BF16) { + } else if (type != GGML_TYPE_F16 && type != GGML_TYPE_BF16) { throw std::runtime_error(format("cannot dequantize/convert tensor type %s", ggml_type_name(type))); } if (nthread < 2) { - if (type == GGML_TYPE_F16) { - ggml_fp16_to_fp32_row((const ggml_fp16_t *)data, f32_output, nelements); - } else if (type == GGML_TYPE_BF16) { - ggml_bf16_to_fp32_row((const ggml_bf16_t *)data, f32_output, nelements); - } else if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { - qtype->to_float(data, f32_output, nelements); - } else { - GGML_ABORT("fatal error"); // unreachable - } + if (type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)data, f32_output, nelements); } + else if (type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)data, f32_output, nelements); } + else if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { qtype->to_float(data, f32_output, nelements); } + else { GGML_ABORT("fatal error"); } + return; } size_t block_size; - if (type == GGML_TYPE_F16 || - type == GGML_TYPE_BF16) { - block_size = 1; - } else { - block_size = (size_t)ggml_blck_size(type); - } + if (type == GGML_TYPE_F16 || type == GGML_TYPE_BF16) { block_size = 1; } + else { block_size = (size_t)ggml_blck_size(type); } - size_t block_size_bytes = ggml_type_size(type); + const size_t block_size_bytes = ggml_type_size(type); GGML_ASSERT(nelements % block_size == 0); - size_t nblocks = nelements / block_size; - size_t blocks_per_thread = nblocks / nthread; - size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count + const size_t nblocks = nelements / block_size; + const size_t blocks_per_thread = nblocks / nthread; + const size_t spare_blocks = nblocks - (blocks_per_thread * nthread); // if blocks aren't divisible by thread count size_t in_buff_offs = 0; size_t out_buff_offs = 0; for (int tnum = 0; tnum < nthread; tnum++) { - size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread + const size_t thr_blocks = blocks_per_thread + (tnum == nthread - 1 ? spare_blocks : 0); // num blocks for this thread size_t thr_elems = thr_blocks * block_size; // number of elements for this thread - size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread + const size_t thr_block_bytes = thr_blocks * block_size_bytes; // number of input bytes for this thread auto compute = [qtype] (ggml_type typ, const uint8_t * inbuf, float * outbuf, int nels) { - if (typ == GGML_TYPE_F16) { - ggml_fp16_to_fp32_row((const ggml_fp16_t *)inbuf, outbuf, nels); - } else if (typ == GGML_TYPE_BF16) { - ggml_bf16_to_fp32_row((const ggml_bf16_t *)inbuf, outbuf, nels); - } else { - qtype->to_float(inbuf, outbuf, nels); - } + if (typ == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)inbuf, outbuf, nels); } + else if (typ == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)inbuf, outbuf, nels); } + else { qtype->to_float(inbuf, outbuf, nels); } }; workers.emplace_back(compute, type, (const uint8_t *) data + in_buff_offs, f32_output + out_buff_offs, thr_elems); in_buff_offs += thr_block_bytes; @@ -295,21 +284,17 @@ static void llama_tensor_dequantize_impl( workers.clear(); } -// // do we allow this tensor to be quantized? -// - static bool tensor_allows_quantization(const llama_model_quantize_params * params, llm_arch arch, const ggml_tensor * tensor) { - // trivial checks first -- no string ops needed - if (params->only_copy) return false; + if (params->only_copy) { return false; } // quantize only 2D+ tensors (matrices, experts, conv kernels) - if (ggml_n_dims(tensor) < 2) return false; + if (ggml_n_dims(tensor) < 2) { return false; } const std::string name = ggml_get_name(tensor); - // This used to be a regex, but has an extreme cost to compile times. - bool quantize = name.rfind("weight") == name.size() - 6; // ends with 'weight'? + // ends with 'weight'? + bool quantize = name.rfind("weight") == name.size() - 6; // do not quantize norm tensors quantize &= name.find("_norm.weight") == std::string::npos; @@ -317,7 +302,6 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= params->quantize_output_tensor || name != "output.weight"; // do not quantize expert gating tensors - // NOTE: can't use LLM_TN here because the layer number is not known quantize &= name.find("ffn_gate_inp.weight") == std::string::npos; // do not quantize the i32 token-id -> expert-id routing table (DeepSeek-V4) @@ -360,7 +344,6 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param quantize &= name != LLM_TN(arch)(LLM_TENSOR_TOKEN_TYPES, "weight"); // do not quantize Mamba/Kimi's small conv1d weights - // NOTE: can't use LLM_TN here because the layer number is not known quantize &= name.find("ssm_conv1d") == std::string::npos; quantize &= name.find("shortconv.conv.weight") == std::string::npos; @@ -458,90 +441,77 @@ static bool tensor_allows_quantization(const llama_model_quantize_params * param return quantize; } -// -// tensor type selection -// +// mapping from an incompatible target type to its block-size-32 substitute +static ggml_type fallback_type_for(const ggml_type target_type) { + switch (target_type) { + // types on the left, block size 256; types on the right, block size 32 + case GGML_TYPE_IQ1_S: + case GGML_TYPE_IQ1_M: + case GGML_TYPE_IQ2_XXS: + case GGML_TYPE_IQ2_XS: + case GGML_TYPE_IQ2_S: + case GGML_TYPE_IQ3_XXS: + case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_XS: return GGML_TYPE_IQ4_NL; + case GGML_TYPE_Q2_0: + case GGML_TYPE_Q2_K: + case GGML_TYPE_Q3_K: + case GGML_TYPE_TQ1_0: + case GGML_TYPE_TQ2_0: return GGML_TYPE_Q4_0; + case GGML_TYPE_Q4_K: return GGML_TYPE_Q5_0; + case GGML_TYPE_Q5_K: return GGML_TYPE_Q5_1; + case GGML_TYPE_Q6_K: return GGML_TYPE_Q8_0; + default: + if (ggml_blck_size(target_type) <= 32) { return GGML_TYPE_COUNT; } // nothing smaller to demote to + throw std::runtime_error(format("no tensor type fallback is defined for type %s", ggml_type_name(target_type))); + } +} // incompatible tensor shapes are handled here - fallback to a compatible type static ggml_type tensor_type_fallback(quantize_state_impl & qs, const ggml_tensor * t, const ggml_type target_type) { - ggml_type return_type = target_type; - const int64_t ncols = t->ne[0]; const int64_t qk_k = ggml_blck_size(target_type); - - if (ncols % qk_k != 0) { // this tensor's shape is incompatible with this quant - LLAMA_LOG_WARN("warning: %-36s - ncols %6" PRId64 " not divisible by %3" PRId64 " (required for type %7s) ", - t->name, ncols, qk_k, ggml_type_name(target_type)); - ++qs.n_fallback; - - switch (target_type) { - // types on the left: block size 256 - case GGML_TYPE_IQ1_S: - case GGML_TYPE_IQ1_M: - case GGML_TYPE_IQ2_XXS: - case GGML_TYPE_IQ2_XS: - case GGML_TYPE_IQ2_S: - case GGML_TYPE_IQ3_XXS: - case GGML_TYPE_IQ3_S: // types on the right: block size 32 - case GGML_TYPE_IQ4_XS: return_type = GGML_TYPE_IQ4_NL; break; - case GGML_TYPE_Q2_0: - case GGML_TYPE_Q2_K: - case GGML_TYPE_Q3_K: - case GGML_TYPE_TQ1_0: - case GGML_TYPE_TQ2_0: return_type = GGML_TYPE_Q4_0; break; - case GGML_TYPE_Q4_K: return_type = GGML_TYPE_Q5_0; break; - case GGML_TYPE_Q5_K: return_type = GGML_TYPE_Q5_1; break; - case GGML_TYPE_Q6_K: return_type = GGML_TYPE_Q8_0; break; - default: - if (qk_k <= 32) { - // the target is already a 32-block type, so there is no smaller block to demote to - // the check below turns it into F16, as a 256-block type does when its fallback does not fit - return_type = target_type; - break; - } - throw std::runtime_error(format("no tensor type fallback is defined for type %s", - ggml_type_name(target_type))); - } - if (ncols % ggml_blck_size(return_type) != 0) { - // - // the fallback return type is still not compatible for this tensor! - // - // most likely, this tensor's first dimension is not divisible by 32. - // this is very rare. we can either abort the quantization, or - // fallback to F16 / F32. - // - LLAMA_LOG_WARN("(WARNING: must use F16 due to unusual shape) "); - return_type = GGML_TYPE_F16; - } - LLAMA_LOG_WARN("-> falling back to %7s\n", ggml_type_name(return_type)); - } - return return_type; + if (ncols % qk_k == 0) { return target_type; } // this tensor's shape is compatible with this quant + ++qs.n_fallback; + LLAMA_LOG_WARN("warning: %-36s - ncols %6" PRId64 " not divisible by %3" PRId64 " (required for type %7s) ", + t->name, ncols, qk_k, ggml_type_name(target_type)); + + ggml_type fallback_type = fallback_type_for(target_type); + if (fallback_type == GGML_TYPE_COUNT || ncols % ggml_blck_size(fallback_type) != 0) { + // + // the fallback return type is still not compatible for this tensor! + // + // most likely, this tensor's first dimension is not divisible by 32. + // this is very rare. we can either abort the quantization, or + // fallback to F16 / F32. + // + LLAMA_LOG_WARN("(WARNING: must use F16 due to unusual shape) "); + fallback_type = GGML_TYPE_F16; + } + LLAMA_LOG_WARN("-> falling back to %7s\n", ggml_type_name(fallback_type)); + + return fallback_type; } -// internal standard logic for selecting the target tensor type based on tensor category, ftype, and model arch +// select the target tensor type based on tensor category, ftype, and model arch static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype, tensor_category category) { const std::string name = ggml_get_name(tensor); // TODO: avoid hardcoded tensor names - use the TN_* constants const llm_arch arch = qs.model.arch; - - auto use_more_bits = [](int i_layer, int n_layers) -> bool { - return i_layer < n_layers/8 || i_layer >= 7*n_layers/8 || (i_layer - n_layers/8)%3 == 2; + auto use_more_bits = [](const int i_layer, const int n_layers) -> bool { + return i_layer < n_layers / 8 || i_layer >= 7 * n_layers / 8 || (i_layer - n_layers / 8) % 3 == 2; }; + const int n_expert = std::max(1, (int)qs.model.hparams.n_expert); - auto layer_info = [n_expert] (int i_layer, int n_layer, const char * name) { + auto layer_info = [n_expert] (int i_layer, int n_layer, const char * tname) { if (n_expert > 1) { - // Believe it or not, "experts" in the FFN of Mixtral-8x7B are not consecutive, but occasionally randomly - // sprinkled in the model. Hence, simply dividing i_ffn_down by n_expert does not work - // for getting the current layer as I initially thought, and we need to resort to parsing the - // tensor name. - if (sscanf(name, "blk.%d.", &i_layer) != 1) { - throw std::runtime_error(format("Failed to determine layer for tensor %s", name)); - } - if (i_layer < 0 || i_layer >= n_layer) { - throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, name, n_layer)); - } + // Experts may not be consecutive and simply dividing i_ffn_down by n_expert does not work, + // so we need to parse the tensor name + if (sscanf(tname, "blk.%d.", &i_layer) != 1) { throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); } + if (i_layer < 0 || i_layer >= n_layer) { throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, tname, n_layer)); } } + return std::make_pair(i_layer, n_layer); }; @@ -564,22 +534,16 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type // bumping to q8_0 is preferred since these tensors are not really big // TODO: nemotron 3 super shares ffn_latent and afmoe, bailingmoe3, dots3note, hy-v4, kimi-k3 and laguna share attn_gate. // Widening the guard is likely a win there too, but it changes their files, so it wants a perplexity comparison per architecture first. - if (arch == LLM_ARCH_MUSE_SPARK && - (category == tensor_category::FFN_LATENT || category == tensor_category::ATTENTION_GATE)) { - auto bits_per_weight = [](ggml_type t) { - return 8.0 * ggml_type_size(t) / ggml_blck_size(t); - }; - if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) { - new_type = GGML_TYPE_Q8_0; - } + if (arch == LLM_ARCH_MUSE_SPARK && (category == TENSOR_CATEGORY_FFN_LATENT || category == TENSOR_CATEGORY_ATTENTION_GATE)) { + auto bits_per_weight = [](ggml_type t) { return 8.0 * ggml_type_size(t) / ggml_blck_size(t); }; + if (ggml_is_quantized(new_type) && bits_per_weight(new_type) < bits_per_weight(GGML_TYPE_Q8_0)) { new_type = GGML_TYPE_Q8_0; } } - // for arches that share the same tensor between the token embeddings and the output, we quantize the token embeddings - // with the quantization of the output tensor - if (category == tensor_category::OUTPUT || (qs.has_tied_embeddings && category == tensor_category::TOKEN_EMBD)) { - if (qs.params->output_tensor_type < GGML_TYPE_COUNT) { - new_type = qs.params->output_tensor_type; - } else { + // for arches that share the same tensor between the token embeddings and the output, + // we quantize the token embeddings with the quantization of the output tensor + if (category == TENSOR_CATEGORY_OUTPUT || (qs.has_tied_embeddings && category == TENSOR_CATEGORY_TOKEN_EMBD)) { + if (qs.params->output_tensor_type < GGML_TYPE_COUNT) { new_type = qs.params->output_tensor_type; } + else { const int64_t nx = tensor->ne[0]; const int64_t qk_k = ggml_blck_size(new_type); @@ -599,14 +563,14 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type } } } else if (ftype == LLAMA_FTYPE_MOSTLY_MXFP4_MOE) { - // MoE tensors -> MXFP4 - // other tensors -> Q8_0 if (tensor_is_expert(name)) { + // MoE tensors -> MXFP4 new_type = GGML_TYPE_MXFP4; } else { + // other tensors -> Q8_0 new_type = GGML_TYPE_Q8_0; } - } else if (category == tensor_category::TOKEN_EMBD) { + } else if (category == TENSOR_CATEGORY_TOKEN_EMBD) { if (qs.params->token_embedding_type < GGML_TYPE_COUNT) { new_type = qs.params->token_embedding_type; } else { @@ -627,242 +591,189 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) { if (category_is_attn_v(category)) { - if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) new_type = GGML_TYPE_Q4_K; - else new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K; + if (qs.model.hparams.n_gqa() >= 4 || qs.model.hparams.n_expert >= 4) { new_type = GGML_TYPE_Q4_K; } + else { new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K; } + ++qs.i_attention_wv; } - else if (qs.model.hparams.n_expert == 8 && category == tensor_category::ATTENTION_K) { - new_type = GGML_TYPE_Q4_K; - } - else if (category == tensor_category::FFN_DOWN) { + else if (qs.model.hparams.n_expert == 8 && category == TENSOR_CATEGORY_ATTENTION_K) { new_type = GGML_TYPE_Q4_K; } + else if (category == TENSOR_CATEGORY_FFN_DOWN) { if (qs.i_ffn_down < qs.n_ffn_down/8) { new_type = ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ? GGML_TYPE_IQ3_S : GGML_TYPE_Q2_K; } + ++qs.i_ffn_down; } - else if (category == tensor_category::ATTENTION_OUTPUT) { - if (qs.model.hparams.n_expert == 8) { - new_type = GGML_TYPE_Q5_K; - } else { - if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) new_type = GGML_TYPE_IQ2_XXS; - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) new_type = GGML_TYPE_IQ3_S; + else if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT) { + if (qs.model.hparams.n_expert == 8) { new_type = GGML_TYPE_Q5_K; } + else { + if (ftype == LLAMA_FTYPE_MOSTLY_IQ1_S || ftype == LLAMA_FTYPE_MOSTLY_IQ1_M) { new_type = GGML_TYPE_IQ2_XXS; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M) { new_type = GGML_TYPE_IQ3_S; } } } } else if (category_is_attn_v(category)) { - if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { - new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) { - new_type = GGML_TYPE_Q4_K; - } + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q4_K; } else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = qs.model.hparams.n_gqa() >= 4 ? GGML_TYPE_Q4_K : !qs.has_imatrix ? GGML_TYPE_IQ3_S : GGML_TYPE_IQ3_XXS; } - else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) { - new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { - new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) { - new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q5_K; - else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) { - new_type = GGML_TYPE_Q5_K; - } + else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S) && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) { new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = GGML_TYPE_Q5_K; } + else if ((ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && qs.model.hparams.n_gqa() >= 4) { new_type = GGML_TYPE_Q5_K; } else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) && - use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) new_type = GGML_TYPE_Q6_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) new_type = GGML_TYPE_Q5_K; + use_more_bits(qs.i_attention_wv, qs.n_attention_wv)) { new_type = GGML_TYPE_Q6_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) { new_type = GGML_TYPE_Q5_K; } if (qs.model.type == LLM_TYPE_70B) { // In the 70B model we have 8 heads sharing the same attn_v weights. As a result, the attn_v.weight tensor is // 8x smaller compared to attn_q.weight. Hence, we can get a nice boost in quantization accuracy with // nearly negligible increase in model size by quantizing this tensor with more bits: - if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) new_type = GGML_TYPE_Q5_K; + if (new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K) { new_type = GGML_TYPE_Q5_K; } } if (qs.model.hparams.n_expert == 8) { // for the 8-expert model, bumping this to Q8_0 trades just ~128MB // TODO: explore better strategies new_type = GGML_TYPE_Q8_0; } + ++qs.i_attention_wv; - } else if (category == tensor_category::ATTENTION_K) { + } else if (category == TENSOR_CATEGORY_ATTENTION_K) { if (qs.model.hparams.n_expert == 8) { - // for the 8-expert model, bumping this to Q8_0 trades just ~128MB // TODO: explore better strategies new_type = GGML_TYPE_Q8_0; } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { - new_type = GGML_TYPE_IQ3_XXS; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { - new_type = GGML_TYPE_IQ2_S; - } - } else if (category == tensor_category::ATTENTION_Q) { - if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { - new_type = GGML_TYPE_IQ3_XXS; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { - new_type = GGML_TYPE_IQ2_S; - } - } else if (category == tensor_category::FFN_DOWN) { + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { new_type = GGML_TYPE_IQ3_XXS; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ2_S; } + } else if (category == TENSOR_CATEGORY_ATTENTION_Q) { + if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS) { new_type = GGML_TYPE_IQ3_XXS; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ2_S; } + } else if (category == TENSOR_CATEGORY_FFN_DOWN) { auto info = layer_info(qs.i_ffn_down, qs.n_ffn_down, name.c_str()); int i_layer = info.first, n_layer = info.second; - if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) new_type = GGML_TYPE_Q3_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) { - if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) { - new_type = i_layer < n_layer/8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; - } + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) { new_type = GGML_TYPE_Q3_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S) { if (i_layer < n_layer/8) new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS && !qs.has_imatrix) { new_type = i_layer < n_layer / 8 ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; } else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) { new_type = i_layer < n_layer/16 ? GGML_TYPE_Q5_K : arch != LLM_ARCH_FALCON || use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q4_K : GGML_TYPE_Q3_K; } - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer/8 || - (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) { + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M && (i_layer < n_layer / 8 || (qs.model.hparams.n_expert == 8 && use_more_bits(i_layer, n_layer)))) { new_type = GGML_TYPE_Q4_K; } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { - new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K; - } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = arch == LLM_ARCH_FALCON ? GGML_TYPE_Q4_K : GGML_TYPE_Q5_K; } else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) { if (arch == LLM_ARCH_FALCON) { - new_type = i_layer < n_layer/16 ? GGML_TYPE_Q6_K : - use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; - } else { - if (use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K; - } + new_type = i_layer < n_layer / 16 ? GGML_TYPE_Q6_K : use_more_bits(i_layer, n_layer) ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K; + } else if (use_more_bits(i_layer, n_layer)) { new_type = GGML_TYPE_Q6_K; } } - else if (i_layer < n_layer/8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) { + else if (i_layer < n_layer / 8 && (ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) && !qs.has_imatrix) { new_type = GGML_TYPE_Q5_K; } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) new_type = GGML_TYPE_Q6_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) { - new_type = GGML_TYPE_Q5_K; - } - else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0) - && qs.has_imatrix && i_layer < n_layer/8) { - // Guard against craziness in the first few ffn_down layers that can happen even with imatrix for Q4_0/Q5_0. - // We only do it when an imatrix is provided because a) we want to make sure that one can always get the - // same quantization as before imatrix stuff, and b) Q4_1/Q5_1 do go crazy on ffn_down without an imatrix. + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M && use_more_bits(i_layer, n_layer)) { new_type = GGML_TYPE_Q6_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && arch != LLM_ARCH_FALCON && i_layer < n_layer/8) { new_type = GGML_TYPE_Q5_K; } + else if ((ftype == LLAMA_FTYPE_MOSTLY_Q4_0 || ftype == LLAMA_FTYPE_MOSTLY_Q5_0) && qs.has_imatrix && i_layer < n_layer / 8) { + // Safeguard against instability in the initial ffn_down layers, which can occur with Q4_0/Q5_0 quantization even when an imatrix is used. + // The rationale is two-fold: first, to guarantee that the resulting quantization remains consistent with the pre-imatrix state, + // and second, because Q4_1/Q5_1 tend to exhibit instability in ffn_down layers without an imatrix. new_type = ftype == LLAMA_FTYPE_MOSTLY_Q4_0 ? GGML_TYPE_Q4_1 : GGML_TYPE_Q5_1; } + ++qs.i_ffn_down; - } else if (category == tensor_category::ATTENTION_OUTPUT) { + } else if (category == TENSOR_CATEGORY_ATTENTION_OUTPUT) { if (arch != LLM_ARCH_FALCON) { if (qs.model.hparams.n_expert == 8) { if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S || ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S || - ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) { - new_type = GGML_TYPE_Q5_K; - } + ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS) { new_type = GGML_TYPE_Q5_K; } } else { - if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) new_type = GGML_TYPE_Q3_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) new_type = GGML_TYPE_IQ3_S; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) new_type = GGML_TYPE_Q4_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) new_type = GGML_TYPE_Q5_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) new_type = GGML_TYPE_Q4_K; + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K ) { new_type = GGML_TYPE_Q3_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS) { new_type = GGML_TYPE_IQ3_S; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M ) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L ) { new_type = GGML_TYPE_Q5_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_M ) { new_type = GGML_TYPE_Q4_K; } } - } else { - if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) new_type = GGML_TYPE_Q4_K; - } + } else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) { new_type = GGML_TYPE_Q4_K; } } - else if (category == tensor_category::ATTENTION_QKV) { - if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { - new_type = GGML_TYPE_Q4_K; - } - else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) new_type = GGML_TYPE_Q5_K; - else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) new_type = GGML_TYPE_Q6_K; + else if (category == TENSOR_CATEGORY_ATTENTION_QKV) { + if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L || ftype == LLAMA_FTYPE_MOSTLY_IQ3_M) { new_type = GGML_TYPE_Q4_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) { new_type = GGML_TYPE_Q5_K; } + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) { new_type = GGML_TYPE_Q6_K; } } - else if (category == tensor_category::FFN_GATE) { + else if (category == TENSOR_CATEGORY_FFN_GATE) { auto info = layer_info(qs.i_ffn_gate, qs.n_ffn_gate, name.c_str()); int i_layer = info.first, n_layer = info.second; - if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) { - new_type = GGML_TYPE_IQ3_XXS; - } + if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && i_layer >= n_layer / 8 && i_layer < 7 * n_layer / 8) { new_type = GGML_TYPE_IQ3_XXS; } + ++qs.i_ffn_gate; } - else if (category == tensor_category::FFN_UP) { + else if (category == TENSOR_CATEGORY_FFN_UP) { auto info = layer_info(qs.i_ffn_up, qs.n_ffn_up, name.c_str()); int i_layer = info.first, n_layer = info.second; - if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && (i_layer >= n_layer/8 && i_layer < 7*n_layer/8)) { - new_type = GGML_TYPE_IQ3_XXS; - } + if (ftype == LLAMA_FTYPE_MOSTLY_IQ3_XS && i_layer >= n_layer / 8 && i_layer < 7 * n_layer / 8) { new_type = GGML_TYPE_IQ3_XXS; } + ++qs.i_ffn_up; } return new_type; } -// outer wrapper: determine the ggml_type that this tensor should be quantized to -static ggml_type llama_tensor_get_type(quantize_state_impl & qs, const llama_model_quantize_params * params, const ggml_tensor * tensor, ggml_type default_type, const tensor_metadata & tm) { - if (!tensor_allows_quantization(params, qs.model.arch, tensor)) { - return tensor->type; - } - if (params->token_embedding_type < GGML_TYPE_COUNT && tm.category == tensor_category::TOKEN_EMBD) { +// determine the ggml_type that this tensor should be quantized to +static ggml_type llama_tensor_get_type(quantize_state_impl & qs, + const llama_model_quantize_params * params, + const ggml_tensor * tensor, + const ggml_type default_type, + const tensor_metadata & tm +) { + if (params->target_bpw != -1.0f || params->target_size != -1) { return tensor->type; } + if (!tensor_allows_quantization(params, qs.model.arch, tensor)) { return tensor->type; } + if (params->token_embedding_type < GGML_TYPE_COUNT && tm.category == TENSOR_CATEGORY_TOKEN_EMBD) { // per_layer_token_embd follows --token-embedding-type by default, but it is a large // separate table, so let an explicit --tensor-type name it - bool named = false; - if (std::strcmp(tensor->name, "per_layer_token_embd.weight") == 0) { - const std::string tensor_name(tensor->name); - for (const auto & [pattern, qtype] : qs.tensor_type_patterns) { - if (std::regex_search(tensor_name, pattern)) { - named = true; - break; - } - } - } - if (!named) { - return params->token_embedding_type; - } - } - if (params->output_tensor_type < GGML_TYPE_COUNT && tm.category == tensor_category::OUTPUT) { - return params->output_tensor_type; + const bool named = std::strcmp(tensor->name, "per_layer_token_embd.weight") == 0 && tensor_type_override_for(qs, tensor->name) != GGML_TYPE_COUNT; + if (!named) { return params->token_embedding_type; } } + if (params->output_tensor_type < GGML_TYPE_COUNT && tm.category == TENSOR_CATEGORY_OUTPUT) { return params->output_tensor_type; } ggml_type new_type = default_type; // get more optimal quantization type based on the tensor shape, layer, etc. if (ggml_is_quantized(default_type)) { - // if the user provided tensor types - use those - bool manual = false; - if (!qs.tensor_type_patterns.empty()) { - const std::string tensor_name(tensor->name); - for (const auto & [pattern, qtype] : qs.tensor_type_patterns) { - if (std::regex_search(tensor_name, pattern)) { - if (qtype != new_type) { - LLAMA_LOG_WARN("%s: %-36s - applying manual override: %s -> %s\n", - __func__, tensor_name.c_str(), ggml_type_name(new_type), ggml_type_name(qtype)); - new_type = qtype; - } - manual = true; - break; - } - } + // if the user provided tensor types, use those + const ggml_type manual_type = tensor_type_override_for(qs, tensor->name); + const bool manual = manual_type != GGML_TYPE_COUNT; + if (manual && manual_type != new_type) { + LLAMA_LOG_WARN("%s: %-36s - applying manual override: %s -> %s\n", + __func__, tensor->name, ggml_type_name(new_type), ggml_type_name(manual_type)); + new_type = manual_type; } - // if not manual - use the standard logic for choosing the quantization type based on the selected mixture - if (!manual && !params->pure) { - new_type = llama_tensor_get_type_impl(qs, new_type, tensor, params->ftype, tm.category); - } + // otherwise, use the standard logic + if (!manual && !params->pure) { new_type = llama_tensor_get_type_impl(qs, new_type, tensor, params->ftype, tm.category); } - // incompatible tensor shapes are handled here - fallback to a compatible type + // if incompatible tensor shape, fallback to a compatible type new_type = tensor_type_fallback(qs, tensor, new_type); } return new_type; } -// -// quantization implementation -// - // quantize rows [first_row, first_row + nrows), indexed globally across all expert matrices // note: chunks never cross an expert boundary since each expert has its own imatrix slice -static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * f32_data, void * new_data, const int64_t chunk_size, int64_t first_row, int64_t nrows, int64_t nrows_per_expert, int64_t n_per_row, const float * imatrix, std::vector & workers, const int nthread) { +static size_t llama_tensor_quantize_impl(ggml_type new_type, + const float * f32_data, + void * new_data, + const int64_t chunk_size, + int64_t first_row, + int64_t nrows, + int64_t nrows_per_expert, + int64_t n_per_row, + const float * imatrix, + std::vector & workers, + const int nthread +) { const size_t row_size = ggml_row_size(new_type, n_per_row); auto imatrix_for_row = [=](int64_t row_global) { @@ -877,12 +788,12 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * const int64_t this_nrow = std::min(nrows - row, nrows_per_expert - row_global % nrows_per_expert); void * this_data = (char *) new_data + row * row_size; size_t this_size = ggml_quantize_chunk(new_type, f32_data + row * n_per_row, this_data, 0, this_nrow, n_per_row, imatrix_for_row(row_global)); - if (!ggml_validate_row_data(new_type, this_data, this_size)) { - throw std::runtime_error("quantized data validation failed"); - } + if (!ggml_validate_row_data(new_type, this_data, this_size)) { throw std::runtime_error("quantized data validation failed"); } + new_size += this_size; row += this_nrow; } + return new_size; } @@ -891,15 +802,13 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * size_t new_size = 0; bool valid = true; auto compute = [&mutex, &counter, &new_size, &valid, new_type, f32_data, new_data, chunk_size, - first_row, nrows, nrows_per_expert, n_per_row, row_size, imatrix_for_row]() { + first_row, nrows, nrows_per_expert, n_per_row, row_size, imatrix_for_row] { const int64_t nrows_per_chunk = chunk_size / n_per_row; size_t local_size = 0; while (true) { std::unique_lock lock(mutex); if (counter >= nrows) { - if (local_size > 0) { - new_size += local_size; - } + if (local_size > 0) { new_size += local_size; } break; } const int64_t row = counter; @@ -921,140 +830,2346 @@ static size_t llama_tensor_quantize_impl(enum ggml_type new_type, const float * } } }; - for (int it = 0; it < nthread - 1; ++it) { - workers.emplace_back(compute); - } + + for (int it = 0; it < nthread - 1; ++it) { workers.emplace_back(compute); } compute(); for (auto & w : workers) { w.join(); } workers.clear(); - if (!valid) { - throw std::runtime_error("quantized data validation failed"); - } + if (!valid) { throw std::runtime_error("quantized data validation failed"); } + return new_size; } -// -// imatrix requirement check -// +// Returns tensor type overrides that meet a global file size or bpw target +static std::unordered_map target_bpw_type( + llama_model_loader & ml, + quantize_state_impl & qs, + const std::vector & tensors, + const std::map & mapped, + const std::unordered_map> * values_data, + const std::unordered_map> * activations_data, + const std::unordered_map> * statistics_data, + const std::vector * stats_schema, + const std::unordered_map * locked_tensors, + int nthread +) { + bool interrupted = false; + std::mutex interrupt_mutex; + auto poll_interrupt = [&]() { + if (!qs.params->abort_callback) { return false; } + std::lock_guard lock(interrupt_mutex); + if (!interrupted) { interrupted = qs.params->abort_callback(qs.params->abort_callback_data); } + return interrupted; + }; -static bool tensor_requires_imatrix(const char * tensor_name, const ggml_type dst_type, const llama_ftype ftype) { - if (tensor_name_match_token_embd(tensor_name) || tensor_name_match_output_weight(tensor_name)) { - return false; - } - switch (dst_type) { - case GGML_TYPE_IQ3_XXS: - case GGML_TYPE_IQ2_XXS: - case GGML_TYPE_IQ2_XS: - case GGML_TYPE_IQ2_S: - case GGML_TYPE_IQ1_M: - case GGML_TYPE_IQ1_S: - return true; - case GGML_TYPE_Q2_K: - // as a general rule, the k-type quantizations don't require imatrix data. - // the only exception is Q2_K tensors that are part of a Q2_K_S file. - return ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S; - default: - return false; - } -} + // GGML_TYPE scores + struct type_scores { + ggml_type type = GGML_TYPE_COUNT; + float bpw = 0.0f; + size_t bytes = 0; + double error = 0.0; + double mse = 0.0; + double wce = 0.0; + }; -// -// given a file type, get the default tensor type -// + // Tensor quantization type choice + struct type_choice { + const llama_model_loader::llama_tensor_weight * w = nullptr; + std::vector candidates; + int choice = -1; + float min_bpw = 0.0; + float max_bpw = 0.0; + size_t n_elements = 0; + float boost = 1.0f; + }; -ggml_type llama_ftype_get_default_type(llama_ftype ftype) { - switch (ftype) { - case LLAMA_FTYPE_MOSTLY_Q4_0: return GGML_TYPE_Q4_0; - case LLAMA_FTYPE_MOSTLY_Q4_1: return GGML_TYPE_Q4_1; - case LLAMA_FTYPE_MOSTLY_Q5_0: return GGML_TYPE_Q5_0; - case LLAMA_FTYPE_MOSTLY_Q5_1: return GGML_TYPE_Q5_1; - case LLAMA_FTYPE_MOSTLY_Q8_0: return GGML_TYPE_Q8_0; - case LLAMA_FTYPE_MOSTLY_F16: return GGML_TYPE_F16; - case LLAMA_FTYPE_MOSTLY_BF16: return GGML_TYPE_BF16; - case LLAMA_FTYPE_ALL_F32: return GGML_TYPE_F32; - case LLAMA_FTYPE_MOSTLY_Q1_0: return GGML_TYPE_Q1_0; - case LLAMA_FTYPE_MOSTLY_Q2_0: return GGML_TYPE_Q2_0; + // Quantization types + constexpr ggml_type quant_types[] = { + GGML_TYPE_IQ1_S, + GGML_TYPE_IQ1_M, + GGML_TYPE_IQ2_XXS, + GGML_TYPE_IQ2_XS, + GGML_TYPE_IQ2_S, + GGML_TYPE_IQ3_XXS, + GGML_TYPE_IQ3_S, + GGML_TYPE_IQ4_XS, + GGML_TYPE_IQ4_NL, + GGML_TYPE_Q2_K, + GGML_TYPE_Q3_K, + GGML_TYPE_Q4_0, + GGML_TYPE_Q4_1, + GGML_TYPE_Q4_K, + GGML_TYPE_Q5_0, + GGML_TYPE_Q5_1, + GGML_TYPE_Q5_K, + GGML_TYPE_Q6_K, + GGML_TYPE_Q8_0, + GGML_TYPE_F16, + GGML_TYPE_BF16, + }; - case LLAMA_FTYPE_MOSTLY_MXFP4_MOE: return GGML_TYPE_MXFP4; + constexpr double EPSILON = 1e-12; + constexpr double INFINITE = std::numeric_limits::infinity(); + constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2" + constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d; + constexpr float ffn_down_boost = 6.0f; + constexpr float output_boost = 3.0f; + constexpr float tied_embd_boost = 2.5f; + constexpr float attn_v_boost = 1.25f; + constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw + constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted + const char * func = __func__; - // K-quants - case LLAMA_FTYPE_MOSTLY_Q2_K_S: - case LLAMA_FTYPE_MOSTLY_Q2_K: return GGML_TYPE_Q2_K; - case LLAMA_FTYPE_MOSTLY_IQ3_XS: return GGML_TYPE_IQ3_S; - case LLAMA_FTYPE_MOSTLY_Q3_K_S: - case LLAMA_FTYPE_MOSTLY_Q3_K_M: - case LLAMA_FTYPE_MOSTLY_Q3_K_L: return GGML_TYPE_Q3_K; - case LLAMA_FTYPE_MOSTLY_Q4_K_S: - case LLAMA_FTYPE_MOSTLY_Q4_K_M: return GGML_TYPE_Q4_K; - case LLAMA_FTYPE_MOSTLY_Q5_K_S: - case LLAMA_FTYPE_MOSTLY_Q5_K_M: return GGML_TYPE_Q5_K; - case LLAMA_FTYPE_MOSTLY_Q6_K: return GGML_TYPE_Q6_K; - case LLAMA_FTYPE_MOSTLY_TQ1_0: return GGML_TYPE_TQ1_0; - case LLAMA_FTYPE_MOSTLY_TQ2_0: return GGML_TYPE_TQ2_0; - case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return GGML_TYPE_IQ2_XXS; - case LLAMA_FTYPE_MOSTLY_IQ2_XS: return GGML_TYPE_IQ2_XS; - case LLAMA_FTYPE_MOSTLY_IQ2_S: return GGML_TYPE_IQ2_XS; - case LLAMA_FTYPE_MOSTLY_IQ2_M: return GGML_TYPE_IQ2_S; - case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return GGML_TYPE_IQ3_XXS; - case LLAMA_FTYPE_MOSTLY_IQ1_S: return GGML_TYPE_IQ1_S; - case LLAMA_FTYPE_MOSTLY_IQ1_M: return GGML_TYPE_IQ1_M; - case LLAMA_FTYPE_MOSTLY_IQ4_NL: return GGML_TYPE_IQ4_NL; - case LLAMA_FTYPE_MOSTLY_IQ4_XS: return GGML_TYPE_IQ4_XS; - case LLAMA_FTYPE_MOSTLY_IQ3_S: - case LLAMA_FTYPE_MOSTLY_IQ3_M: return GGML_TYPE_IQ3_S; + // --target-exclude must leave at least one quant type in the pool + if (qs.has_ignored_types) { + bool all_ignored = true; + for (const ggml_type t : quant_types) { + if (!qs.ignored_types[t]) { all_ignored = false; break; } + } - default: return GGML_TYPE_COUNT; + if (all_ignored) { throw std::runtime_error(format("%s: --target-exclude bars every quant type in the selection pool\n", func)); } } -} + // Tensor size in bytes for a given type + auto tensor_bytes = [](const ggml_tensor * gt, const ggml_type gq) -> size_t { + return (size_t)ggml_nrows(gt) * ggml_row_size(gq, gt->ne[0]); + }; -static void init_quantize_state_counters(quantize_state_impl & qs, std::vector & metadata) { - for (auto & tm : metadata) { - tensor_category cat = tensor_get_category(tm.name); - tm.category = cat; + // Tensor bpw for a given type + auto tensor_bpw = [&](const ggml_tensor * gt, const ggml_type gq) -> double { + return (double)tensor_bytes(gt, gq) * 8.0 / (double)ggml_nelements(gt); + }; - if (category_is_attn_v(cat)) { - ++qs.n_attention_wv; - } + // Check if tensor is compatible with quantization type + auto is_compatible = [](const ggml_tensor * gt, const ggml_type gq) -> bool { + const int64_t blck = ggml_blck_size(gq); + return blck <= 1 || gt->ne[0] % blck == 0; + }; + + // Get suitable fallback for type + auto make_compatible = [&](const ggml_tensor * gt, const ggml_type gq) -> ggml_type { + if (is_compatible(gt, gq)) { return gq; } + const ggml_type fb = fallback_type_for(gq); + return fb != GGML_TYPE_COUNT && is_compatible(gt, fb) ? fb : GGML_TYPE_F16; + }; - if (cat == tensor_category::OUTPUT) { - qs.has_tied_embeddings = false; + // Check if tensor is an IQ type + auto is_iq = [](const enum ggml_type gt) { + switch (gt) { + case GGML_TYPE_IQ1_S: + case GGML_TYPE_IQ1_M: + case GGML_TYPE_IQ2_XXS: + case GGML_TYPE_IQ2_XS: + case GGML_TYPE_IQ2_S: + case GGML_TYPE_IQ3_XXS: + case GGML_TYPE_IQ3_S: + case GGML_TYPE_IQ4_NL: + case GGML_TYPE_IQ4_XS: + return true; + default: + return false; } - } - qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)qs.model.hparams.n_layer_all; -} + }; -// -// main quantization driver -// + // Check if tensor can be quantized + auto can_quantize = [&](const ggml_tensor * gt) -> bool { + if (ggml_n_dims(gt) < 2 || ggml_n_dims(gt) > 3) { return false; } // skip 1D & 4D+ tensors + return tensor_allows_quantization(qs.params, qs.model.arch, gt); + }; -static void llama_model_quantize_impl(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) { - llama_ftype ftype = params->ftype; + // DJB2 hashing algorithm + auto djb2_hash = [&](const uint8_t * data, const size_t n, uint64_t h = 5381) -> uint64_t { + for (size_t i = 0; i < n; ++i) { h = (h << 5) + h + data[i]; } + return h ? h : HASH_MAGIC; + }; - int nthread = params->nthread; + // Model ID from the metadata, the imatrix data and the pruned layers + const uint64_t model_id = [&] { + const size_t sz = gguf_get_meta_size(ml.metadata); + std::vector buf(sz); + gguf_get_meta_data(ml.metadata, buf.data()); + uint64_t h = djb2_hash(buf.data(), buf.size()); + auto hash_bytes = [&](const void * data, const size_t n) { h = djb2_hash((const uint8_t *)data, n, h); }; + auto hash_size = [&](const uint64_t n) { hash_bytes(& n, sizeof(n)); }; + + for (const auto * m : { values_data, activations_data, statistics_data }) { + const uint8_t present = m != nullptr; + hash_bytes(& present, sizeof(present)); + if (!m) { continue; } + + // the maps have no fixed order + std::vector names; + names.reserve(m->size()); + for (const auto & e : * m) { names.push_back(e.first); } + std::sort(names.begin(), names.end()); + + hash_size(names.size()); + for (const auto & name : names) { + const std::vector & v = m->at(name); + hash_size(name.size()); + hash_bytes(name.data(), name.size()); + hash_size(v.size()); + hash_bytes(v.data(), v.size() * sizeof(float)); + } + } - if (nthread <= 0) { - nthread = std::thread::hardware_concurrency(); - } + const uint8_t has_schema = stats_schema != nullptr; + hash_bytes(& has_schema, sizeof(has_schema)); + if (stats_schema) { + hash_size(stats_schema->size()); + for (const auto & name : * stats_schema) { + hash_size(name.size()); + hash_bytes(name.data(), name.size()); + } + } - ggml_type default_type = llama_ftype_get_default_type(ftype); - if (default_type == GGML_TYPE_COUNT) { - throw std::runtime_error(format("invalid output file type %d\n", ftype)); - } + for (const auto & [blk, num] : mapped) { + const int32_t b = blk; + hash_bytes(& b, sizeof(b)); + hash_size(num.size()); + hash_bytes(num.data(), num.size()); + } - // mmap consistently increases speed on Linux, and also increases speed on Windows with - // hot cache. It may cause a slowdown on macOS, possibly related to free memory. -#if defined(__linux__) || defined(_WIN32) - constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_MMAP; -#else - constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_NONE; -#endif + return h; + }(); - const llama_model_kv_override * kv_overrides = params->kv_overrides; - std::vector splits = {}; - llama_model_loader ml(/*metadata*/ nullptr, /*set_tensor_data*/ nullptr, /*set_tensor_data_ud*/ nullptr, - fname_inp, splits, /*file*/ nullptr, /*load_mode*/ load_mode, /*check_tensors*/ true, /*no_alloc*/ false, /*load_mtp*/ true, kv_overrides, nullptr); - ml.init_mappings(false); // no prefetching + std::string checkpoint_file; + + { + char hex[17]; + std::string name; + std::snprintf(hex, sizeof(hex), "%016" PRIx64, (uint64_t)model_id); + ml.get_key(LLM_KV_GENERAL_NAME, name, false); + name.erase(0, name.find_last_of('/') + 1); + std::replace(name.begin(), name.end(), ' ', '_'); + name.empty() ? checkpoint_file = ml.arch_name : checkpoint_file = name; + checkpoint_file += "-" + std::string(hex) + ".bpw_state"; + + if (qs.params->state_file) { + if (qs.params->state_file[0] != '\0') { checkpoint_file = qs.params->state_file; } + const char * fname = checkpoint_file.c_str(); + FILE * f = std::fopen(fname, "rb"); + if (!f && errno == ENOENT) { + f = std::fopen(fname, "wbx"); + if (!f) { throw std::runtime_error(format("%s: failed to open %s: %s\n", func, fname, std::strerror(errno))); } + std::fclose(f); + if (std::remove(fname) != 0) { LLAMA_LOG_WARN("%s: failed to remove %s: %s\n", func, fname, std::strerror(errno)); } + } else { + const bool readable = f && (std::fgetc(f) != EOF || !std::ferror(f)); + const int err = errno; + if (f) { std::fclose(f); } + if (!readable) { throw std::runtime_error(format("%s: failed to open %s: %s\n", func, fname, std::strerror(err))); } + } + } + } + + // Save vector state to disk + auto save_state = [&](const std::vector & all_tensors) { + const std::string tmp = checkpoint_file + ".tmp"; + std::ofstream ofs(tmp, std::ios::binary | std::ios::trunc); + if (!ofs) { + LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (open error)\n", func, tmp.c_str()); + return; + } + ofs.write((const char *)& STATE_MAGIC, sizeof(STATE_MAGIC)); + ofs.write((const char *)& model_id, sizeof(model_id)); + const uint64_t n = all_tensors.size(); + ofs.write((const char *)& n, sizeof(n)); + for (const auto & tn : all_tensors) { + const std::string name = ggml_get_name(tn.w->tensor); + const auto len = (uint32_t)name.size(); + ofs.write((const char *)& len, sizeof(len)); + ofs.write(name.data(), len); + + const uint64_t sz = tn.candidates.size(); + ofs.write((const char *)& sz, sizeof(sz)); + ofs.write((const char *)& tn.choice, sizeof(tn.choice)); + ofs.write((const char *)& tn.min_bpw, sizeof(tn.min_bpw)); + ofs.write((const char *)& tn.max_bpw, sizeof(tn.max_bpw)); + const uint64_t ne = tn.n_elements; + ofs.write((const char *)& ne, sizeof(ne)); + + for (const auto & c : tn.candidates) { + const int32_t tp = c.type; + const uint64_t bt = c.bytes; + ofs.write((const char *)& tp, sizeof(tp)); + ofs.write((const char *)& c.bpw, sizeof(c.bpw)); + ofs.write((const char *)& bt, sizeof(bt)); + ofs.write((const char *)& c.error, sizeof(c.error)); + } + } + + const bool werr = ofs.fail() || ofs.bad(); + ofs.close(); + if (werr || ofs.fail() || ofs.bad()) { + std::remove(tmp.c_str()); + LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (write error)\n", func, tmp.c_str()); + return; + } + + std::remove(checkpoint_file.c_str()); + if (std::rename(tmp.c_str(), checkpoint_file.c_str()) != 0) { + LLAMA_LOG_WARN("\n\t%s: failed to save progress to %s (rename error), kept in %s\n", func, checkpoint_file.c_str(), tmp.c_str()); + return; + } + + LLAMA_LOG_INFO("\t%s: saved target progress for %zu tensors to %s\n", func, all_tensors.size(), checkpoint_file.c_str()); + }; + + // Load vector state from disk + auto load_state = [&]() -> std::unordered_map { + std::ifstream ifs(checkpoint_file, std::ios::binary); + if (!ifs) { return {}; } + + uint64_t magic = 0; + uint64_t id = 0; + ifs.read((char *)& magic, sizeof(magic)); + ifs.read((char *)& id, sizeof(id)); + if (id != model_id) { + LLAMA_LOG_WARN("%s: state file does not match this model, imatrix or pruned layers, ignoring\n", func); + return {}; + } + + if (magic != STATE_MAGIC) { + LLAMA_LOG_WARN("%s: invalid state file, ignoring\n", func); + return {}; + } + + std::unordered_map out; + uint64_t n = 0; + ifs.read((char *)& n, sizeof(n)); + for (uint64_t i = 0; i < n; ++i) { + if (!ifs.good()) { break; } + uint32_t len = 0; + ifs.read((char *)& len, sizeof(len)); + if (len >= GGML_MAX_NAME) { + LLAMA_LOG_WARN("%s: state file name length exceeds limits, ignoring\n", func); + return {}; + } + std::string name(len, '\0'); + ifs.read(name.data(), len); + + type_choice si; + uint64_t sz = 0; + ifs.read((char *)& sz, sizeof(sz)); + if (!ifs.good()) { break; } + if (sz == 0 || sz > std::size(quant_types)) { + LLAMA_LOG_WARN("%s: candidate count out of range, ignoring state file\n", func); + return {}; + } + ifs.read((char *)& si.choice, sizeof(si.choice)); + ifs.read((char *)& si.min_bpw, sizeof(si.min_bpw)); + ifs.read((char *)& si.max_bpw, sizeof(si.max_bpw)); + uint64_t ne = 0; + ifs.read((char *)& ne, sizeof(ne)); + si.n_elements = (size_t)ne; + + si.candidates.resize(sz); + for (auto & cd : si.candidates) { + if (!ifs.good()) { break; } + int32_t t = 0; + uint64_t b = 0; + ifs.read((char *)& t, sizeof(t)); + if (!ifs.good()) { break; } + if (std::find(std::begin(quant_types), std::end(quant_types), t) == std::end(quant_types)) { + LLAMA_LOG_WARN("%s: candidate type is not in the selection pool, ignoring state file\n", func); + return {}; + } + cd.type = (ggml_type)t; + ifs.read((char *)& cd.bpw, sizeof(cd.bpw)); + ifs.read((char *)& b, sizeof(b)); + cd.bytes = (size_t)b; + ifs.read((char *)& cd.error, sizeof(cd.error)); + } + + out.emplace(std::move(name), std::move(si)); + } + + if (!ifs.good()) { + LLAMA_LOG_WARN("%s: state file truncated or read error, ignoring\n", func); + return {}; + } + + LLAMA_LOG_INFO("\t%s: using %s (data for %zu tensors loaded)\n", func, checkpoint_file.c_str(), out.size()); + return out; + }; + + // Check for interruptions and try save progress + auto throw_if_aborted = [&](const std::vector & all_tensors) { + if (interrupted) { + if (qs.params->state_file) { + if (qs.has_ignored_types) { + LLAMA_LOG_WARN("\n\t%s: interrupted; state checkpoint is not written while --target-exclude is active\n", func); + } else { + LLAMA_LOG_INFO("\n\t%s: interrupted, saving progress for %zu tensors to %s\n", func, all_tensors.size(), checkpoint_file.c_str()); + save_state(all_tensors); + } + } else { + LLAMA_LOG_INFO("\n\t%s: interrupted\n", func); + } + + throw std::runtime_error("interrupted"); + } + }; + + // Quality metrics + struct quant_error { + double error = std::numeric_limits::infinity(); + double mse = 0.0; + double wce = 0.0; + }; + + // Pre-calculated stats for MSE + struct mse_cache { + std::vector row_sq_norm; + }; + + // Pre-calculated stats for WCE + struct wce_cache { + std::vector row_sq_norm; + }; + + // Determine optimization strategy + auto is_angle_sensitive = [](const std::string & name) -> bool { + return name.find("attn_q.weight") != std::string::npos || + name.find("attn_k.weight") != std::string::npos || + name.find("attn_qkv.weight") != std::string::npos || + name.find("attn_q_a.weight") != std::string::npos || + name.find("attn_q_b.weight") != std::string::npos; + }; + + // Tensors sensitive to distortion in dot-product/inner-product calculations (TurboQuant) + auto is_inner_product_sensitive = [](const std::string & name) -> bool { + // Query/Key and variants (fused, latent, and enc/dec) + if (name.find("attn_q") != std::string::npos || name.find("attn_k") != std::string::npos) { return true; } + // Attention Output and variants (standard, enc/dec, cross-attn) + if (name.find("attn_o") != std::string::npos) { return true; } + // Value and variants + if (name.find("attn_v") != std::string::npos) { return true; } + + return false; + }; + + // Estimate error for a given type using a sampled subset of rows + auto compute_quant_error = [&]( + const ggml_tensor * t, + const ggml_type quant_type, + const std::vector & f32_sample, + const std::vector & rows_sample, + const float * values_sample, + const float * activations_sample, + std::vector & quantized_buffer, + std::vector & dequantized_buffer, + const wce_cache * ref_wce = nullptr, + const mse_cache * ref_mse = nullptr, + const float * values_winsorized = nullptr + ) -> quant_error + { + const int64_t n_per_row = t->ne[0]; + const int64_t ne2 = t->ne[2] > 0 ? t->ne[2] : 1; + const size_t sample_elems = f32_sample.size(); + const size_t sample_rows = n_per_row > 0 ? sample_elems / (size_t)n_per_row : 0; + + quant_error qe; + if (sample_rows == 0) { + qe.error = 0.0; + return qe; + } + + const size_t row_sz = ggml_row_size(quant_type, n_per_row); + constexpr size_t SAFETY_PADDING = 256; + if (quantized_buffer.size() < row_sz + SAFETY_PADDING) { quantized_buffer.resize(row_sz + SAFETY_PADDING); } + if (dequantized_buffer.size() < (size_t)n_per_row) { dequantized_buffer.resize((size_t)n_per_row); } + + const ggml_type_traits * traits = ggml_get_type_traits(quant_type); + if (!traits || !traits->to_float) { return qe; } + + auto quant_dequant_row = [&](const float * src, float * dst, const float * v) { + ggml_quantize_chunk(quant_type, src, quantized_buffer.data(), 0, 1, n_per_row, v); + if (quant_type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)quantized_buffer.data(), dst, (int)n_per_row); } + else if (quant_type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)quantized_buffer.data(), dst, (int)n_per_row); } + else { traits->to_float(quantized_buffer.data(), dst, (int)n_per_row); } + }; + + const bool has_vals = values_sample != nullptr; + const bool has_acts = activations_sample != nullptr; + const bool use_wce = has_acts && has_vals && is_angle_sensitive(t->name); + const float * valw = values_winsorized ? values_winsorized : values_sample; + + // Sampled stats for MSE + std::vector local_row_sq_norm; + const std::vector * ptr_row_sq_norm = nullptr; + + // Setup reference stats pointers for MSE + if (!use_wce) { + if (ref_mse) { + ptr_row_sq_norm = & ref_mse->row_sq_norm; + } else { + local_row_sq_norm.reserve(sample_rows); + size_t off = 0; + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + const float * val = has_vals ? valw + s * n_per_row : nullptr; + const float * act = has_acts ? activations_sample + s * n_per_row : nullptr; + for (int64_t r = 0; r < rs; ++r) { + const float * x = f32_sample.data() + off; + double sum = 0.0; + double bias_sum = 0.0; + if (val && act) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double act_j = act[j]; + const double variance = std::max(0.0, (double)val[j] - act_j * act_j); + sum += variance * x[j] * x[j]; + bias_sum += act_j * x[j]; + } + sum += bias_sum * bias_sum; + } else if (val) { + for (int64_t j = 0; j < n_per_row; ++j) { sum += std::max(0.0f, val[j]) * x[j] * x[j]; } + } else { + for (int64_t j = 0; j < n_per_row; ++j) { sum += x[j] * x[j]; } + } + + local_row_sq_norm.push_back(sum); + off += (size_t)n_per_row; + } + } + + ptr_row_sq_norm = & local_row_sq_norm; + } + } + + // Helper for trimmed mean + auto trimmed_mean = [](std::vector & v) -> double { + const auto n = v.size(); + if (n == 0) { return 0.0; } + if (n < 100) { return std::accumulate(v.begin(), v.end(), 0.0) / (double)n; } + const auto k = (size_t)((double)n * 0.01); // trim 1% from each end + std::nth_element(v.begin(), v.begin() + k, v.end()); + std::nth_element(v.begin() + k, v.end() - k, v.end()); + return std::accumulate(v.begin() + k, v.end() - k, 0.0) / std::max(1.0, (double)(n - 2 * k)); + }; + + // Weighted Cosine Error (WCE) + if (use_wce) { + double total_cos_error = 0.0; + size_t off = 0; + size_t sample_idx = 0; + + const std::vector * cached_norm_x = ref_wce && !ref_wce->row_sq_norm.empty() ? & ref_wce->row_sq_norm : nullptr; + + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + if (rs == 0) { continue; } + + const float * v = values_sample + s * n_per_row; + const float * vw = valw + s * n_per_row; + double slice_sum = 0.0; + + for (int64_t r = 0; r < rs; ++r, ++sample_idx) { + const float * wx = f32_sample.data() + off; + float * wy = dequantized_buffer.data(); + quant_dequant_row(wx, wy, v); + + double dot = 0.0; + double ny = 0.0; + double nx = 0.0; + const bool calc_nx = !cached_norm_x; + + if (calc_nx) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, vw[j]); + const double xj = wx[j]; + const double yj = wy[j]; + const double yw = yj * w; + dot += xj * yw; + ny += yj * yw; + nx += xj * xj * w; + } + } else { + nx = (* cached_norm_x)[sample_idx]; + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, vw[j]); + const double yj = wy[j]; + const double yw = yj * w; + dot += (double) wx[j] * yw; + ny += yj * yw; + } + } + + // Cosine Distance + double cos_sim; + const double norm_prod = nx * ny; + + if (norm_prod <= EPSILON) { cos_sim = nx <= EPSILON && ny <= EPSILON ? 1.0 : 0.0; } + else { cos_sim = dot / std::sqrt(norm_prod); } + + if (cos_sim > 1.0) { cos_sim = 1.0; } + else if (cos_sim < -1.0) { cos_sim = -1.0; } + + slice_sum += 1.0 - cos_sim; + off += (size_t) n_per_row; + } + + const double nrows = t->ne[1]; + total_cos_error += slice_sum / (double)rs * (double)nrows; + } + + qe.wce = total_cos_error; + qe.error = qe.wce; + return qe; + } + + // Expected Output Error MSE (EOE-MSE) + size_t off = 0; + size_t row_idx = 0; + double total_wmse = 0.0; + + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + if (rs == 0) { continue; } + + const float * val = has_vals ? values_sample + s * n_per_row : nullptr; + const float * mval = has_vals ? valw + s * n_per_row : nullptr; + const float * act = has_acts ? activations_sample + s * n_per_row : nullptr; + + std::vector slice_mse_norm; + slice_mse_norm.reserve(rs); + + for (int64_t r = 0; r < rs; ++r, ++row_idx) { + const float * x = f32_sample.data() + off; + float * y = dequantized_buffer.data(); + quant_dequant_row(x, y, val); + + double w_err = 0.0; + double bias_num = 0.0; + + if (mval && act) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, mval[j]); + const double a = act[j]; + const double e = (double)y[j] - (double)x[j]; + w_err += w * e * e; + bias_num += a * e; + } + w_err += bias_num * bias_num; + } else if (mval) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = std::max(0.0f, mval[j]); + const double e = (double)y[j] - (double)x[j]; + w_err += w * e * e; + } + } else { + for (int64_t j = 0; j < n_per_row; ++j) { + const double e = (double)y[j] - (double)x[j]; + w_err += e * e; + } + } + + const double rsn = (* ptr_row_sq_norm)[row_idx]; + const double m_norm = rsn > EPSILON ? w_err / rsn : 0.0; + slice_mse_norm.push_back(std::isfinite(m_norm) ? m_norm : INFINITE); + + off += (size_t)n_per_row; + } + + const int64_t nrows = t->ne[1]; + const double slice_mean_mse = trimmed_mean(slice_mse_norm) * (double)nrows; + + total_wmse += slice_mean_mse; + } + + qe.mse = total_wmse; + qe.error = total_wmse; + return qe; + }; + + std::unordered_map bpw_data; + if (qs.params->state_file && !checkpoint_file.empty()) { bpw_data = load_state(); } + + auto has_side_data = [&](const auto * m, const std::string & name, const int64_t n2, const int64_t n_per_row) { + if (!m) { return false; } + auto it = m->find(name); + if (it == m->end()) { return false; } + const size_t req = (size_t) n2 * (size_t) n_per_row; + const size_t sz = it->second.size(); + return sz == req || sz == (size_t) n_per_row; + }; + + // Look up stats used by CNIF + enum { ENERGY, H_NORM, L2_DIST, COSSIM, PCC, N_STATS }; + const char * stat_names[N_STATS] = { "sum_sq", "h_norm", "l2_dist", "cossim", "pearson" }; + size_t stat_pos[N_STATS] = {}; + size_t min_stats = 0; + bool use_cnif = statistics_data && !statistics_data->empty(); + for (int i = 0; use_cnif && i < N_STATS; ++i) { + const size_t n = stats_schema ? stats_schema->size() : 0; + size_t p = 0; + while (p < n && (* stats_schema)[p] != stat_names[i]) { ++p; } + if (p == n) { + LLAMA_LOG_WARN("%s: statistics have no %s metric, skipping CNIF; model quality may be compromised\n", func, stat_names[i]); + use_cnif = false; + } + stat_pos[i] = p; + min_stats = std::max(min_stats, p + 1); + } + + // Precompute the Centered‑Normalized Importance Factor (CNIF) + std::unordered_map cnif_scores; + if (use_cnif) { + struct tensor_score { + std::string name; + float score = 0.0f; + }; + + auto corr_error = [](float x) { + if (!std::isfinite(x)) { return 0.0f; } + return 1.0f - std::abs(std::clamp(x, -1.0f, 1.0f)); + }; + + auto sort_scores = [](std::vector & scores) { + std::sort(scores.begin(), scores.end(), [](const tensor_score & a, const tensor_score & b) { + return a.score < b.score || (a.score == b.score && a.name < b.name); + }); + }; + + auto median = [](const auto & values, auto get_value) { + const size_t mid = values.size() / 2; + if (values.size() % 2 != 0) { return get_value(values[mid]); } + return 0.5f * (get_value(values[mid - 1]) + get_value(values[mid])); + }; + + auto rank = [&](std::vector & scores, const float beta) { + if (scores.empty()) { return; } + + sort_scores(scores); + + if (scores.size() == 1) { + cnif_scores[scores[0].name] = 1.0f; + return; + } + + for (size_t i = 0; i < scores.size();) { + size_t j = i + 1; + while (j < scores.size() && std::abs(scores[j].score - scores[i].score) <= 1e-6f) { ++j; } + + const float p = 0.5f * (float)(i + j - 1) / (float)(scores.size() - 1); + const float scale = std::exp(beta * (2.0f * p - 1.0f)); + for (size_t k = i; k < j; ++k) { cnif_scores[scores[k].name] = scale; } + i = j; + } + }; + + auto cnif = [&](std::vector & scores, const float beta) { + constexpr size_t min_scores = 8; + constexpr float eps = 1e-6f; + constexpr float mad_factor = 1.4826f; // Median Absolute Deviation estimator for normal distributions + + if (scores.size() < min_scores) { + rank(scores, beta); + return; + } + + sort_scores(scores); + + const float med = median(scores, [](const tensor_score & s) { return s.score; }); + std::vector deviations; + deviations.reserve(scores.size()); + for (const auto & score : scores) { deviations.push_back(std::abs(score.score - med)); } + + std::sort(deviations.begin(), deviations.end()); + const float mad = median(deviations, [](float x) { return x; }); + if (mad <= eps) { + rank(scores, beta); + return; + } + + const float inv_scale = 1.0f / (mad_factor * mad + eps); + for (const auto & score : scores) { + const float z = std::clamp((score.score - med) * inv_scale, -4.0f, 4.0f); + cnif_scores[score.name] = std::exp(beta * std::tanh(0.8f * z)); + } + }; + + std::vector mse_scores; + std::vector wce_scores; + mse_scores.reserve(tensors.size()); + wce_scores.reserve(tensors.size()); + cnif_scores.reserve(tensors.size()); + + for (const auto * tw : tensors) { + const ggml_tensor * tensor = tw->tensor; + if (!can_quantize(tensor)) { continue; } + + const std::string name = remap_imatrix(ggml_get_name(tensor), mapped); + auto it = statistics_data->find(name); + if (it == statistics_data->end() || it->second.size() < min_stats) { continue; } + + // Heads have no previous-layer counterpart so they stay outside the pool at cnif = 1.0 + if (tensor_name_match_token_embd(ggml_get_name(tensor)) || tensor_name_match_output_weight(ggml_get_name(tensor))) { continue; } + + const auto & ts = it->second; + const float h_norm = std::isfinite(ts[stat_pos[H_NORM]]) ? std::clamp(ts[stat_pos[H_NORM]], 0.0f, 100.0f) : 100.0f; + const float concentration = 1.0f - h_norm / 100.0f; + const float energy = std::isfinite(ts[stat_pos[ENERGY]]) ? std::max(0.0f, ts[stat_pos[ENERGY]]) : 0.0f; + const float l2_dist = std::isfinite(ts[stat_pos[L2_DIST]]) ? std::max(0.0f, ts[stat_pos[L2_DIST]]) : 0.0f; + const float rel_l2 = l2_dist / (std::sqrt(energy) + EPSILON); + const float density = rel_l2 / (1.0f + rel_l2); + const float fragility = 0.5f * (corr_error(ts[stat_pos[COSSIM]]) + corr_error(ts[stat_pos[PCC]])); + + const int64_t n_per_row = tensor->ne[0]; + const int64_t ne2 = tensor->ne[2] > 0 ? tensor->ne[2] : 1; + const bool has_vals = has_side_data(values_data, name, ne2, n_per_row); + const bool has_acts = has_side_data(activations_data, name, ne2, n_per_row); + const bool use_wce = has_vals && has_acts && is_angle_sensitive(name); + + // parameters tuned for better results at low bitrates (<= 4.5 bits) + const float score = use_wce + ? 0.75f * concentration + 0.15f * density + 0.10f * fragility + : 0.40f * concentration + 0.35f * density + 0.25f * fragility; + + auto & scores = use_wce ? wce_scores : mse_scores; + scores.push_back({ name, score }); + } + + cnif(mse_scores, 0.40f); + cnif(wce_scores, 0.25f); + } + + // Outlier mitigation (simulate TurboQuant rotation) + auto outlier_smoothing = [&](const std::vector& src, std::vector& dst, const int64_t n_rows, const int64_t len) { + dst.resize(src.size()); + for (int64_t r = 0; r < n_rows; ++r) { + const float* src_row = src.data() + r * len; + float* dst_row = dst.data() + r * len; + + // Fast variance estimation + double mean_d = 0.0; + double M2 = 0.0; + for (int64_t i = 0; i < len; ++i) { + double delta = src_row[i] - mean_d; + mean_d += delta / (i + 1); + M2 += delta * (src_row[i] - mean_d); + } + + const float mean = mean_d; + float variance = M2 / len; + const float std_dev = std::sqrt(std::max(0.0f, variance)); + + // Clip at 4 standard deviations to simulate the effect of rotation spreading the outlier energy + float clip_val = 4.0f * std_dev; + + if (clip_val > 1e-4f) { + for (int64_t i = 0; i < len; ++i) { dst_row[i] = std::clamp(src_row[i], mean - clip_val, mean + clip_val); } + } else { + std::memcpy(dst_row, src_row, len * sizeof(float)); + } + } + }; + + // HMT Randomized SVD condition number estimator: kappa = sigma 1 / sigma 20. See https://arxiv.org/abs/0909.4061 + auto randomized_svd_condition_number = [&](const std::vector & f32_sample, const int64_t n_per_row, const int64_t total_rows_sampled) -> float { + constexpr int64_t target_rank = 25; + constexpr int64_t k = 20; // 20th singular value for condition number estimation + constexpr float eps_norm = 1e-8f; + constexpr float eps_eig = EPSILON; + constexpr int jacobi_sweeps = 20; + if (total_rows_sampled < 1 || n_per_row < 1) { return INFINITE; } + + const int64_t m = total_rows_sampled; + const int64_t n = n_per_row; + + // Jacobi eigenvalue decomposition for symmetric matrix + auto jacobi_diag = [&](std::vector & A, const int64_t dim, const int max_sweeps) { + for (int sweep = 0; sweep < max_sweeps; ++sweep) { + bool converged = true; + for (int64_t p = 0; p < dim - 1; ++p) { + for (int64_t q = p + 1; q < dim; ++q) { + const float app = A[p * dim + p]; + const float aqq = A[q * dim + q]; + const float apq = A[p * dim + q]; + if (std::abs(apq) <= eps_eig) { continue; } + converged = false; + + const float tau = (aqq - app) / (2.0f * apq); + const float t = tau >= 0.0f + ? 1.0f / (tau + std::sqrt(1.0f + tau * tau)) + : -1.0f / (-tau + std::sqrt(1.0f + tau * tau)); + const float c = 1.0f / std::sqrt(1.0f + t * t); + const float s = c * t; + + A[p * dim + p] = app - t * apq; + A[q * dim + q] = aqq + t * apq; + A[p * dim + q] = 0.0f; + A[q * dim + p] = 0.0f; + + for (int64_t r = 0; r < dim; ++r) { + if (r == p || r == q) { continue; } + const float arp = A[r * dim + p]; + const float arq = A[r * dim + q]; + A[r * dim + p] = c * arp - s * arq; + A[p * dim + r] = A[r * dim + p]; + A[r * dim + q] = s * arp + c * arq; + A[q * dim + r] = A[r * dim + q]; + } + } + } + + if (converged) { break; } + } + }; + + auto matmul_a = [&]( + const std::vector & A, const int64_t rows_a, + const int64_t cols_a, const std::vector & B, + const int64_t cols_b, std::vector & C + ) + { + C.assign((size_t)rows_a * (size_t)cols_b, 0.0f); + for (int64_t i = 0; i < rows_a; ++i) { + const size_t i_a = (size_t)i * (size_t)cols_a; + const size_t i_c = (size_t)i * (size_t)cols_b; + for (int64_t l = 0; l < cols_a; ++l) { + const float aik = A[i_a + (size_t)l]; + if (aik == 0.0f) { continue; } + const size_t k_b = (size_t)l * (size_t)cols_b; + for (int64_t j = 0; j < cols_b; ++j) { + C[i_c + (size_t)j] += aik * B[k_b + (size_t)j]; + } + } + } + }; + + // C = A^T * B (A is rows_a x cols_a, B is rows_a x cols_b, C is cols_a x cols_b) + auto matmul_b = [&]( + const std::vector & A, + const int64_t rows_a, + const int64_t cols_a, + const std::vector & B, const int64_t cols_b, + std::vector & C + ) + { + C.assign((size_t)cols_a * (size_t)cols_b, 0.0f); + for (int64_t i = 0; i < cols_a; ++i) { + const size_t i_c = (size_t)i * (size_t)cols_b; + for (int64_t l = 0; l < rows_a; ++l) { + const float aki = A[(size_t)l * (size_t)cols_a + (size_t)i]; + if (aki == 0.0f) { continue; } + const size_t k_b = (size_t)l * (size_t)cols_b; + for (int64_t j = 0; j < cols_b; ++j) { + C[i_c + (size_t)j] += aki * B[k_b + (size_t)j]; + } + } + } + }; + + // Modified Gram-Schmidt QR Decomposition. Q gets orthonormal columns from Y (Y is rows x cols) + auto mgs_qr = [&]( + const std::vector & Y, + const int64_t rows, const int64_t cols, + std::vector & Q + ) + { + Q.assign((size_t)rows * (size_t)cols, 0.0f); + std::vector v(rows); + for (int64_t j = 0; j < cols; ++j) { + for (int64_t i = 0; i < rows; ++i) { + v[i] = Y[(size_t)i * (size_t)cols + (size_t)j]; + } + + for (int64_t b = 0; b < j; ++b) { + double dot = 0.0; + for (int64_t i = 0; i < rows; ++i) { + dot += (double)v[i] * (double)Q[(size_t)i * (size_t)cols + (size_t)b]; + } + for (int64_t i = 0; i < rows; ++i) { + v[i] -= (float)dot * Q[(size_t)i * (size_t)cols + (size_t)b]; + } + } + + double norm_sq = 0.0; + for (int64_t i = 0; i < rows; ++i) { + norm_sq += (double)v[i] * (double)v[i]; + } + + const float norm = std::sqrt((float)norm_sq); + if (norm > eps_norm) { + const float inv = 1.0f / norm; + for (int64_t i = 0; i < rows; ++i) { + Q[(size_t)i * (size_t)cols + (size_t)j] = v[i] * inv; + } + } + } + }; + + // Filter and row-normalize valid rows (exclude NaN/Inf and near zero norm rows) + std::vector norm_matrix; + norm_matrix.reserve((size_t)m * (size_t)n); + for (int64_t r = 0; r < m; ++r) { + const float * row = f32_sample.data() + r * n; + double l2_sq = 0.0; + for (int64_t j = 0; j < n; ++j) { + const float val = row[j]; + if (!std::isfinite(val)) { l2_sq = -1.0; break; } + l2_sq += (double)val * (double)val; + } + + if (l2_sq < 0.0) { continue; } + const float l2 = std::sqrt((float)l2_sq); + if (l2 <= eps_norm) { continue; } + const float inv_l2 = 1.0f / l2; + const size_t cur = norm_matrix.size(); + norm_matrix.resize(cur + (size_t)n); + float * dst = norm_matrix.data() + cur; + for (int64_t j = 0; j < n; ++j) { dst[j] = row[j] * inv_l2; } + } + + const int64_t valid_m = (int64_t)norm_matrix.size() / n; + if (valid_m < 2) { return INFINITE; } + const bool hmt_direct = valid_m >= target_rank; + const bool hmt_transpose = !hmt_direct && n >= target_rank; + + // Deterministic random Gaussian projection using Golden Ratio * Random Scrambling Hashing + std::mt19937 rng((uint64_t)(n_per_row * 0x9E3779B97F4A7C15ULL + valid_m * 0xBF58476D1CE4E5B9ULL)); + std::normal_distribution normal(0.0f, 1.0f); + + // Estimate the condition number (kappa) + auto condition_number = [&](const std::vector & eigenvalues) -> float { + if ((int64_t)eigenvalues.size() < k) { return INFINITE; } + const float sigma_max = std::sqrt(std::max(0.0f, eigenvalues[0])); + const float sigma_min = std::sqrt(std::max(0.0f, eigenvalues[k - 1])); + if (sigma_min <= eps_eig) { return INFINITE; } + + return sigma_max / sigma_min; + }; + + if (hmt_direct) { + // HMT on A (valid_m x n) with q=1 power iteration + std::vector Omega((size_t)n * (size_t)target_rank); + for (auto & v : Omega) { v = normal(rng); } + + std::vector Y0; + std::vector Z; + std::vector Y1; + std::vector Q; + std::vector B; + std::vector C; + matmul_a(norm_matrix, valid_m, n, Omega, target_rank, Y0); // Y0 = A * Omega + matmul_b(norm_matrix, valid_m, n, Y0, target_rank, Z); // Z = A^T * Y0 + matmul_a(norm_matrix, valid_m, n, Z, target_rank, Y1); // Y1 = A * Z + mgs_qr(Y1, valid_m, target_rank, Q); + matmul_b(Q, valid_m, target_rank, norm_matrix, n, B); // B = Q^T * A + + // C = B * B^T (target_rank x target_rank) + C.assign((size_t)target_rank * (size_t)target_rank, 0.0f); + for (int64_t i = 0; i < target_rank; ++i) { + for (int64_t j = 0; j < target_rank; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < n; ++l) { + sum += (double)B[(size_t)i * (size_t)n + (size_t)l] * (double)B[(size_t)j * (size_t)n + (size_t)l]; + } + + C[(size_t)i * (size_t)target_rank + (size_t)j] = (float)sum; + } + } + + jacobi_diag(C, target_rank, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(target_rank); + for (int64_t i = 0; i < target_rank; ++i) { eigenvalues.push_back(C[i * target_rank + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + } + + if (hmt_transpose) { + // HMT on A^T (n x valid_m) with q=1 power iteration + std::vector Omega((size_t)valid_m * (size_t)target_rank); + for (auto & v : Omega) { v = normal(rng); } + + std::vector Y0; + std::vector Z; + std::vector Y1; + std::vector Q; + std::vector B; + std::vector C; + matmul_b(norm_matrix, valid_m, n, Omega, target_rank, Y0); // Y0 = A^T * Omega + matmul_a(norm_matrix, valid_m, n, Y0, target_rank, Z); // Z = A * Y0 + matmul_b(norm_matrix, valid_m, n, Z, target_rank, Y1); // Y1 = A^T * Z + mgs_qr(Y1, n, target_rank, Q); + + // B = Q^T * A^T (target_rank x valid_m) + B.assign((size_t)target_rank * (size_t)valid_m, 0.0f); + for (int64_t j = 0; j < target_rank; ++j) { + for (int64_t k = 0; k < valid_m; ++k) { + double sum = 0.0; + for (int64_t i = 0; i < n; ++i) { + sum += (double)Q[(size_t)i * (size_t)target_rank + (size_t)j] * (double)norm_matrix[(size_t)k * (size_t)n + (size_t)i]; + } + + B[(size_t)j * (size_t)valid_m + (size_t)k] = (float)sum; + } + } + + // C = B * B^T (target_rank x target_rank) + C.assign((size_t)target_rank * (size_t)target_rank, 0.0f); + for (int64_t i = 0; i < target_rank; ++i) { + for (int64_t j = 0; j < target_rank; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < valid_m; ++l) { + sum += (double)B[(size_t)i * (size_t)valid_m + (size_t)l] * (double)B[(size_t)j * (size_t)valid_m + (size_t)l]; + } + + C[(size_t)i * (size_t)target_rank + (size_t)j] = (float)sum; + } + } + + jacobi_diag(C, target_rank, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(target_rank); + for (int64_t i = 0; i < target_rank; ++i) { eigenvalues.push_back(C[i * target_rank + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + } + + // Fallback: full thin SVD via Gram matrix of smaller dimension + Jacobi + const bool gram_rows = valid_m <= n; + if (gram_rows) { + const int64_t gram_dim = valid_m; + std::vector G((size_t)gram_dim * (size_t)gram_dim, 0.0f); + for (int64_t i = 0; i < gram_dim; ++i) { + for (int64_t j = i; j < gram_dim; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < n; ++l) { + sum += (double)norm_matrix[(size_t)i * (size_t)n + (size_t)l] * (double)norm_matrix[(size_t)j * (size_t)n + (size_t)l]; + } + + G[(size_t)i * (size_t)gram_dim + (size_t)j] = (float)sum; + G[(size_t)j * (size_t)gram_dim + (size_t)i] = (float)sum; + } + } + + jacobi_diag(G, gram_dim, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(gram_dim); + for (int64_t i = 0; i < gram_dim; ++i) { eigenvalues.push_back(G[i * gram_dim + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + } + + // G = A^T * A (n x n) + const int64_t gram_dim = n; + std::vector G((size_t)gram_dim * (size_t)gram_dim, 0.0f); + for (int64_t i = 0; i < gram_dim; ++i) { + for (int64_t j = i; j < gram_dim; ++j) { + double sum = 0.0; + for (int64_t l = 0; l < valid_m; ++l) { + sum += (double)norm_matrix[(size_t)l * (size_t)n + (size_t)i] * (double)norm_matrix[(size_t)l * (size_t)n + (size_t)j]; + } + + G[(size_t)i * (size_t)gram_dim + (size_t)j] = (float)sum; + G[(size_t)j * (size_t)gram_dim + (size_t)i] = (float)sum; + } + } + + jacobi_diag(G, gram_dim, jacobi_sweeps); + std::vector eigenvalues; + eigenvalues.reserve(gram_dim); + for (int64_t i = 0; i < gram_dim; ++i) { eigenvalues.push_back(G[i * gram_dim + i]); } + std::sort(eigenvalues.begin(), eigenvalues.end(), std::greater()); + + return condition_number(eigenvalues); + }; + + // Map [1, ∞) to [1, M]; alpha controls mapping aggressiveness towards M + auto squash_kappa = [](float kappa) -> float { + constexpr float M = 5.0f; + constexpr float alpha = 0.15f; + if (!std::isfinite(kappa)) { return M; } + + return 1.0f + (M - 1.0f) * std::tanh(alpha * std::log(kappa)); + }; + + // Parallelize tensor processing (courtesy of https://github.com/ddh0) + const int n_workers = std::max(1, std::min(nthread, (int) tensors.size())); + const size_t max_buf_worker = std::max(1, (qs.params->max_buf_size ? qs.params->max_buf_size : LLAMA_QUANT_MAX_BUF_SIZE) / n_workers); + + auto process_tensor = [&]( + const llama_model_loader::llama_tensor_weight * tw, + std::vector> & thread_local_buffer, + std::vector & f32_sample, + std::vector & smoothed_sample, + std::vector & val_cache, + std::vector & act_cache, + std::mutex & loader_mutex, + std::mutex & log_mutex + ) -> std::optional + { + ggml_tensor * tensor = tw->tensor; + struct tensor_guard { + ggml_tensor * t; + void * orig; + ~tensor_guard() { t->data = orig; } + } guard{tensor, tensor->data}; + + const std::string name = ggml_get_name(tensor); + if (poll_interrupt()) { return std::nullopt; } + + const std::string remapped_name = remap_imatrix(name, mapped); + + // Check cache + if (auto tn = bpw_data.find(name); tn != bpw_data.end()) { + type_choice tc; + tc.w = tw; + tc.candidates = tn->second.candidates; + tc.choice = tn->second.choice; + tc.min_bpw = tn->second.min_bpw; + tc.max_bpw = tn->second.max_bpw; + tc.n_elements = tn->second.n_elements ? tn->second.n_elements : (size_t)ggml_nelements(tensor); + // remove ignored types + if (qs.has_ignored_types) { + tc.candidates.erase(std::remove_if(tc.candidates.begin(), tc.candidates.end(), + [&](const type_scores & c) { return c.type >= 0 && c.type < GGML_TYPE_COUNT && qs.ignored_types[c.type]; }), + tc.candidates.end()); + + if (tc.candidates.empty()) { + // locked tensors are exempt + const bool is_locked = locked_tensors && locked_tensors->find(name) != locked_tensors->end(); + if (!is_locked) { + throw std::runtime_error(format("%s: tensor '%s' has %zu quant type candidates left after --target-exclude\n", func, name.c_str(), tc.candidates.size())); + } + + type_scores fb; + fb.type = tensor->type; + fb.bytes = ggml_nbytes(tensor); + fb.bpw = fb.bytes * 8.0f / tc.n_elements; + tc.candidates.push_back(fb); + } + + tc.choice = 0; + } + + return tc; + } + + { + std::lock_guard lock(log_mutex); + LLAMA_LOG_INFO("\t%s: - processing tensor %45s \t(%12" PRId64 " elements)\n", func, name.c_str(), ggml_nelements(tensor)); + } + + const size_t tensor_nbytes = ggml_nbytes(tensor); + const size_t row_nbytes = ggml_row_size(tensor->type, tensor->ne[0]); + const bool stream_rows = !ml.use_mmap && tensor_nbytes > max_buf_worker; + + if (!stream_rows) { + if (!ml.use_mmap && thread_local_buffer.size() < tensor_nbytes) { thread_local_buffer.resize(tensor_nbytes); } + std::lock_guard lock(loader_mutex); + tensor->data = const_cast(ml.load_data_range(*tw, 0, tensor_nbytes, thread_local_buffer.data())); + } else if (thread_local_buffer.size() < row_nbytes) { + thread_local_buffer.resize(row_nbytes); + } + + auto load_row = [&](const int64_t slice, const int64_t row) -> const uint8_t * { + const size_t offs = ((size_t) slice*tensor->ne[1] + row) * row_nbytes; + if (!stream_rows) { return (const uint8_t *) tensor->data + offs; } + std::lock_guard lock(loader_mutex); + return (const uint8_t *) ml.load_data_range(*tw, offs, row_nbytes, thread_local_buffer.data()); + }; + + // Sampling + const int64_t n_per_row = tensor->ne[0]; + const int64_t nrows_total = tensor->ne[1]; + const int64_t ne2 = tensor->ne[2] > 0 ? tensor->ne[2] : 1; + + // Compute rows based on tensor shape and slice count + auto sample_count = [&](const int64_t n, const int64_t rows, const int64_t n2, const bool has_acts) { + constexpr double k_scale = 1.0; + const double tensor_budget = (has_acts ? 1.0 : 0.5) * k_scale * 1024.0 * 1024.0; + const double scale = std::clamp(std::sqrt(std::max(1.0, (double)rows) / 4096.0), 0.5, 2.0); // more rows for large tensors + const double slice_budget = tensor_budget * scale / std::max(1, n2); + const int64_t min_r = (has_acts ? 512 : 256) * (int64_t)k_scale; + const int64_t max_r = 4096 * (int64_t)k_scale; + int64_t tr = std::llround(slice_budget / std::max(1, n)); + tr = std::max(min_r, std::min(tr, std::min(rows, max_r))); + if (rows <= min_r * 2) { tr = rows; } + return tr; + }; + + const int64_t rows_to_sample = sample_count(n_per_row, nrows_total, ne2, activations_data != nullptr); + f32_sample.clear(); + f32_sample.reserve((size_t)ne2 * (size_t)std::min(nrows_total, rows_to_sample) * (size_t)n_per_row); + std::vector rows_sample(ne2, 0); + + // Populate f32_sample + { + const ggml_type src_type = tensor->type; + const ggml_type_traits * traits = ggml_get_type_traits(src_type); + + for (int64_t slice = 0; slice < ne2; ++slice) { + std::mt19937 rng(djb2_hash((const uint8_t*)name.data(), name.size()) ^ HASH_MAGIC ^ slice); + const int64_t limit = std::max(1, std::min(nrows_total, rows_to_sample)); + const double stride = (double)nrows_total / limit; + int64_t offset = stride > 1.0 ? std::uniform_int_distribution(0, (int64_t)stride - 1)(rng) : 0; + + int64_t count = 0; + for (int64_t i = 0; i < limit; ++i) { + int64_t r = offset + std::llround(i * stride); + if (r >= nrows_total) { break; } + + const uint8_t * src = load_row(slice, r); + size_t cur_sz = f32_sample.size(); + f32_sample.resize(cur_sz + n_per_row); + float * dst = f32_sample.data() + cur_sz; + + if (src_type == GGML_TYPE_F32) { std::memcpy(dst, src, n_per_row * sizeof(float)); } + else if (src_type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t*)src, dst, (int)n_per_row); } + else if (src_type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t*)src, dst, (int)n_per_row); } + else if (traits && traits->to_float) { traits->to_float(src, dst, (int)n_per_row); } + else { throw std::runtime_error(format("unsupported source type %s for sampling", ggml_type_name(src_type))); } + + ++count; + } + + rows_sample[slice] = count; + } + } + + smoothed_sample.clear(); + bool is_outlier_heavy = remapped_name.find("ffn_down") != std::string::npos; + if (is_outlier_heavy) { outlier_smoothing(f32_sample, smoothed_sample, rows_to_sample * ne2, n_per_row); } + + // Prepare side data + auto get_side_data = [&](const auto * m) { + if (!m) { return std::pair{nullptr, 0}; } + auto it = m->find(remapped_name); + return it != m->end() ? std::pair{it->second.data(), it->second.size()} : std::pair{nullptr, 0}; + }; + + auto [val_ptr, val_sz] = get_side_data(values_data); + auto [act_ptr, act_sz] = get_side_data(activations_data); + + // Cache WCE stats per tensor + const float * val_vec_ptr = nullptr; + const float * act_vec_ptr = nullptr; + + auto prepare_broadcast = [&](const float* src, size_t sz, std::vector& storage, const float*& out_ptr) { + if (!src) { + out_ptr = nullptr; + return; + } + size_t req = (size_t)ne2 * n_per_row; + if (sz == req) { out_ptr = src; } + else if (sz == (size_t)n_per_row) { + storage.resize(req); + for (int s = 0; s < ne2; ++s) { std::memcpy(storage.data() + s * n_per_row, src, n_per_row * sizeof(float)); } + out_ptr = storage.data(); + } else { + std::lock_guard lock(log_mutex); + out_ptr = nullptr; + LLAMA_LOG_WARN("%s: side data mismatch for %s\n", func, name.c_str()); + } + }; + + prepare_broadcast(val_ptr, val_sz, val_cache, val_vec_ptr); + prepare_broadcast(act_ptr, act_sz, act_cache, act_vec_ptr); + + // Cap (winsorize) each row-slice at exp(med + 4 * 1.4826 * mad) of ln(val) to reduce noise and prevent skewness + // Activation-side equivalent of the ±4 sigma weight clip in outlier_smoothing + std::vector val_metric; + const float * ptr_val_metric = nullptr; + if (val_vec_ptr) { + val_metric.assign(val_vec_ptr, val_vec_ptr + (size_t)ne2 * n_per_row); + std::vector scratch; + for (int64_t s = 0; s < ne2; ++s) { + const float * vrow = val_vec_ptr + s * n_per_row; + scratch.clear(); + for (int64_t j = 0; j < n_per_row; ++j) { + const float v = vrow[j]; + if (v > 0.0f) { scratch.push_back(std::log(v)); } + } + + if (scratch.size() < 8 || scratch.size() < (size_t)n_per_row / 2) { continue; } // too few positive entries; leave untouched + auto mid = scratch.begin() + scratch.size() / 2; + std::nth_element(scratch.begin(), mid, scratch.end()); + const float med = * mid; + for (auto & d : scratch) { d = std::fabs(d - med); } + std::nth_element(scratch.begin(), mid, scratch.end()); + const float mad = * mid; + if (mad <= 1e-6f * std::max(1.0f, std::fabs(med))) { continue; } // abnormal row stats: leave untouched + const float cap = std::exp(med + 4.0f * 1.4826f * mad); + float * dst = val_metric.data() + s * n_per_row; + float row_max = -INFINITY; + for (int64_t j = 0; j < n_per_row; ++j) { + row_max = std::max(row_max, dst[j]); + dst[j] = std::min(dst[j], cap); + } + } + + ptr_val_metric = val_metric.data(); + } + + const bool use_wce = val_vec_ptr && act_vec_ptr && is_angle_sensitive(remapped_name); + + // Precompute WCE reference stats + wce_cache ref_wce; + mse_cache ref_mse; + size_t total_rows_sampled = 0; + for (int64_t r : rows_sample) { total_rows_sampled += r; } + + if (use_wce) { + ref_wce.row_sq_norm.reserve(total_rows_sampled); + size_t off = 0; + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + if (rs == 0) { continue; } + const float * v = ptr_val_metric + s * n_per_row; + for (int64_t r = 0; r < rs; ++r) { + const float * wx = f32_sample.data() + off; + double norm_x = 0.0; + for (int64_t j = 0; j < n_per_row; ++j) { + const double w = v ? std::max(0.0f, v[j]) : 1.0; + norm_x += (double)wx[j] * wx[j] * w; + } + ref_wce.row_sq_norm.push_back(norm_x); + off += n_per_row; + } + } + } else { + // Precompute MSE reference stats + ref_mse.row_sq_norm.reserve(total_rows_sampled); + const bool has_acts = act_vec_ptr != nullptr; + const bool has_vals = val_vec_ptr != nullptr; + + size_t off = 0; + for (int64_t s = 0; s < ne2; ++s) { + const int64_t rs = rows_sample[s]; + const float * val = has_vals ? ptr_val_metric + s * n_per_row : nullptr; + const float * act = has_acts ? act_vec_ptr + s * n_per_row : nullptr; + for (int64_t r = 0; r < rs; ++r) { + const float * x = f32_sample.data() + off; + double sum = 0.0; + double bias_sum = 0.0; + if (val && act) { + for (int64_t j = 0; j < n_per_row; ++j) { + const double act_j = act[j]; + const double variance = std::max(0.0, (double)val[j] - act_j * act_j); + sum += variance * x[j] * x[j]; + bias_sum += act_j * x[j]; + } + sum += bias_sum * bias_sum; + } else if (val) { + for (int64_t j = 0; j < n_per_row; ++j) { + sum += std::max(0.0f, val[j]) * x[j] * x[j]; + } + } else { + for (int64_t j = 0; j < n_per_row; ++j) { sum += x[j] * x[j]; } + } + + ref_mse.row_sq_norm.push_back(sum); + off += (size_t)n_per_row; + } + } + } + + float kappa_raw = std::numeric_limits::quiet_NaN(); + float kappa_factor = 1.0f; + if (statistics_data && !statistics_data->empty()) { + kappa_raw = randomized_svd_condition_number(f32_sample, n_per_row, (int64_t)total_rows_sampled); + kappa_factor = squash_kappa(kappa_raw); + } + + // Build candidates + std::vector valid_types; + valid_types.reserve(std::size(quant_types)); + size_t max_row_sz = 0; + const bool valid_matrix = val_vec_ptr != nullptr; + + for (auto t : quant_types) { + if (is_iq(t) && !valid_matrix) { continue; } + if (qs.ignored_types[t]) { continue; } + ggml_type compat = make_compatible(tensor, t); + if (qs.ignored_types[compat]) { continue; } + if (!is_compatible(tensor, compat)) { continue; } + valid_types.push_back(compat); + max_row_sz = std::max(max_row_sz, ggml_row_size(compat, n_per_row)); + } + + std::sort(valid_types.begin(), valid_types.end()); + valid_types.erase(std::unique(valid_types.begin(), valid_types.end()), valid_types.end()); + + // Evaluate candidates + std::vector evaluations; + evaluations.reserve(valid_types.size()); + std::vector q_buf; + std::vector dq_buf; + if (total_rows_sampled > 0 && max_row_sz > 0) { + q_buf.reserve(max_row_sz + 256); // safety padding + dq_buf.reserve(n_per_row); + } + + float cnif_score = 1.0f; + if (auto it = cnif_scores.find(remapped_name); it != cnif_scores.end()) { cnif_score = it->second; } + const float scaling_factor = cnif_score * kappa_factor; + const bool ip_sensitive = is_inner_product_sensitive(remapped_name); + + std::vector raw_errors; + raw_errors.reserve(valid_types.size()); + + for (ggml_type vt : valid_types) { + if (poll_interrupt()) { return std::nullopt; } + const wce_cache * ptr_ref_wce = use_wce && !ref_wce.row_sq_norm.empty() ? & ref_wce : nullptr; + const mse_cache * ptr_ref_mse = !use_wce && !ref_mse.row_sq_norm.empty() ? & ref_mse : nullptr; + const float bpw = (float)ggml_type_size(vt) * 8.0f / (float)ggml_blck_size(vt); + const std::vector& eval_sample = is_outlier_heavy && bpw < 3.0f ? smoothed_sample : f32_sample; + + quant_error qe = compute_quant_error( + tensor, + vt, + eval_sample, + rows_sample, + val_vec_ptr, + act_vec_ptr, + q_buf, + dq_buf, + ptr_ref_wce, + ptr_ref_mse, + ptr_val_metric + ); + + double error = qe.error; + if (ip_sensitive) { error *= 1.0f + 0.5f * std::pow(2.0f, 3.0f - bpw); } // error adjustment for inner-product sensitive tensors at low bpw + + type_scores candidate; + candidate.type = vt; + candidate.bpw = (float)tensor_bpw(tensor, vt); + candidate.bytes = tensor_bytes(tensor, vt); + candidate.error = error * scaling_factor; + candidate.mse = qe.mse; + candidate.wce = qe.wce; + evaluations.push_back(candidate); + raw_errors.push_back(qe.error); + } + + type_choice ch; + ch.w = tw; + ch.n_elements = ggml_nelements(tensor); + + for (const auto & ev : evaluations) { + if (ev.bytes == 0) { continue; } + ch.candidates.push_back(ev); + } + + if (ch.candidates.empty()) { + const bool is_locked = locked_tensors && locked_tensors->find(name) != locked_tensors->end(); + if (qs.has_ignored_types && !is_locked) { + throw std::runtime_error(format("%s: tensor '%s' has %zu quant type candidates left after --target-exclude\n", func, name.c_str(), ch.candidates.size())); + } + + type_scores fb; + fb.type = tensor->type; + fb.bytes = ggml_nbytes(tensor); + fb.bpw = fb.bytes * 8.0f / ch.n_elements; + ch.candidates.push_back(fb); + } + + auto simplify_pareto = [&](std::vector & candidates) { + std::sort(candidates.begin(), candidates.end(), [](const auto& a, const auto& b) { + return a.bytes < b.bytes || (a.bytes == b.bytes && (a.error < b.error || (a.error == b.error && a.type < b.type))); + }); + candidates.erase(std::unique(candidates.begin(), candidates.end(), + [](const auto & a, const auto &b) { return a.bytes == b.bytes; }), candidates.end()); + + std::vector hull; + double min_err = INFINITE; + for(const auto & c : candidates) { + if (c.error < min_err) { + min_err = c.error; + hull.push_back(c); + } + } + candidates = std::move(hull); + + if (candidates.size() < 3) { return; } + std::vector convex; + auto cross = [](const auto& a, const auto& b, const auto& c) { + return ((double)b.bytes - (double)a.bytes) * (c.error - a.error) - ((double)c.bytes - (double)a.bytes) * (b.error - a.error); + }; + + for (const auto & c : candidates) { + while (convex.size() >= 2 && cross(convex[convex.size()-2], convex.back(), c) <= EPSILON) { convex.pop_back(); } + convex.push_back(c); + } + + candidates = std::move(convex); + }; + + simplify_pareto(ch.candidates); + ch.choice = 0; + ch.min_bpw = ch.candidates.front().bpw; + ch.max_bpw = ch.candidates.back().bpw; + return ch; + }; + + std::vector all_tensors; // this vector will be populated by the parallel workers + { + std::atomic idx{0}; + std::mutex m_load; + std::mutex m_log; + std::mutex m_res; + std::exception_ptr w_exception; + std::atomic w_failed{false}; + std::vector threads; + threads.reserve(n_workers); + + for (int i = 0; i < n_workers; ++i) { + threads.emplace_back([&](){ + try { + std::vector> buf; + std::vector f32_sample; + std::vector smoothed_sample; + std::vector val_cache; + std::vector act_cache; + while(true) { + if (w_failed.load(std::memory_order_relaxed) || poll_interrupt()) { break; } + const size_t cur = idx.fetch_add(1); + if (cur >= tensors.size()) { break; } + if (!can_quantize(tensors[cur]->tensor)) { continue; } + + auto res = process_tensor(tensors[cur], buf, f32_sample, smoothed_sample, val_cache, act_cache, m_load, m_log); + if (res) { + std::lock_guard lock(m_res); + all_tensors.push_back(std::move(*res)); + } else { + break; + } + } + } catch (...) { + std::lock_guard lock(m_res); + if (!w_failed.exchange(true)) { + w_exception = std::current_exception(); + } + } + }); + } + + for(auto& t : threads) { t.join(); } + + if (w_exception) { + std::rethrow_exception(w_exception); + } + } + + if (interrupted) { + std::unordered_set reached; + for (const auto & tc : all_tensors) { reached.insert(ggml_get_name(tc.w->tensor)); } + for (const auto * tw : tensors) { + const std::string name = ggml_get_name(tw->tensor); + const auto it = bpw_data.find(name); + if (it == bpw_data.end() || reached.count(name)) { continue; } + type_choice tc = it->second; + tc.w = tw; + all_tensors.push_back(std::move(tc)); + } + } + + throw_if_aborted(all_tensors); + if (qs.params->state_file) { + if (qs.has_ignored_types) { LLAMA_LOG_WARN("\t%s: state checkpoint cannot be saved while --target-exclude is active\n", func); } + else { save_state(all_tensors); } + } + + if (all_tensors.empty()) { return {}; } + + // Compute total elements across all tensors and bytes for non-quantizable tensors + size_t n_elements = 0; + size_t nq_bytes = 0; + for (const auto * it : tensors) { + const ggml_tensor * tensor = it->tensor; + n_elements += (size_t)ggml_nelements(tensor); + if (!can_quantize(tensor)) { nq_bytes += ggml_nbytes(tensor); } + } + + // Exclude user defined tensors (--tensor-type) from the Lagrangian optimization (courtesy of https://github.com/AesSedai) + std::vector pinned_tensors; + if (locked_tensors && !locked_tensors->empty()) { + std::vector variable_tensors; + variable_tensors.reserve(all_tensors.size()); + for (auto & tn : all_tensors) { + const std::string name = ggml_get_name(tn.w->tensor); + auto lt = locked_tensors->find(name); + if (lt != locked_tensors->end()) { + const ggml_type mc = tensor_type_fallback(qs, tn.w->tensor, lt->second); + int idx = -1; + for (int j = 0; j < (int)tn.candidates.size(); ++j) { + if (tn.candidates[j].type == mc) { + idx = j; + break; + } + } + + if (idx == -1) { + // Pinned type was pareto-pruned or not evaluated; add with unknown error + type_scores ts; + ts.type = mc; + ts.bpw = (float)tensor_bpw(tn.w->tensor, mc); + ts.bytes = tensor_bytes(tn.w->tensor, mc); + ts.error = std::numeric_limits::quiet_NaN(); + tn.candidates.push_back(ts); + idx = (int)tn.candidates.size() - 1; + } + + tn.choice = idx; + pinned_tensors.push_back(std::move(tn)); + } else { + variable_tensors.push_back(std::move(tn)); + } + } + + all_tensors = std::move(variable_tensors); + } + + size_t pinned_bytes = 0; + for (const auto & tc : pinned_tensors) { pinned_bytes += tc.candidates[tc.choice].bytes; } + + size_t min_total_bytes = 0; + size_t max_total_bytes = 0; + for (const auto & tn : all_tensors) { + min_total_bytes += tn.candidates.front().bytes; + max_total_bytes += tn.candidates.back().bytes; + } + + size_t total_budget_bytes = 0; + size_t total_fixed_bytes = nq_bytes + pinned_bytes; + if (qs.params->target_size != -1) { + total_fixed_bytes += gguf_get_meta_size(ml.metadata); + total_budget_bytes = (size_t)qs.params->target_size; + } else { + total_budget_bytes = std::llround(qs.params->target_bpw * (double)n_elements / 8.0); + } + + size_t pinned_min_bytes = 0; + for (const auto & tc : pinned_tensors) { pinned_min_bytes += tc.candidates.front().bytes; } + + const size_t min_bytes = total_fixed_bytes + min_total_bytes; + const size_t unpinned_min_bytes = min_bytes - pinned_bytes + pinned_min_bytes; + const bool clamped = total_budget_bytes < min_bytes; + + auto size_str = [&](const size_t bytes) { + return qs.params->target_size != -1 ? format("%zu bytes", bytes) : format("%.4f bpw", (double)bytes * 8.0 / n_elements); + }; + + const std::string requested = qs.params->target_size != -1 ? format("file size %zu", total_budget_bytes) : format("bpw %.4f", qs.params->target_bpw); + size_t budget_bytes = 0; + if (!clamped) { + budget_bytes = total_budget_bytes - total_fixed_bytes; + if (!pinned_tensors.empty() && budget_bytes > max_total_bytes) { + LLAMA_LOG_WARN("\t%s: target %s is not reachable with the pinned tensors (maximum ~%s); clamping to maximum\n", + func, requested.c_str(), size_str(total_fixed_bytes + max_total_bytes).c_str()); + } + } else { + if (total_budget_bytes >= unpinned_min_bytes) { + throw std::runtime_error(format("%s: target %s is not reachable with the pinned tensors (minimum ~%s)", + func, requested.c_str(), size_str(min_bytes).c_str())); + } + + const std::string pinned_min = pinned_tensors.empty() ? "" : format(" (~%s with the pinned tensors)", size_str(min_bytes).c_str()); + LLAMA_LOG_WARN("\t%s: requested %s is smaller than minimum possible model size (~%s); clamping to minimum%s\n", + func, requested.c_str(), size_str(unpinned_min_bytes).c_str(), pinned_min.c_str()); + + budget_bytes = min_total_bytes; + } + + // pins starve the selection process when remaining bpw is below boost_taper + if (!pinned_tensors.empty() && !all_tensors.empty()) { + size_t pinned_elements = 0; + for (const auto & tc : pinned_tensors) { pinned_elements += tc.n_elements; } + size_t rest_elements = 0; + for (const auto & tn : all_tensors) { rest_elements += tn.n_elements; } + + const size_t other_fixed_bytes = total_fixed_bytes - pinned_bytes; + const double shared_bpw = std::max(0.0, 8.0 * ((double)total_budget_bytes - (double)other_fixed_bytes) / (double)(pinned_elements + rest_elements)); + const double rest_bpw = 8.0 * (double)std::min(budget_bytes, max_total_bytes) / (double)rest_elements; + LLAMA_LOG_INFO("\t%s: pinning %zu tensors (%.2f%% of weights) leaves %.4f bpw available for the rest\n", + func, pinned_tensors.size(), 100.0 * pinned_elements / (pinned_elements + rest_elements), rest_bpw); + + if (!clamped && rest_bpw < boost_taper && shared_bpw >= boost_taper) { + LLAMA_LOG_WARN("\t%s: remaining bpw is below the %.1f safety limit; model's quality may be severely compromised\n", func, boost_taper); + } + } + + // Get the types' override + auto build_mix = [&]() -> std::unordered_map { + std::unordered_map quant_mix; + std::unordered_map optimized; + std::unordered_map pinned; + optimized.reserve(all_tensors.size()); + for (const auto & tn : all_tensors) { optimized[ggml_get_name(tn.w->tensor)] = & tn; } + pinned.reserve(pinned_tensors.size()); + for (const auto & tn : pinned_tensors) { pinned[ggml_get_name(tn.w->tensor)] = & tn; } + + LLAMA_LOG_INFO("\t%s: tensor quantization mix:\n", func); + for (const auto * tn : tensors) { + const std::string name = ggml_get_name(tn->tensor); + + auto pd = pinned.find(name); + bool is_pinned = pd != pinned.end(); + const auto * tn_ptr = is_pinned ? pd->second : nullptr; + + if (!tn_ptr) { + auto opt = optimized.find(name); + if (opt != optimized.end()) { tn_ptr = opt->second; } + } + + if (tn_ptr) { + const auto & tp = * tn_ptr; + const auto & choice = tp.candidates[tp.choice]; + + LLAMA_LOG_INFO("\t%s: %45s %s\t%8s, \t%1.4f bpw,\terror: %.4f%s\n", + func, + name.c_str(), + tp.boost > 1.0f ? "⬆︎" : "-", + ggml_type_name(choice.type), + choice.bpw, + choice.error, + is_pinned ? " (pinned)" : ""); + + quant_mix[name] = choice.type; + } + } + + return quant_mix; + }; + + if (budget_bytes <= min_total_bytes) { + for(auto & tn : all_tensors) { tn.choice = 0; } + return build_mix(); + } + if (budget_bytes >= max_total_bytes) { + for(auto & tn : all_tensors) { tn.choice = (int)tn.candidates.size() - 1; } + return build_mix(); + } + + // Certain tensors have a higher impact on model quality, so they get a boost + size_t total_elements = 0; + for (const auto & tn : all_tensors) { total_elements += tn.n_elements; } + const double global_bpw = 8.0 * (double)budget_bytes / (double)total_elements; + for (auto & tn : all_tensors) { + const std::string tensor_name = ggml_get_name(tn.w->tensor); + if (tensor_name.find("ffn_down.weight") != std::string::npos) { + if (global_bpw < boost_taper) { + for (auto & candidate : tn.candidates) { candidate.error *= 1.0 + std::pow(2.0, 3.0 - candidate.bpw); } + } else { + tn.boost = ffn_down_boost; + } + } else if (tensor_name == "output.weight") { + tn.boost = output_boost; + } else if (tensor_name.find("attn_v") != std::string::npos) { + tn.boost = attn_v_boost; + } else if (qs.has_tied_embeddings && tensor_name == "token_embd.weight" && global_bpw >= boost_taper) { + const double embd_share = (double)tn.n_elements / (double)total_elements; + tn.boost = embd_share <= 0.10 ? tied_embd_boost : (float)std::max(1.25, (double)tied_embd_boost * (1.0 - 3.0 * (embd_share - 0.10))); + } + } + + // Minimize error subject to a size target constraint + auto lagrangian_relaxation = [&](const double mu, std::vector & choices, size_t & bytes, double & cost) { + choices.resize(all_tensors.size()); + bytes = 0; + cost = 0.0; + for (size_t i = 0; i < all_tensors.size(); ++i) { + const auto & tn = all_tensors[i]; + const double eff_mu = mu / tn.boost; // boosted tensors get a lower penalty + int best = 0; + for(int j = 1; j < (int)tn.candidates.size(); ++j) { + double lr = (tn.candidates[j].error - tn.candidates[best].error) + eff_mu * ((double)tn.candidates[j].bytes - (double)tn.candidates[best].bytes) * 8.0; + if (lr < -EPSILON || (std::abs(lr) <= EPSILON && tn.candidates[j].bytes < tn.candidates[best].bytes)) { + best = j; + } + } + + choices[i] = best; + bytes += tn.candidates[best].bytes; + cost += tn.candidates[best].error; + } + }; + + // Binary search for mu then greedy upgrade upwards followed by greedy upgrade downwards of any leftover budget + auto run_auction = [&](const size_t budget) { + size_t min_bytes = 0; + size_t max_bytes = 0; + for (const auto & tn : all_tensors) { + min_bytes += tn.candidates.front().bytes; + max_bytes += tn.candidates.back().bytes; + } + + if (budget <= min_bytes) { + for (auto & tn : all_tensors) { tn.choice = 0; } + return; + } + + if (budget >= max_bytes) { + for (auto & tn : all_tensors) { tn.choice = (int)tn.candidates.size() - 1; } + return; + } + + // Binary search for mu + double mu_lo = 0.0; + double mu_hi = 1.0; + std::vector ch_lo; + std::vector ch_hi; + std::vector ch_under; + std::vector ch_over; + size_t bt_lo; + size_t bt_hi; + size_t bt_mid; + double dummy; + + lagrangian_relaxation(mu_lo, ch_lo, bt_lo, dummy); + int safety = 0; + + do { + lagrangian_relaxation(mu_hi, ch_hi, bt_hi, dummy); + if (bt_hi <= budget || bt_hi == std::numeric_limits::max()) { break; } + mu_hi *= 2.0; + } while(++safety < 60); + + double gap_under = INFINITE; + double gap_over = INFINITE; + + for(int i = 0; i < 40; ++i) { + double mu = 0.5 * (mu_lo + mu_hi); + std::vector ch_mid; + double cost_mid = 0.0; + lagrangian_relaxation(mu, ch_mid, bt_mid, cost_mid); + + double gap = std::abs((double)bt_mid - (double)budget); + if (bt_mid > budget) { + mu_lo = mu; + if (gap < gap_over) { + gap_over = gap; + ch_over = ch_mid; + } + } else { + mu_hi = mu; + if (gap < gap_under) { + gap_under = gap; + ch_under = ch_mid; + } + } + } + + if (!ch_under.empty()) { + for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_under[i]; } + } + else if (!ch_over.empty()) { + for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_over[i]; } + } + else if (bt_hi <= budget && !ch_hi.empty()) { + for(size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = ch_hi[i]; } + } + else { + for(auto& tn : all_tensors) { tn.choice = 0; } + } + + auto current_bytes = [&] { + size_t cb = 0; + for(const auto & tn : all_tensors) { cb += tn.candidates[tn.choice].bytes; } + return cb; + }; + + struct tensor_upgrade { + int index; + int next_choice; + double score; + bool operator<(const tensor_upgrade & other) const { + return score < other.score; + } + }; + + // greedy upwards/downwards upgrades in case there is budget left + auto allocate_remaining = [&] { + size_t cb = current_bytes(); + std::priority_queue queue; + + auto push_next = [&](const int i) { + const auto & tn = all_tensors[i]; + int next = tn.choice + 1; + if (next < (int)tn.candidates.size()) { + const double err = std::max(0.0, tn.candidates[tn.choice].error - tn.candidates[next].error); + auto bytes = (double)(tn.candidates[next].bytes - tn.candidates[tn.choice].bytes); + if (bytes > EPSILON) { + double ratio = err / bytes; + ratio *= tn.boost; // boosted tensors get a higher priority + queue.push({i, next, ratio}); + } + } + }; + + for (size_t i = 0; i < all_tensors.size(); ++i) { push_next((int)i); } + + while (!queue.empty()) { + auto top = queue.top(); + queue.pop(); + + int i = top.index; + int next = top.next_choice; + if (all_tensors[i].choice >= next) { continue; } + + size_t delta_bt = all_tensors[i].candidates[next].bytes - all_tensors[i].candidates[all_tensors[i].choice].bytes; + if (cb + delta_bt <= budget) { + cb += delta_bt; + all_tensors[i].choice = next; + push_next(i); + } + } + }; + + // upwards upgrade + allocate_remaining(); + + // upgrade cannot swap one large for several small so we try downwards too + auto total_cost = [&] { + double cost = 0.0; + for (const auto & tn : all_tensors) { cost += tn.boost * tn.candidates[tn.choice].error; } + return cost; + }; + + std::vector under_choices(all_tensors.size()); + for (size_t i = 0; i < all_tensors.size(); ++i) { under_choices[i] = all_tensors[i].choice; } + const double under_cost = total_cost(); + + const std::vector & over = ch_over.empty() ? ch_lo : ch_over; + for (size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = over[i]; } + + // drop the step with the least boosted error per byte, counting no more bytes than are still over budget + size_t cb = current_bytes(); + while (cb > budget) { + int best = -1; + double best_score = INFINITE; + for (size_t i = 0; i < all_tensors.size(); ++i) { + const auto & tn = all_tensors[i]; + if (tn.choice == 0) { continue; } + const double err = tn.boost * std::max(0.0, tn.candidates[tn.choice - 1].error - tn.candidates[tn.choice].error); + const size_t freed = tn.candidates[tn.choice].bytes - tn.candidates[tn.choice - 1].bytes; + const double score = err / (double)std::min(freed, cb - budget); + if (score < best_score) { + best_score = score; + best = (int)i; + } + } + + if (best < 0) { break; } + auto & tn = all_tensors[best]; + cb -= tn.candidates[tn.choice].bytes - tn.candidates[tn.choice - 1].bytes; + --tn.choice; + } + + allocate_remaining(); + if (current_bytes() > budget || total_cost() >= under_cost * (1.0 - downward_threshold)) { + for (size_t i = 0; i < all_tensors.size(); ++i) { all_tensors[i].choice = under_choices[i]; } + } + }; + + run_auction(budget_bytes); + + // Dense ffn_down cap + if (global_bpw >= boost_taper) { + const std::regex dense_ffn_down("blk\\.[0-9]+\\.ffn_down\\.weight"); + std::vector role; + for (size_t i = 0; i < all_tensors.size(); ++i) { + if (std::regex_match(std::string(ggml_get_name(all_tensors[i].w->tensor)), dense_ffn_down)) { + role.push_back(i); + } + } + + if (role.size() >= 8) { + std::vector role_bpw; + role_bpw.reserve(role.size()); + for (const size_t i : role) { role_bpw.push_back(all_tensors[i].candidates[all_tensors[i].choice].bpw); } + std::sort(role_bpw.begin(), role_bpw.end()); + const size_t mid = role_bpw.size() / 2; + const double median_bpw = role_bpw.size() % 2 ? role_bpw[mid] : 0.5 * (role_bpw[mid - 1] + role_bpw[mid]); + + std::vector outlier; + for (const size_t i : role) { + if (median_bpw - (double)all_tensors[i].candidates[all_tensors[i].choice].bpw > 2.0) { outlier.push_back(i); } + } + + if (!outlier.empty()) { + // nominal-bpw tie break: K-quants first, then IQ, then legacy + auto family_rank = [&](const ggml_type gt) { + switch (gt) { + case GGML_TYPE_Q2_K: + case GGML_TYPE_Q3_K: + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + return 0; + default: + return is_iq(gt) ? 1 : 2; + } + }; + + ggml_type fill = GGML_TYPE_Q8_0; + double fill_bpw = INFINITE; + int fill_rank = 3; + for (const ggml_type t : quant_types) { + if (!ggml_is_quantized(t)) { continue; } + if (qs.ignored_types[t]) { continue; } + const double nominal = (double)ggml_type_size(t) * 8.0 / (double)ggml_blck_size(t); + if (nominal < median_bpw) { continue; } + const int rank = family_rank(t); + if (nominal < fill_bpw || (nominal == fill_bpw && rank < fill_rank)) { + fill = t; + fill_bpw = nominal; + fill_rank = rank; + } + } + + if (fill_bpw == INFINITE && qs.ignored_types[fill]) { + LLAMA_LOG_WARN("\t%s: ffn_down type %s is ignored by --target-exclude, keeping the auto-selected type\n", func, ggml_type_name(fill)); + } else { + size_t locked_bytes = 0; + std::vector remaining; + remaining.reserve(all_tensors.size()); + for (size_t i = 0; i < all_tensors.size(); ++i) { + auto & tn = all_tensors[i]; + if (!std::binary_search(outlier.begin(), outlier.end(), i)) { + remaining.push_back(std::move(tn)); + continue; + } + + const ggml_tensor * tensor = tn.w->tensor; + const ggml_type mc = make_compatible(tensor, fill); + if (qs.ignored_types[mc]) { + // the fill resolution is barred - keep the auction-chosen type + remaining.push_back(std::move(tn)); + continue; + } + int idx = -1; + for (int j = 0; j < (int)tn.candidates.size(); ++j) { + if (tn.candidates[j].type == mc) { idx = j; break; } + } + + if (idx == -1) { + type_scores ts; + ts.type = mc; + ts.bpw = (float)tensor_bpw(tensor, mc); + ts.bytes = tensor_bytes(tensor, mc); + ts.error = std::numeric_limits::quiet_NaN(); + tn.candidates.push_back(ts); + idx = (int)tn.candidates.size() - 1; + } + + tn.choice = idx; + locked_bytes += tn.candidates[idx].bytes; + pinned_tensors.push_back(std::move(tn)); + } + + all_tensors = std::move(remaining); + run_auction(budget_bytes > locked_bytes ? budget_bytes - locked_bytes : 0); + } + } + } + } + + // Expert down-projection cap + if (global_bpw < boost_taper) { + const std::regex expert_ffn_down("blk\\.[0-9]+\\.ffn_down_exps\\.weight"); + const std::regex expert_ffn_gate("blk\\.[0-9]+\\.ffn_gate_exps\\.weight"); + const std::regex expert_ffn_up ("blk\\.[0-9]+\\.ffn_up_exps\\.weight"); + + // Element-weighted mean of the chosen bpw + auto mean_bpw = [&](const std::regex & re, std::vector * members) -> double { + double num = 0.0; + double den = 0.0; + for (size_t i = 0; i < all_tensors.size(); ++i) { + const auto & tn = all_tensors[i]; + if (!std::regex_match(std::string(ggml_get_name(tn.w->tensor)), re)) { continue; } + num += (double)tn.n_elements * (double)tn.candidates[tn.choice].bpw; + den += (double)tn.n_elements; + if (members) { members->push_back(i); } + } + + return den > 0.0 ? num / den : -1.0; + }; + + std::vector role; + std::vector siblings; + const double down_bpw = mean_bpw(expert_ffn_down, &role); + // mean_bpw appends so siblings gets both the gate and the up tensors + const double gate_bpw = mean_bpw(expert_ffn_gate, &siblings); + const double up_bpw = mean_bpw(expert_ffn_up, &siblings); + const double sibling_bpw = std::max(gate_bpw, up_bpw); + std::sort(siblings.begin(), siblings.end()); + if (!role.empty() && sibling_bpw > 0.0 && down_bpw > sibling_bpw) { + std::vector outliers; + for (const size_t i : role) { + if ((double)all_tensors[i].candidates[all_tensors[i].choice].bpw > sibling_bpw) { outliers.push_back(i); } + } + + if (!outliers.empty()) { + size_t locked_bytes = 0; + std::vector remaining; + remaining.reserve(all_tensors.size()); + for (size_t i = 0; i < all_tensors.size(); ++i) { + auto & tn = all_tensors[i]; + if (!std::binary_search(outliers.begin(), outliers.end(), i)) { + if (std::binary_search(siblings.begin(), siblings.end(), i)) { + locked_bytes += tn.candidates[tn.choice].bytes; + pinned_tensors.push_back(std::move(tn)); + continue; + } + + if (std::binary_search(role.begin(), role.end(), i)) { + const ggml_type chosen = tn.candidates[tn.choice].type; + std::vector kept; + kept.reserve(tn.candidates.size()); + for (const auto & c : tn.candidates) { + if ((double)c.bpw <= sibling_bpw) { kept.push_back(c); } + } + + int new_choice = -1; + for (int j = 0; j < (int)kept.size(); ++j) { + if (kept[j].type == chosen) { new_choice = j; break; } + } + + if (new_choice >= 0) { + tn.candidates = std::move(kept); + tn.choice = new_choice; + } + } + + remaining.push_back(std::move(tn)); + continue; + } + + int idx = -1; + for (int j = 0; j < (int)tn.candidates.size(); ++j) { + if ((double)tn.candidates[j].bpw > sibling_bpw) { continue; } + if (idx == -1 || tn.candidates[j].bpw > tn.candidates[idx].bpw) { idx = j; } + } + + if (idx == -1) { + remaining.push_back(std::move(tn)); + continue; + } + + tn.choice = idx; + locked_bytes += tn.candidates[idx].bytes; + pinned_tensors.push_back(std::move(tn)); + } + + all_tensors = std::move(remaining); + run_auction(budget_bytes > locked_bytes ? budget_bytes - locked_bytes : 0); + } + } + } + + return build_mix(); +} + +// imatrix requirement check +static bool tensor_requires_imatrix(const char * tensor_name, const ggml_type dst_type, const llama_ftype ftype) { + if (tensor_name_match_token_embd(tensor_name) || tensor_name_match_output_weight(tensor_name)) { return false; } + switch (dst_type) { + case GGML_TYPE_IQ3_XXS: + case GGML_TYPE_IQ2_XXS: + case GGML_TYPE_IQ2_XS: + case GGML_TYPE_IQ2_S: + case GGML_TYPE_IQ1_M: + case GGML_TYPE_IQ1_S: + return true; + case GGML_TYPE_Q2_K: + // as a general rule, the k-type quantizations don't require imatrix data. + // the only exception is Q2_K tensors that are part of a Q2_K_S file. + return ftype == LLAMA_FTYPE_MOSTLY_Q2_K_S; + default: + return false; + } +} + +// given a file type, get the default tensor type +ggml_type llama_ftype_get_default_type(const llama_ftype ftype) { + switch (ftype) { + case LLAMA_FTYPE_MOSTLY_Q4_0: return GGML_TYPE_Q4_0; + case LLAMA_FTYPE_MOSTLY_Q4_1: return GGML_TYPE_Q4_1; + case LLAMA_FTYPE_MOSTLY_Q5_0: return GGML_TYPE_Q5_0; + case LLAMA_FTYPE_MOSTLY_Q5_1: return GGML_TYPE_Q5_1; + case LLAMA_FTYPE_MOSTLY_Q8_0: return GGML_TYPE_Q8_0; + case LLAMA_FTYPE_MOSTLY_F16: return GGML_TYPE_F16; + case LLAMA_FTYPE_MOSTLY_BF16: return GGML_TYPE_BF16; + case LLAMA_FTYPE_ALL_F32: return GGML_TYPE_F32; + case LLAMA_FTYPE_MOSTLY_Q1_0: return GGML_TYPE_Q1_0; + case LLAMA_FTYPE_MOSTLY_Q2_0: return GGML_TYPE_Q2_0; + + case LLAMA_FTYPE_MOSTLY_MXFP4_MOE: return GGML_TYPE_MXFP4; + + // K-quants + case LLAMA_FTYPE_MOSTLY_Q2_K_S: + case LLAMA_FTYPE_MOSTLY_Q2_K: return GGML_TYPE_Q2_K; + case LLAMA_FTYPE_MOSTLY_IQ3_XS: return GGML_TYPE_IQ3_S; + case LLAMA_FTYPE_MOSTLY_Q3_K_S: + case LLAMA_FTYPE_MOSTLY_Q3_K_M: + case LLAMA_FTYPE_MOSTLY_Q3_K_L: return GGML_TYPE_Q3_K; + case LLAMA_FTYPE_MOSTLY_Q4_K_S: + case LLAMA_FTYPE_MOSTLY_Q4_K_M: return GGML_TYPE_Q4_K; + case LLAMA_FTYPE_MOSTLY_Q5_K_S: + case LLAMA_FTYPE_MOSTLY_Q5_K_M: return GGML_TYPE_Q5_K; + case LLAMA_FTYPE_MOSTLY_Q6_K: return GGML_TYPE_Q6_K; + // Ternary quants + case LLAMA_FTYPE_MOSTLY_TQ1_0: return GGML_TYPE_TQ1_0; + case LLAMA_FTYPE_MOSTLY_TQ2_0: return GGML_TYPE_TQ2_0; + // Lattice and Non-linear quants + case LLAMA_FTYPE_MOSTLY_IQ2_XXS: return GGML_TYPE_IQ2_XXS; + case LLAMA_FTYPE_MOSTLY_IQ2_XS: return GGML_TYPE_IQ2_XS; + case LLAMA_FTYPE_MOSTLY_IQ2_S: return GGML_TYPE_IQ2_XS; + case LLAMA_FTYPE_MOSTLY_IQ2_M: return GGML_TYPE_IQ2_S; + case LLAMA_FTYPE_MOSTLY_IQ3_XXS: return GGML_TYPE_IQ3_XXS; + case LLAMA_FTYPE_MOSTLY_IQ1_S: return GGML_TYPE_IQ1_S; + case LLAMA_FTYPE_MOSTLY_IQ1_M: return GGML_TYPE_IQ1_M; + case LLAMA_FTYPE_MOSTLY_IQ4_NL: return GGML_TYPE_IQ4_NL; + case LLAMA_FTYPE_MOSTLY_IQ4_XS: return GGML_TYPE_IQ4_XS; + case LLAMA_FTYPE_MOSTLY_IQ3_S: + case LLAMA_FTYPE_MOSTLY_IQ3_M: return GGML_TYPE_IQ3_S; + + default: return GGML_TYPE_COUNT; + } +} + +static void init_quantize_state_counters(quantize_state_impl & qs, std::vector & metadata) { + for (auto & tm : metadata) { + tm.category = tensor_get_category(tm.name); + if (category_is_attn_v(tm.category)) { ++qs.n_attention_wv; } + if (tm.category == TENSOR_CATEGORY_OUTPUT) { qs.has_tied_embeddings = false; } + } + + qs.n_ffn_down = qs.n_ffn_gate = qs.n_ffn_up = (int)qs.model.hparams.n_layer_all; +} + +// main quantization driver +static void llama_model_quantize_impl(const std::string & fname_inp, const std::string & fname_out, const llama_model_quantize_params * params) { + llama_ftype ftype = params->ftype; + int nthread = params->nthread; + if (nthread <= 0) { nthread = (int)std::thread::hardware_concurrency(); } + + const ggml_type default_type = llama_ftype_get_default_type(ftype); + if (default_type == GGML_TYPE_COUNT) { throw std::runtime_error(format("invalid output file type %d\n", ftype)); } + + // mmap consistently increases speed on Linux, and also increases speed on Windows with + // hot cache. It may cause a slowdown on macOS, possibly related to free memory. +#if defined(__linux__) || defined(_WIN32) + constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_MMAP; +#else + constexpr llama_load_mode load_mode = LLAMA_LOAD_MODE_NONE; +#endif + + const llama_model_kv_override * kv_overrides = params->kv_overrides; + std::vector splits = {}; + llama_model_loader ml(/*metadata*/ nullptr, /*set_tensor_data*/ nullptr, /*set_tensor_data_ud*/ nullptr, + fname_inp, splits, /*file*/ nullptr, /*load_mode*/ load_mode, /*check_tensors*/ true, /*no_alloc*/ false, /*load_mtp*/ true, kv_overrides, nullptr); + ml.init_mappings(false); // no prefetching auto mparams = llama_model_default_params(); std::unique_ptr model_ptr(llama_model_create(ml, mparams)); @@ -1069,39 +3184,70 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: quantize_state_impl qs(*model, params); - if (params->only_copy) { - ftype = ml.ftype; - } - std::unordered_map> i_data; - const std::unordered_map> * imatrix_data = nullptr; + if (params->only_copy) { ftype = ml.ftype; } + const std::unordered_map> * values_data = nullptr; + const std::unordered_map> * activations_data = nullptr; + const std::unordered_map> * statistics_data = nullptr; + std::unordered_map> vdata; + std::unordered_map> adata; + std::unordered_map> sdata; + const std::vector * stats_schema = nullptr; + std::vector sschema; if (params->imatrix) { - for (const llama_model_imatrix_data * p = params->imatrix; p->name != nullptr; p++) { - i_data.emplace(p->name, std::vector(p->data, p->data + p->size)); + for (const llama_model_imatrix_data * i = params->imatrix; i->name != nullptr; i++) { + vdata.emplace(i->name, std::vector(i->data, i->data + i->size)); } - imatrix_data = & i_data; - if (imatrix_data) { - LLAMA_LOG_INFO("\n%s: have importance matrix data with %d entries\n", - __func__, (int)imatrix_data->size()); + + values_data = & vdata; + if (values_data) { + LLAMA_LOG_INFO("%s: have importance matrix data with %d entries", __func__, (int)values_data->size()); qs.has_imatrix = true; // check imatrix for nans or infs - for (const auto & kv : *imatrix_data) { + for (const auto & kv : * values_data) { for (float f : kv.second) { - if (!std::isfinite(f)) { - throw std::runtime_error(format("imatrix contains non-finite value %f\n", f)); - } + if (!std::isfinite(f)) { throw std::runtime_error(format("imatrix contains non-finite value %f\n", f)); } } } } } + if (params->activations) { + for (const llama_model_imatrix_data * a = params->activations; a->name != nullptr; a++) { + adata.emplace(a->name, std::vector(a->data, a->data + a->size)); + } + + activations_data = & adata; + if (activations_data) { + LLAMA_LOG_INFO(" - %d activations", (int)activations_data->size()); + qs.has_activations = true; + // check activations for nans or infs + for (const auto & kv : * activations_data) { + for (float f : kv.second) { + if (!std::isfinite(f)) { throw std::runtime_error(format("activations contain non-finite value %f\n", f)); } + } + } + } + } + if (params->statistics) { + for (const llama_model_imatrix_data * s = params->statistics; s->name != nullptr; s++) { + sdata.emplace(s->name, std::vector(s->data, s->data + s->size)); + } + if (params->stats_schema) { + for (const char * const * s = params->stats_schema; * s != nullptr; s++) { sschema.emplace_back(* s); } + stats_schema = & sschema; + } + + statistics_data = & sdata; + if (statistics_data) { LLAMA_LOG_INFO(" and %d statistics", (int)statistics_data->size()); + } + } + LLAMA_LOG_INFO("\n"); const size_t align = GGUF_DEFAULT_ALIGNMENT; gguf_context_ptr ctx_out { gguf_init_empty() }; std::vector prune_list = {}; if (params->prune_layers) { - for (const int32_t * p = params->prune_layers; * p != -1; p++) { - prune_list.push_back(* p); - } + for (const int32_t * p = params->prune_layers; * p != -1; p++) { prune_list.push_back(* p); } } // copy the KV pairs from the input file @@ -1115,27 +3261,38 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: gguf_remove_key(ctx_out.get(), ml.llm_kv(LLM_KV_SPLIT_TENSORS_COUNT).c_str()); if (params->kv_overrides) { - for (const llama_model_kv_override * o = params->kv_overrides; o->key[0] != 0; ++o) { - if (o->tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) { - gguf_set_val_f32(ctx_out.get(), o->key, o->val_f64); - } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_INT) { + for (const llama_model_kv_override * kvo = params->kv_overrides; kvo->key[0] != 0; ++kvo) { + if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_FLOAT) { + gguf_set_val_f32(ctx_out.get(), kvo->key, kvo->val_f64); + } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_INT) { // Setting type to UINT32. See https://github.com/ggml-org/llama.cpp/pull/14182 for context - gguf_set_val_u32(ctx_out.get(), o->key, (uint32_t)std::abs(o->val_i64)); - } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) { - gguf_set_val_bool(ctx_out.get(), o->key, o->val_bool); - } else if (o->tag == LLAMA_KV_OVERRIDE_TYPE_STR) { - gguf_set_val_str(ctx_out.get(), o->key, o->val_str); + gguf_set_val_u32(ctx_out.get(), kvo->key, (uint32_t)std::abs(kvo->val_i64)); + } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_BOOL) { + gguf_set_val_bool(ctx_out.get(), kvo->key, kvo->val_bool); + } else if (kvo->tag == LLAMA_KV_OVERRIDE_TYPE_STR) { + gguf_set_val_str(ctx_out.get(), kvo->key, kvo->val_str); } else { - LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, o->key); + LLAMA_LOG_WARN("%s: unknown KV override type for key %s\n", __func__, kvo->key); } } } + // first layer without its own kv cache + int n_unused_kv_from = -1; + { + uint32_t n_block = 0; + uint32_t n_shared = 0; + ml.get_key(LLM_KV_BLOCK_COUNT, n_block, false); + ml.get_key(LLM_KV_ATTENTION_SHARED_KV_LAYERS, n_shared, false); + if (n_shared > 0 && n_shared <= n_block) { n_unused_kv_from = (int)(n_block - n_shared); } + } + std::map mapped; int blk_id = 0; // make a list of weights std::vector tensors; + std::unordered_set unused_kv_tensors; tensors.reserve(ml.weights_map.size()); for (const auto & it : ml.weights_map) { const std::string remapped_name(remap_layer(it.first, prune_list, mapped, blk_id)); @@ -1143,32 +3300,28 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: LLAMA_LOG_DEBUG("%s: pruning tensor %s\n", __func__, it.first.c_str()); continue; } - if (remapped_name != it.first) { ggml_set_name(it.second.tensor, remapped_name.c_str()); LLAMA_LOG_DEBUG("%s: tensor %s remapped to %s\n", __func__, it.first.c_str(), ggml_get_name(it.second.tensor)); } + if (tensor_name_match_unused_kv(it.first, n_unused_kv_from)) { unused_kv_tensors.insert(remapped_name); } + tensors.push_back(&it.second); } - if (!prune_list.empty()) { - gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), blk_id); - } + + if (!prune_list.empty()) { gguf_set_val_u32(ctx_out.get(), ml.llm_kv(LLM_KV_BLOCK_COUNT).c_str(), blk_id); } // keep_split requires that the weights are sorted by split index if (params->keep_split) { std::sort(tensors.begin(), tensors.end(), [](const llama_model_loader::llama_tensor_weight * a, const llama_model_loader::llama_tensor_weight * b) { - if (a->idx == b->idx) { - return a->offs < b->offs; - } + if (a->idx == b->idx) { return a->offs < b->offs; } return a->idx < b->idx; }); } // compute tensor metadata once and cache it std::vector metadata(tensors.size()); - for (size_t i = 0; i < tensors.size(); ++i) { - metadata[i].name = ggml_get_name(tensors[i]->tensor); - } + for (size_t i = 0; i < tensors.size(); ++i) { metadata[i].name = ggml_get_name(tensors[i]->tensor); } // initialize quantization state counters and metadata categories init_quantize_state_counters(qs, metadata); @@ -1178,46 +3331,41 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // Assume split index is continuous if (params->keep_split) { - for (const auto * it : tensors) { - n_split = std::max(uint16_t(it->idx + 1), n_split); - } + for (const auto * it : tensors) { n_split = std::max((uint16_t)(it->idx + 1), n_split); } } + std::vector ctx_outs(n_split); ctx_outs[0] = std::move(ctx_out); // flag for --dry-run bool will_require_imatrix = false; - // // preliminary iteration over all weights - // - for (size_t i = 0; i < tensors.size(); ++i) { const auto * it = tensors[i]; const struct ggml_tensor * tensor = it->tensor; uint16_t i_split = params->keep_split ? it->idx : 0; - if (!ctx_outs[i_split]) { - ctx_outs[i_split].reset(gguf_init_empty()); - } + if (!ctx_outs[i_split]) { ctx_outs[i_split].reset(gguf_init_empty()); } gguf_add_tensor(ctx_outs[i_split].get(), tensor); metadata[i].allows_quantization = tensor_allows_quantization(params, model->arch, tensor); - if (metadata[i].allows_quantization) { - metadata[i].target_type = llama_tensor_get_type(qs, params, tensor, default_type, metadata[i]); - } else { - metadata[i].target_type = tensor->type; + if (metadata[i].allows_quantization) { metadata[i].target_type = llama_tensor_get_type(qs, params, tensor, default_type, metadata[i]); } + else { metadata[i].target_type = tensor->type; } + + if (metadata[i].allows_quantization && unused_kv_tensors.count(metadata[i].name)) { + metadata[i].target_type = tensor_type_fallback(qs, tensor, GGML_TYPE_Q4_0); + LLAMA_LOG_INFO("%s: unused tensor (%s shares an earlier layer's kv cache) - converting to %s\n", + __func__, metadata[i].name.c_str(), ggml_type_name(metadata[i].target_type)); } metadata[i].requires_imatrix = tensor_requires_imatrix(tensor->name, metadata[i].target_type, ftype); - if (params->imatrix) { - metadata[i].remapped_imatrix_name = remap_imatrix(tensor->name, mapped); - } else if (metadata[i].allows_quantization && metadata[i].requires_imatrix) { - if (params->dry_run) { - will_require_imatrix = true; - } else { + if (params->imatrix) { metadata[i].remapped_imatrix_name = remap_imatrix(tensor->name, mapped); } + else if (metadata[i].allows_quantization && metadata[i].requires_imatrix) { + if (params->dry_run) { will_require_imatrix = true; } + else { LLAMA_LOG_ERROR("\n============================================================================\n" " ERROR: this quantization requires an importance matrix!\n" " - offending tensor: %s\n" @@ -1229,6 +3377,22 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: } } + // report missing imatrix coverage early + if (values_data) { + std::vector no_imatrix; + for (size_t i = 0; i < tensors.size(); ++i) { + const char * name = metadata[i].name.c_str(); + if (!metadata[i].allows_quantization || unused_kv_tensors.count(metadata[i].name)) { continue; } + if (tensor_name_match_token_embd(name) || tensor_name_match_output_weight(name)) { continue; } + if (!values_data->count(metadata[i].remapped_imatrix_name)) { no_imatrix.push_back(metadata[i].name); } + } + + if (!no_imatrix.empty()) { + LLAMA_LOG_WARN("%s: %zu quantizable tensors have no imatrix data:\n", __func__, no_imatrix.size()); + for (const auto & name : no_imatrix) { LLAMA_LOG_WARN("%s: %s\n", __func__, name.c_str()); } + } + } + // Set split info if needed if (n_split > 1) { for (size_t i = 0; i < ctx_outs.size(); ++i) { @@ -1250,6 +3414,92 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: const size_t max_buf_size = params->max_buf_size ? params->max_buf_size : LLAMA_QUANT_MAX_BUF_SIZE; + std::unordered_map bpw_overrides = {}; + if ((params->target_bpw != -1.0f || params->target_size != -1) && !params->only_copy) { + if (params->imatrix) { + if (params->pure) { + LLAMA_LOG_WARN("%s: --target-bpw/--target-size specified with --pure, ignoring --pure\n", __func__); + } + if (params->target_size >= 0) { + LLAMA_LOG_INFO("%s: computing tensor quantization mix to achieve file size %.2f MiB\n", __func__, (double)params->target_size / 1024.0 / 1024.0); + } else { + LLAMA_LOG_INFO("%s: computing tensor quantization mix to achieve %.4f bpw\n", __func__, params->target_bpw); + } + + if (qs.has_ignored_types) { + std::string barred; + for (size_t i = 0; i < qs.ignored_types.size(); ++i) { + if (qs.ignored_types[i]) { + if (!barred.empty()) { barred += ", "; } + barred += ggml_type_name((ggml_type)i); + } + } + + LLAMA_LOG_INFO("%s: --target-exclude ignores quant types: %s\n", __func__, barred.c_str()); + + // pinned types have precedence over ignored + for (const auto & p : qs.tensor_type_patterns) { + if (p.type < GGML_TYPE_COUNT && qs.ignored_types[p.type]) { + LLAMA_LOG_WARN("%s: --tensor-type pattern '%s' pins type %s which is ignored by --target-exclude, keeping the pinned type\n", + __func__, p.pattern.c_str(), ggml_type_name(p.type)); + } + } + + const std::pair type_flags[] = { + { "--token-embedding-type", params->token_embedding_type }, + { "--output-tensor-type", params->output_tensor_type }, + }; + for (const auto & [flag, type] : type_flags) { + if (type < GGML_TYPE_COUNT && qs.ignored_types[type]) { + LLAMA_LOG_WARN("%s: %s pins type %s which is ignored by --target-exclude, keeping the pinned type\n", __func__, flag, ggml_type_name(type)); + } + } + } + + // Build tensor type map from --tensor-type + embedding + output flags + std::unordered_map locked_tensors; + for (size_t i = 0; i < tensors.size(); ++i) { + if (!metadata[i].allows_quantization) { continue; } + const char * name = ggml_get_name(tensors[i]->tensor); + ggml_type locked = tensor_type_override_for(qs, name); + if (metadata[i].category == TENSOR_CATEGORY_TOKEN_EMBD) { + const bool named = locked != GGML_TYPE_COUNT && std::strcmp(name, "per_layer_token_embd.weight") == 0; + if (params->token_embedding_type < GGML_TYPE_COUNT && !named) { + locked = params->token_embedding_type; + } else if (locked == GGML_TYPE_COUNT && qs.has_tied_embeddings && params->output_tensor_type < GGML_TYPE_COUNT) { + // tied embeddings take the output type, same as in llama_tensor_get_type_impl + locked = params->output_tensor_type; + } + } else if (metadata[i].category == TENSOR_CATEGORY_OUTPUT && params->output_tensor_type < GGML_TYPE_COUNT) { + locked = params->output_tensor_type; + } + + if (locked != GGML_TYPE_COUNT) { locked_tensors[name] = locked; } + } + + // do not allocate budget to unused kv tensors + for (size_t i = 0; i < tensors.size(); ++i) { + if (metadata[i].allows_quantization && unused_kv_tensors.count(metadata[i].name)) { + locked_tensors[metadata[i].name] = metadata[i].target_type; + } + } + + // get quantization type overrides targeting a given bits per weight budget + const auto * lt = locked_tensors.empty() ? nullptr : & locked_tensors; + bpw_overrides = target_bpw_type(ml, qs, tensors, mapped, values_data, activations_data, statistics_data, stats_schema, lt, nthread); + for (size_t i = 0; i < tensors.size(); ++i) { + const std::string name = ggml_get_name(tensors[i]->tensor); + auto it = bpw_overrides.find(name); + if (it != bpw_overrides.end()) { + metadata[i].target_type = it->second; + metadata[i].requires_imatrix = tensor_requires_imatrix(name.c_str(), metadata[i].target_type, ftype); + } + } + } else { + throw std::runtime_error(format("--target-bpw/--target-size require an imatrix but none was provided\n")); + } + } + int cur_split = -1; std::ofstream fout; auto close_ofstream = [&]() { @@ -1280,15 +3530,11 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: }; // no output file for --dry-run - if (!params->dry_run) { - new_ofstream(0); - } + if (!params->dry_run) { new_ofstream(0); } - // // main loop: iterate over all weights - // - for (size_t i = 0; i < tensors.size(); ++i) { + if (params->abort_callback && params->abort_callback(params->abort_callback_data)) { throw std::runtime_error("interrupted"); } const auto & weight = *tensors[i]; const auto & tm = metadata[i]; ggml_tensor * tensor = weight.tensor; @@ -1309,16 +3555,12 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: }; LLAMA_LOG_INFO("[%4d/%4d] %-36s - [%s], type = %6s, ", - ++idx, ml.n_tensors, - ggml_get_name(tensor), - llama_format_tensor_shape(tensor).c_str(), - ggml_type_name(tensor->type)); + ++idx, ml.n_tensors, ggml_get_name(tensor), llama_format_tensor_shape(tensor).c_str(), ggml_type_name(tensor->type)); const ggml_type cur_type = tensor->type; const ggml_type new_type = tm.target_type; - // If we've decided to quantize to the same type the tensor is already - // in then there's nothing to do. + // If we've decided to quantize to the same type the tensor is already in then there's nothing to do. bool quantize = cur_type != new_type; size_t new_size; @@ -1327,25 +3569,19 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // the --dry-run option calculates the final quantization size without quantizing if (quantize) { new_size = ggml_nrows(tensor) * ggml_row_size(new_type, tensor->ne[0]); - LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB (%s)\n", - tensor_size/1024.0/1024.0, - new_size/1024.0/1024.0, - ggml_type_name(new_type)); - if (!will_require_imatrix && tm.requires_imatrix) { - will_require_imatrix = true; - } + LLAMA_LOG_INFO("size = %.2f MiB -> %.2f MiB (%s)\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0, ggml_type_name(new_type)); + if (!will_require_imatrix && tm.requires_imatrix) { will_require_imatrix = true; } } else { new_size = tensor_size; - LLAMA_LOG_INFO("size = %8.3f MiB\n", new_size/1024.0/1024.0); + LLAMA_LOG_INFO("size = %.2f MiB\n", new_size/1024.0/1024.0); } total_size_org += tensor_size; total_size_new += new_size; - continue; } else { // no --dry-run, perform quantization if (!quantize) { new_size = tensor_size; - LLAMA_LOG_INFO("size = %8.3f MiB\n", tensor_size/1024.0/1024.0); + LLAMA_LOG_INFO("size = %.2f MiB\n", tensor_size/1024.0/1024.0); // copy in slabs of whole rows, so that each slab can be validated const size_t row_size = ggml_row_size(tensor->type, tensor->ne[0]); @@ -1357,16 +3593,16 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: } } else { const float * imatrix = nullptr; - if (imatrix_data) { - auto it = imatrix_data->find(tm.remapped_imatrix_name); - if (it == imatrix_data->end()) { - LLAMA_LOG_INFO("\n====== %s: did not find weights for %s\n", __func__, tensor->name); + if (values_data) { + auto it = values_data->find(tm.remapped_imatrix_name); + if (it == values_data->end()) { + LLAMA_LOG_INFO("\n====== %s: did not find imatrix data for %s\n", __func__, tensor->name); } else { if (it->second.size() == (size_t)tensor->ne[0]*tensor->ne[2]*tensor->ne[3]) { imatrix = it->second.data(); } else { LLAMA_LOG_INFO("\n====== %s: imatrix size %d is different from tensor size %d for %s\n", __func__, - int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name); + (int)it->second.size(), (int)tensor->ne[0] * (int)tensor->ne[2] * (int)tensor->ne[3], tensor->name); // this can happen when quantizing an old mixtral model with split tensors with a new incompatible imatrix // this is a significant error and it may be good idea to abort the process if this happens, @@ -1374,7 +3610,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // tok_embd should be ignored in this case, since it always causes this warning if (!tensor_name_match_token_embd(tensor->name)) { throw std::runtime_error(format("imatrix size %d is different from tensor size %d for %s", - int(it->second.size()), int(tensor->ne[0]*tensor->ne[2]*tensor->ne[3]), tensor->name)); + (int)it->second.size(), (int)tensor->ne[0] * (int)tensor->ne[2] * (int)tensor->ne[3], tensor->name)); } } } @@ -1391,7 +3627,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: throw std::runtime_error(format("requantizing from type %s is disabled", ggml_type_name(tensor->type))); } - LLAMA_LOG_INFO("converting to %s .. ", ggml_type_name(new_type)); + LLAMA_LOG_INFO("converting to %7s ", ggml_type_name(new_type)); fflush(stdout); const int64_t n_per_row = tensor->ne[0]; @@ -1405,7 +3641,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: const size_t bytes_per_row = row_size_src + row_size_dst + (tensor->type == GGML_TYPE_F32 ? 0 : n_per_row*sizeof(float)); const int64_t nrows_slab = std::max(1, std::min(nrows_total, max_buf_size/bytes_per_row)); - static const int64_t min_chunk_size = 32 * 512; + static constexpr int64_t min_chunk_size = 32 * 512; const int64_t chunk_size = (n_per_row >= min_chunk_size ? n_per_row : n_per_row * ((min_chunk_size + n_per_row - 1)/n_per_row)); // process rows across all experts in one pass to keep all threads busy @@ -1439,7 +3675,7 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: fout.write((const char *) work.data(), size_cur); new_size += size_cur; } - LLAMA_LOG_INFO("size = %8.2f MiB -> %8.2f MiB\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0); + LLAMA_LOG_INFO("size = %.2f MiB -> %.2f MiB\n", tensor_size/1024.0/1024.0, new_size/1024.0/1024.0); } total_size_org += tensor_size; total_size_new += new_size; @@ -1453,33 +3689,24 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std:: // unmap the tensor to free memory if (ml.use_mmap) { ml.unmap_weight(weight); } - - } // no --dry-run - } // main loop - - if (!params->dry_run) { - close_ofstream(); + } } - LLAMA_LOG_INFO("%s: model size = %8.2f MiB (%.2f BPW)\n", __func__, total_size_org/1024.0/1024.0, total_size_org*8.0/ml.n_elements); - LLAMA_LOG_INFO("%s: quant size = %8.2f MiB (%.2f BPW)\n", __func__, total_size_new/1024.0/1024.0, total_size_new*8.0/ml.n_elements); + if (!params->dry_run) { close_ofstream(); } + + LLAMA_LOG_INFO("%s: model size = %8.2f MiB (%7.4f BPW)\n", __func__, total_size_org/1024.0/1024.0, total_size_org*8.0/ml.n_elements); + LLAMA_LOG_INFO("%s: quant size = %8.2f MiB (%7.4f BPW)\n", __func__, total_size_new/1024.0/1024.0, total_size_new*8.0/ml.n_elements); if (!params->imatrix && params->dry_run && will_require_imatrix) { - LLAMA_LOG_WARN("%s: WARNING: dry run completed successfully, but actually completing this quantization will require an imatrix!\n", - __func__ - ); + LLAMA_LOG_WARN("%s: WARNING: dry run completed successfully, but actually completing this quantization will require an imatrix!\n", __func__); } if (qs.n_fallback > 0) { - LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n", - __func__, qs.n_fallback, ml.n_tensors); + LLAMA_LOG_WARN("%s: WARNING: %d of %d tensor(s) required fallback quantization\n", __func__, qs.n_fallback, ml.n_tensors); } } -// // interface implementation -// - llama_model_quantize_params llama_model_quantize_default_params() { llama_model_quantize_params result = { /*.nthread =*/ 0, @@ -1494,21 +3721,26 @@ llama_model_quantize_params llama_model_quantize_default_params() { /*.dry_run =*/ false, /*.imatrix =*/ nullptr, /*.kv_overrides =*/ nullptr, - /*.tensor_type =*/ nullptr, + /*.tt_overrides =*/ nullptr, /*.prune_layers =*/ nullptr, - /*.max_buf_size =*/ LLAMA_QUANT_MAX_BUF_SIZE + /*.max_buf_size =*/ LLAMA_QUANT_MAX_BUF_SIZE, + /*.activations =*/ nullptr, + /*.statistics =*/ nullptr, + /*.stats_schema =*/ nullptr, + /*.target_bpw =*/ -1.0f, + /*.target_size =*/ -1, + /*.state_file =*/ nullptr, + /*.target_exclude =*/ nullptr, + /*.abort_callback =*/ nullptr, + /*.abort_callback_data =*/ nullptr }; return result; } -uint32_t llama_model_quantize( - const char * fname_inp, - const char * fname_out, - const llama_model_quantize_params * params) { - try { - llama_model_quantize_impl(fname_inp, fname_out, params); - } catch (const std::exception & err) { +uint32_t llama_model_quantize(const char * fname_inp, const char * fname_out, const llama_model_quantize_params * params) { + try { llama_model_quantize_impl(fname_inp, fname_out, params); } + catch (const std::exception & err) { LLAMA_LOG_ERROR("%s: failed to quantize: %s\n", __func__, err.what()); return 1; } @@ -1516,32 +3748,25 @@ uint32_t llama_model_quantize( return 0; } -// // Helper functions for external tools exposed in llama-ext.h -// - -quantize_state_impl * llama_quant_init( - const llama_model * model, - const llama_model_quantize_params * params) { +quantize_state_impl * llama_quant_init(const llama_model * model, const llama_model_quantize_params * params) { return new quantize_state_impl(*model, params); } -void llama_quant_free(quantize_state_impl * qs) { +void llama_quant_free(const quantize_state_impl * qs) { delete qs; } llama_model * llama_quant_model_from_metadata(const llama_quant_model_desc * desc) { struct llama_model_params mparams = llama_model_default_params(); - auto arch = llm_arch_from_string(desc->architecture); + const auto arch = llm_arch_from_string(desc->architecture); auto * model = llama_model_create(arch, mparams); model->arch = arch; // infer llm_type: only LLM_TYPE_70B matters for quantization logic - if (model->arch == LLM_ARCH_LLAMA && desc->n_layer == 80 && desc->n_head != desc->n_head_kv) { - model->type = LLM_TYPE_70B; - } + if (model->arch == LLM_ARCH_LLAMA && desc->n_layer == 80 && desc->n_head != desc->n_head_kv) { model->type = LLM_TYPE_70B; } - model->hparams.n_embd = desc->n_embd; + model->hparams.n_embd = desc->n_embd; model->hparams.n_embd_head_k_full = desc->n_embd_head_k; model->hparams.n_embd_head_v_full = desc->n_embd_head_v; model->hparams.n_layer_all = desc->n_layer; @@ -1549,44 +3774,41 @@ llama_model * llama_quant_model_from_metadata(const llama_quant_model_desc * des model->hparams.n_expert = desc->n_expert; for (uint32_t i = 0; i < desc->n_layer; i++) { - model->hparams.n_head_arr[i] = desc->n_head; + model->hparams.n_head_arr[i] = desc->n_head; model->hparams.n_head_kv_arr[i] = desc->n_head_kv; - model->hparams.n_ff_arr[i] = desc->n_ff; + model->hparams.n_ff_arr[i] = desc->n_ff; } return model; } -bool llama_quant_tensor_allows_quantization( - const quantize_state_impl * qs, - const ggml_tensor * tensor) { +bool llama_quant_tensor_allows_quantization(const quantize_state_impl * qs, const ggml_tensor * tensor) { return tensor_allows_quantization(qs->params, qs->model.arch, tensor); } void llama_quant_compute_types( - quantize_state_impl * qs, - llama_ftype ftype, - ggml_tensor ** tensors, - ggml_type * result_types, - size_t n_tensors) { + quantize_state_impl * qs, + const llama_ftype ftype, + ggml_tensor ** tensors, + ggml_type * result_types, + const size_t n_tensors +) { // reset per-computation state - qs->n_attention_wv = 0; - qs->n_ffn_down = 0; - qs->n_ffn_gate = 0; - qs->n_ffn_up = 0; - qs->i_attention_wv = 0; - qs->i_ffn_down = 0; - qs->i_ffn_gate = 0; - qs->i_ffn_up = 0; - qs->n_fallback = 0; - qs->has_imatrix = false; + qs->n_attention_wv = 0; + qs->n_ffn_down = 0; + qs->n_ffn_gate = 0; + qs->n_ffn_up = 0; + qs->i_attention_wv = 0; + qs->i_ffn_down = 0; + qs->i_ffn_gate = 0; + qs->i_ffn_up = 0; + qs->n_fallback = 0; + qs->has_imatrix = false; qs->has_tied_embeddings = true; // build metadata from tensor names std::vector metadata(n_tensors); - for (size_t i = 0; i < n_tensors; i++) { - metadata[i].name = ggml_get_name(tensors[i]); - } + for (size_t i = 0; i < n_tensors; i++) { metadata[i].name = ggml_get_name(tensors[i]); } // initialize counters and categories init_quantize_state_counters(*qs, metadata); @@ -1595,10 +3817,8 @@ void llama_quant_compute_types( llama_model_quantize_params local_params = *qs->params; local_params.ftype = ftype; - ggml_type default_type = llama_ftype_get_default_type(ftype); + const ggml_type default_type = llama_ftype_get_default_type(ftype); // compute types - for (size_t i = 0; i < n_tensors; i++) { - result_types[i] = llama_tensor_get_type(*qs, &local_params, tensors[i], default_type, metadata[i]); - } + for (size_t i = 0; i < n_tensors; i++) { result_types[i] = llama_tensor_get_type(*qs, &local_params, tensors[i], default_type, metadata[i]); } } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5b997e91bbcf..2e0edcb497c2 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -350,6 +350,7 @@ llama_build_and_test(test-thread-safety.cpp LABEL "main backend" ARGS -m "${MO set_tests_properties(test-thread-safety PROPERTIES FIXTURES_REQUIRED test-download-model) llama_build_and_test(test-arg-parser.cpp LABEL behavior) +llama_build_and_test(test-quantize-target.cpp LABEL "main behavior backend" LINK llama) llama_build_and_test(test-model-resolution.cpp LABEL behavior) # the test serves its repos from an httplib server, and the library links it privately target_link_libraries(test-model-resolution PRIVATE cpp-httplib) diff --git a/tests/test-quantize-target.cpp b/tests/test-quantize-target.cpp new file mode 100644 index 000000000000..9b11584048ab --- /dev/null +++ b/tests/test-quantize-target.cpp @@ -0,0 +1,938 @@ +#include "testing.h" + +#include "ggml-backend.h" +#include "ggml-cpp.h" +#include "gguf.h" +#include "llama-cpp.h" +#include "llama.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#endif + +static const uint32_t n_vocab = 256; +static const uint32_t n_embd = 256; +static const uint32_t n_ff = 512; +static const uint32_t n_head = 2; +static const uint32_t n_layer = 4; +static const float target_bpw = 4.5f; +static bool verbose = false; + +static void set_tensor_data(ggml_tensor * tensor, void * /*userdata*/) { + std::mt19937 gen(std::hash{}(tensor->name)); + std::normal_distribution dis(0.0f, 0.1f); + std::vector data(ggml_nelements(tensor)); + for (float & v : data) { v = dis(gen); } + ggml_backend_tensor_set(tensor, data.data(), 0, ggml_nbytes(tensor)); +} + +// test model +static bool save_model(const std::string & fname) { + gguf_context_ptr meta(gguf_init_empty()); + gguf_set_val_str(meta.get(), "general.architecture", "llama"); + gguf_set_val_u32(meta.get(), "llama.vocab_size", n_vocab); + gguf_set_val_u32(meta.get(), "llama.context_length", 256); + gguf_set_val_u32(meta.get(), "llama.embedding_length", n_embd); + gguf_set_val_u32(meta.get(), "llama.feed_forward_length", n_ff); + gguf_set_val_u32(meta.get(), "llama.block_count", n_layer); + gguf_set_val_u32(meta.get(), "llama.attention.head_count", n_head); + gguf_set_val_u32(meta.get(), "llama.attention.head_count_kv", n_head); + gguf_set_val_f32(meta.get(), "llama.attention.layer_norm_rms_epsilon", 1e-5f); + gguf_set_val_str(meta.get(), "tokenizer.ggml.model", "none"); + + llama_model_params mparams = llama_model_default_params(); + ggml_backend_dev_t devs[] = { nullptr }; + mparams.devices = devs; + + llama_model_ptr model(llama_model_init_from_user(meta.get(), set_tensor_data, nullptr, mparams)); + if (!model) { return false; } + llama_model_save_to_file(model.get(), fname.c_str()); + return true; +} + +// test imatrix +struct imatrix_data { + std::vector names; + std::vector> values; + std::vector> activations; + std::vector> statistics; + std::vector stats_schema; +}; + +// stats schema +static const std::vector default_stats_schema = { + "sum_sq", "mean", "elements", "std_deviation", "skewness", "kurtosis", "gain", "h_norm", "l2_dist", "cossim", "pearson", "covariance" +}; + +static std::vector make_stats(std::mt19937 & gen, const int64_t n_per_row) { + std::uniform_real_distribution u(0.0f, 1.0f); + return { + 100.0f + 100.0f * u(gen), // sum_sq + 0.01f * (u(gen) - 0.5f), // mean + (float) n_per_row, // elements + 1.0f + u(gen), // std_deviation + u(gen) - 0.5f, // skewness + 3.0f * u(gen), // kurtosis + 1.0f + u(gen), // gain + 80.0f + 20.0f * u(gen), // h_norm + 10.0f * u(gen), // l2_dist + 0.5f + 0.5f * u(gen), // cossim + 0.5f + 0.5f * u(gen), // pearson + u(gen), // covariance + }; +} + +static imatrix_data make_imatrix(const std::string & fname_model, const uint32_t seed) { + imatrix_data im; + + ggml_context * ctx_meta = nullptr; + const gguf_init_params params = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta }; + gguf_context_ptr ctx(gguf_init_from_file(fname_model.c_str(), params)); + ggml_context_ptr meta(ctx_meta); + if (!ctx) { return im; } + + std::mt19937 gen(seed); + std::uniform_real_distribution u(0.0f, 1.0f); + for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) { + const char * name = gguf_get_tensor_name(ctx.get(), i); + const ggml_tensor * tensor = ggml_get_tensor(meta.get(), name); + if (ggml_n_dims(tensor) < 2 || strcmp(name, "token_embd.weight") == 0) { continue; } + + const int64_t n_per_row = tensor->ne[0]; + std::vector values(n_per_row); + std::vector activations(n_per_row); + for (int64_t j = 0; j < n_per_row; j++) { + activations[j] = u(gen) - 0.5f; + values[j] = activations[j] * activations[j] + std::exp(2.0f * u(gen) - 1.0f); + } + + im.names.push_back(name); + im.values.push_back(std::move(values)); + im.activations.push_back(std::move(activations)); + im.statistics.push_back(make_stats(gen, n_per_row)); + } + + im.stats_schema = default_stats_schema; + + return im; +} + +static std::vector imatrix_list(const imatrix_data & im, const std::vector> & data) { + std::vector list; + for (size_t i = 0; i < im.names.size(); i++) { + if (data[i].empty()) { continue; } + list.push_back({ im.names[i].c_str(), data[i].data(), data[i].size() }); + } + + list.push_back({ nullptr, nullptr, 0 }); + + return list; +} + +struct quant_run { + uint32_t rc = 1; // 0 when quantization succeeds and output is processed + std::string log; + std::map types; + size_t n_bytes = 0; // tensor data + size_t n_elements = 0; + size_t file_size = 0; +}; + +static void log_callback(ggml_log_level /*level*/, const char * text, void * user_data) { + if (user_data) { static_cast(user_data)->append(text); } + if (verbose) { fputs(text, stderr); } +} + +static quant_run quantize(const std::string & fname_inp, const std::string & fname_out, const imatrix_data & im, llama_model_quantize_params params) { + const auto values = imatrix_list(im, im.values); + const auto activations = imatrix_list(im, im.activations); + const auto statistics = imatrix_list(im, im.statistics); + std::vector stats_schema; + for (const auto & name : im.stats_schema) { stats_schema.push_back(name.c_str()); } + stats_schema.push_back(nullptr); + params.imatrix = values.data(); + params.activations = activations.data(); + params.statistics = statistics.data(); + params.stats_schema = im.stats_schema.empty() ? nullptr : stats_schema.data(); + + quant_run run; + // clear previous run's output + std::filesystem::remove(fname_out); + llama_log_set(log_callback, &run.log); + run.rc = llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ¶ms); + llama_log_set(log_callback, nullptr); + if (run.rc != 0) { return run; } + + ggml_context * ctx_meta = nullptr; + const gguf_init_params gparams = { /*.no_alloc =*/ true, /*.ctx =*/ &ctx_meta }; + gguf_context_ptr ctx(gguf_init_from_file(fname_out.c_str(), gparams)); + ggml_context_ptr meta(ctx_meta); + if (!ctx) { + run.rc = 1; + return run; + } + + for (int64_t i = 0; i < gguf_get_n_tensors(ctx.get()); i++) { + const char * name = gguf_get_tensor_name(ctx.get(), i); + run.types[name] = gguf_get_tensor_type(ctx.get(), i); + run.n_bytes += gguf_get_tensor_size(ctx.get(), i); + run.n_elements += ggml_nelements(ggml_get_tensor(meta.get(), name)); + } + + run.file_size = std::filesystem::file_size(fname_out); + + return run; +} + +static size_t count_matches(const std::string & log, const std::string & text) { + size_t n = 0; + for (size_t pos = log.find(text); pos != std::string::npos; pos = log.find(text, pos + text.size())) { n++; } + + return n; +} + +static size_t logged_number(const std::string & log, const std::string & text) { + const size_t pos = log.find(text); + return pos == std::string::npos ? SIZE_MAX : (size_t) std::strtoull(log.c_str() + pos + text.size(), nullptr, 10); +} + +static size_t count_type(const quant_run & run, const ggml_type type) { + size_t n = 0; + for (const auto & it : run.types) { n += it.second == type; } + + return n; +} + +static size_t count_type_changes(const quant_run & a, const quant_run & b) { + size_t n = 0; + for (const auto & it : a.types) { + const auto other = b.types.find(it.first); + n += other == b.types.end() || other->second != it.second; + } + + return n; +} + +// the type name of a tensor in a run's output, or "none" if the output has no such tensor +static std::string type_name_of(const quant_run & run, const std::string & name) { + const auto it = run.types.find(name); + return it == run.types.end() ? "none" : ggml_type_name(it->second); +} + +// tensor quantization mix rows +static std::vector mix_rows(const quant_run & run) { + std::vector rows; + for (size_t pos = run.log.find("\terror: "); pos != std::string::npos; pos = run.log.find("\terror: ", pos + 1)) { + const size_t start = run.log.rfind('\n', pos) + 1; + rows.push_back(run.log.substr(start, run.log.find('\n', pos) - start)); + } + + return rows; +} + +static size_t count_row_changes(const quant_run & a, const quant_run & b) { + const std::vector rows_a = mix_rows(a); + const std::vector rows_b = mix_rows(b); + if (rows_a.empty() || rows_a.size() != rows_b.size()) { return SIZE_MAX; } + + size_t n = 0; + for (size_t i = 0; i < rows_a.size(); i++) { n += rows_a[i] != rows_b[i]; } + + return n; +} + +static std::string read_file(const std::string & fname) { + std::ifstream file(fname, std::ios::binary); + return std::string(std::istreambuf_iterator(file), std::istreambuf_iterator()); +} + +static void write_file(const std::string & fname, const std::string & data) { + std::ofstream file(fname, std::ios::binary); + file << data; +} + +static const size_t state_header_size = 24; // magic, model id, tensor count +static const size_t state_entry_size = 28; // candidate count, choice, min and max bpw, elements +static const size_t state_candidate_size = 24; // type, bpw, bytes, error + +// offset of the first tensor's candidate count; 0 if the checkpoint holds no candidate +static size_t first_count_offset(const std::string & state) { + uint32_t len = 0; + if (state.size() < state_header_size + sizeof(len)) { return 0; } + memcpy(&len, state.data() + state_header_size, sizeof(len)); + const size_t offset = state_header_size + sizeof(len) + len; + + return state.size() >= offset + state_entry_size + state_candidate_size ? offset : 0; +} + +struct fixture { + std::string fname_model; + std::string fname_out; + std::string fname_state; + imatrix_data im; + quant_run base; +}; + +// first run parameters +static llama_model_quantize_params base_params(const fixture & f) { + llama_model_quantize_params params = llama_model_quantize_default_params(); + params.nthread = 4; + params.target_bpw = target_bpw; + params.state_file = f.fname_state.c_str(); + + return params; +} + +static std::string sibling_path(const fixture & f, const std::string & name) { + return (std::filesystem::path(f.fname_state).parent_path() / name).string(); +} + +static void test_target_bpw(testing & t, const fixture & f) { + const double bpw = 8.0 * f.base.n_bytes / f.base.n_elements; + t.log("final bpw " + std::to_string(bpw)); + t.assert_true("bpw does not exceed the target", bpw <= target_bpw); + t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05); +} + +static void test_state_checkpoint(testing & t, const fixture & f) { + const size_t n_scored = count_matches(f.base.log, "processing tensor"); + const std::string n_tensors = std::to_string(n_scored) + " tensors"; + t.assert_true("first run scores tensors", n_scored > 0); + t.assert_equal("first run saves the checkpoint", (size_t) 1, count_matches(f.base.log, "saved target progress for " + n_tensors + " to " + f.fname_state)); + + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, base_params(f)); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("second run loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)")); + t.assert_equal("second run scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_equal("tensors whose type changed", (size_t) 0, count_type_changes(f.base, run)); +} + +static void test_target_size(testing & t, const fixture & f) { + llama_model_quantize_params params = base_params(f); + params.target_bpw = -1.0f; + params.target_size = (int64_t) f.base.file_size * 9 / 10; + + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + + const int64_t diff = (int64_t) run.file_size - params.target_size; + t.log("file size " + std::to_string(run.file_size) + ", " + std::to_string(diff) + " bytes from the target"); + t.assert_true("the file is within 8 KiB of the target", std::abs(diff) <= 8 * 1024); +} + +static void test_excluded_type(testing & t, const fixture & f) { + ggml_type excluded = GGML_TYPE_COUNT; + for (const auto & it : f.base.types) { + if (it.second != GGML_TYPE_F32 && (excluded == GGML_TYPE_COUNT || count_type(f.base, it.second) > count_type(f.base, excluded))) { + excluded = it.second; + } + } + + t.assert_true("first run selects a type", excluded != GGML_TYPE_COUNT); + if (excluded == GGML_TYPE_COUNT) { return; } + t.log(std::string("excluding ") + ggml_type_name(excluded) + ", the type of " + std::to_string(count_type(f.base, excluded)) + " tensors"); + + const ggml_type exclude[] = { excluded, GGML_TYPE_COUNT }; + llama_model_quantize_params params = base_params(f); + params.target_exclude = exclude; + + params.state_file = nullptr; + const quant_run scored = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, scored.rc); + t.assert_equal("scored with excluded types, tensors of the excluded type", (size_t) 0, count_type(scored, excluded)); + + params.state_file = f.fname_state.c_str(); + const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors"; + const quant_run loaded = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, loaded.rc); + t.assert_equal("run loads the checkpoint", (size_t) 1, count_matches(loaded.log, "using " + f.fname_state + " (data for " + n_tensors + " loaded)")); + t.assert_equal("run scores no tensor", (size_t) 0, count_matches(loaded.log, "processing tensor")); + t.assert_equal("loaded from checkpoint, tensors of the excluded type", (size_t) 0, count_type(loaded, excluded)); + t.assert_equal("run warns that the checkpoint is not saved", (size_t) 1, count_matches(loaded.log, "state checkpoint cannot be saved while --target-exclude is active")); + t.assert_equal("checkpoint is not saved while types are excluded", (size_t) 0, count_matches(loaded.log, "saved target progress")); +} + +static void test_unknown_type(testing & t, const fixture & f) { + std::string state = read_file(f.fname_state); + const size_t offset = first_count_offset(state); + t.assert_true("first run's checkpoint holds a candidate", offset > 0); + if (offset == 0) { return; } + + // type 4 was Q4_2; within ggml_type range but invalid + const int32_t type = 4; + memcpy(&state[offset + state_entry_size], &type, sizeof(type)); + const std::string fname = sibling_path(f, "unknown.bpw_state"); + write_file(fname, state); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("unknown type is reported", (size_t) 1, count_matches(run.log, "candidate type is not in the selection pool, ignoring state file")); + t.assert_equal("unknown checkpoint is not loaded", (size_t) 0, count_matches(run.log, "using " + fname)); + t.assert_equal("unknown checkpoint is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor")); + t.assert_equal("scored again, tensors whose type changed", (size_t) 0, count_type_changes(f.base, run)); +} + +static void test_zero_candidates(testing & t, const fixture & f) { + std::string state = read_file(f.fname_state); + const size_t offset = first_count_offset(state); + t.assert_true("the first run's checkpoint holds a candidate", offset > 0); + if (offset == 0) { return; } + + // drop the first tensor's candidates + uint64_t n = 0; + memcpy(&n, &state[offset], sizeof(n)); + state.erase(offset + state_entry_size, n * state_candidate_size); + n = 0; + memcpy(&state[offset], &n, sizeof(n)); + const std::string fname = sibling_path(f, "zero.bpw_state"); + write_file(fname, state); + + // with a type excluded, an empty candidate list that is loaded fails the call instead of crashing the test + const ggml_type exclude[] = { GGML_TYPE_IQ1_S, GGML_TYPE_COUNT }; + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.target_exclude = exclude; + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("empty candidate list is reported", (size_t) 1, count_matches(run.log, "candidate count out of range, ignoring state file")); + t.assert_equal("checkpoint with an empty candidate list is not loaded", (size_t) 0, count_matches(run.log, "using " + fname)); + t.assert_equal("checkpoint with an empty candidate list is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor")); +} + +static void test_truncated(testing & t, const fixture & f) { + const std::string state = read_file(f.fname_state); + const size_t offset = first_count_offset(state); + t.assert_true("first run's checkpoint has a candidate", offset > 0); + if (offset == 0) { return; } + + // cut before the first candidate count, then before the first candidate type + const std::string fname = sibling_path(f, "truncated.bpw_state"); + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + write_file(fname, state.substr(0, offset)); + const quant_run at_count = quantize(f.fname_model, f.fname_out, f.im, params); + write_file(fname, state.substr(0, offset + state_entry_size)); + const quant_run at_type = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, at_count.rc); + t.assert_equal("checkpoint cut before a candidate count is reported as truncated", (size_t) 1, count_matches(at_count.log, "state file truncated or read error, ignoring")); + t.assert_equal("quantize succeeds", 0u, at_type.rc); + t.assert_equal("checkpoint cut before a candidate type is reported as truncated", (size_t) 1, count_matches(at_type.log, "state file truncated or read error, ignoring")); +} + +static void test_missing_dir(testing & t, const fixture & f) { + const std::string dir = sibling_path(f, "no-such-dir"); + const std::string fname = (std::filesystem::path(dir) / "model.bpw_state").string(); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("path in missing directory fails", 1u, run.rc); + t.assert_equal("path in missing directory is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": ")); + t.assert_equal("path in missing directory stops execution before scoring", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_true("missing directory is not created", !std::filesystem::exists(dir)); +} + +static void test_unreadable_file(testing & t, const fixture & f) { +#ifdef _WIN32 + GGML_UNUSED(f); + t.skip("POSIX permissions only"); +#else + namespace fs = std::filesystem; + std::error_code ec; + const std::string fname = sibling_path(f, "locked.bpw_state"); + write_file(fname, "forbidden"); + // write-only, so that a probe that opens the file for writing could still damage it + fs::permissions(fname, fs::perms::owner_write, ec); + if (std::ifstream(fname).good()) { + fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec); + t.skip("the file can still be read, as by root"); + return; + } + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + const bool kept_perms = fs::status(fname, ec).permissions() == fs::perms::owner_write; + fs::permissions(fname, fs::perms::owner_read | fs::perms::owner_write, ec); + t.assert_equal("an unreadable file fails the call", 1u, run.rc); + t.assert_equal("an unreadable file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": ")); + t.assert_equal("an unreadable file stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_true("an unreadable file keeps its permissions", kept_perms); + t.assert_true("an unreadable file keeps its content", read_file(fname) == "forbidden"); +#endif +} + +static void test_directory_path(testing & t, const fixture & f) { + const std::string fname = sibling_path(f, "dir.bpw_state"); + std::filesystem::create_directory(fname); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("a directory instead of a file fails the call", 1u, run.rc); + t.assert_equal("a directory instead of a file is reported", (size_t) 1, count_matches(run.log, "failed to open " + fname + ": ")); + t.assert_equal("a directory stops the run before scoring", (size_t) 0, count_matches(run.log, "processing tensor")); + t.assert_true("the directory is left as it was", std::filesystem::is_directory(fname) && std::filesystem::is_empty(fname)); +} + +static void test_save_error(testing & t, const fixture & f) { + const std::string fname = sibling_path(f, "unsaved.bpw_state"); + write_file(fname, read_file(f.fname_state)); + std::filesystem::create_directory(fname + ".tmp"); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("a failed save is reported", (size_t) 1, count_matches(run.log, "failed to save progress to " + fname + ".tmp (open error)")); + t.assert_equal("a failed save logs no saved checkpoint", (size_t) 0, count_matches(run.log, "saved target progress")); +} + +static void test_imatrix_swap(testing & t, const fixture & f) { + const imatrix_data im = make_imatrix(f.fname_model, 4321); + const std::string fname = sibling_path(f, "swap.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = nullptr; + const quant_run fresh = quantize(f.fname_model, f.fname_out, im, params); + params.state_file = fname.c_str(); + const quant_run reused = quantize(f.fname_model, f.fname_out, im, params); + t.log(std::to_string(count_type_changes(f.base, fresh)) + " tensors change type with the other imatrix"); + t.assert_equal("quantize succeeds", 0u, fresh.rc); + t.assert_equal("quantize succeeds", 0u, reused.rc); + t.assert_equal("a checkpoint from another imatrix is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint from another imatrix is scored again", count_matches(f.base.log, "processing tensor"), count_matches(reused.log, "processing tensor")); + t.assert_equal("scored again with another imatrix, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused)); +} + +static void test_imatrix_parts(testing & t, const fixture & f) { + // one float doubled in one list at a time + auto check = [&](const std::string & part, const imatrix_data & im) { + const std::string fname = sibling_path(f, part + ".bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run run = quantize(f.fname_model, f.fname_out, im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("a checkpoint from other " + part + " is reported", (size_t) 1, count_matches(run.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint from other " + part + " is scored again", count_matches(f.base.log, "processing tensor"), count_matches(run.log, "processing tensor")); + }; + + imatrix_data im = f.im; + im.values[0][0] *= 2.0f; + check("values", im); + + im = f.im; + im.activations[0][0] *= 2.0f; + check("activations", im); + + im = f.im; + im.statistics[0][0] *= 2.0f; + check("statistics", im); +} + +static void test_imatrix_order(testing & t, const fixture & f) { + // the same imatrix data, passed in reverse order + imatrix_data im = f.im; + std::reverse(im.names.begin(), im.names.end()); + std::reverse(im.values.begin(), im.values.end()); + std::reverse(im.activations.begin(), im.activations.end()); + std::reverse(im.statistics.begin(), im.statistics.end()); + const std::string fname = sibling_path(f, "reversed.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const std::string n_tensors = std::to_string(count_matches(f.base.log, "processing tensor")) + " tensors"; + const quant_run run = quantize(f.fname_model, f.fname_out, im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("the same imatrix in another order loads the checkpoint", (size_t) 1, count_matches(run.log, "using " + fname + " (data for " + n_tensors + " loaded)")); + t.assert_equal("the same imatrix in another order scores no tensor", (size_t) 0, count_matches(run.log, "processing tensor")); +} + +static void test_pruned_layer(testing & t, const fixture & f) { + // pruning a block renumbers the ones after it + const int32_t prune[] = { 1, -1 }; + const std::string fname = sibling_path(f, "pruned.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.prune_layers = prune; + params.state_file = nullptr; + const quant_run fresh = quantize(f.fname_model, f.fname_out, f.im, params); + params.state_file = fname.c_str(); + const quant_run reused = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("quantize succeeds", 0u, fresh.rc); + t.assert_equal("quantize succeeds", 0u, reused.rc); + t.assert_equal("a checkpoint without pruning is reported", (size_t) 1, count_matches(reused.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint without pruning is scored again", count_matches(fresh.log, "processing tensor"), count_matches(reused.log, "processing tensor")); + t.assert_equal("scored again with a pruned block, tensors whose type differs from a fresh run", (size_t) 0, count_type_changes(fresh, reused)); + + // another block pruned, reusing the checkpoint saved for block 1 + const int32_t prune_other[] = { 2, -1 }; + params.prune_layers = prune_other; + const quant_run other = quantize(f.fname_model, f.fname_out, f.im, params); + t.assert_equal("the pruned run saves its checkpoint", (size_t) 1, count_matches(reused.log, "saved target progress")); + t.assert_equal("quantize succeeds", 0u, other.rc); + t.assert_equal("a checkpoint for another pruned block is reported", (size_t) 1, count_matches(other.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("a checkpoint for another pruned block is scored again", count_matches(fresh.log, "processing tensor"), count_matches(other.log, "processing tensor")); +} + +static void test_stats_order(testing & t, const fixture & f) { + // stats in reverse order + imatrix_data im = f.im; + std::reverse(im.stats_schema.begin(), im.stats_schema.end()); + for (auto & stats : im.statistics) { std::reverse(stats.begin(), stats.end()); } + + llama_model_quantize_params params = base_params(f); + params.state_file = nullptr; + const quant_run run = quantize(f.fname_model, f.fname_out, im, params); + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_equal("statistics in different order", (size_t) 0, count_matches(run.log, "skipping CNIF")); + t.assert_equal("statistics in different order, rows that changed", (size_t) 0, count_row_changes(f.base, run)); +} + +static void test_stats_missing(testing & t, const fixture & f) { + // tensor whose stats vector is cut short or left out + const size_t k = std::find(f.im.names.begin(), f.im.names.end(), "blk.1.ffn_down.weight") - f.im.names.begin(); + t.assert_true("imatrix has blk.1.ffn_down.weight", k < f.im.names.size()); + if (k == f.im.names.size()) { return; } + + // pearson under another name + imatrix_data renamed = f.im; + std::replace(renamed.stats_schema.begin(), renamed.stats_schema.end(), std::string("pearson"), std::string("spearman")); + const std::string fname = sibling_path(f, "renamed.bpw_state"); + write_file(fname, read_file(f.fname_state)); + + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + const quant_run missing = quantize(f.fname_model, f.fname_out, renamed, params); + + // no names + imatrix_data unnamed = f.im; + unnamed.stats_schema.clear(); + params.state_file = nullptr; + const quant_run no_names = quantize(f.fname_model, f.fname_out, unnamed, params); + + // stats vector cut before pearson + imatrix_data cut = f.im; + cut.statistics[k].resize(10); + const quant_run short_stats = quantize(f.fname_model, f.fname_out, cut, params); + imatrix_data dropped = f.im; + dropped.statistics[k].clear(); + const quant_run no_stats = quantize(f.fname_model, f.fname_out, dropped, params); + + const size_t n_changed = count_row_changes(f.base, missing); + t.log(std::to_string(n_changed) + " mix rows change without CNIF"); + t.assert_equal("quantize succeeds", 0u, missing.rc); + t.assert_true("missing metric changes the mix", n_changed > 0 && n_changed != SIZE_MAX); + t.assert_equal("missing metric is reported", (size_t) 1, count_matches(missing.log, "statistics have no pearson metric, skipping CNIF")); + t.assert_equal("checkpoint with different statistics names is reported", (size_t) 1, count_matches(missing.log, "state file does not match this model, imatrix or pruned layers, ignoring")); + t.assert_equal("checkpoint with different statistics names is scored again", count_matches(f.base.log, "processing tensor"), count_matches(missing.log, "processing tensor")); + t.assert_equal("quantize succeeds", 0u, no_names.rc); + t.assert_equal("statistics without names are reported", (size_t) 1, count_matches(no_names.log, "statistics have no sum_sq metric, skipping CNIF")); + t.assert_equal("statistics without names log one line", (size_t) 1, count_matches(no_names.log, "skipping CNIF")); + t.assert_equal("statistics without names, rows that differ from a missing metric", (size_t) 0, count_row_changes(missing, no_names)); + t.assert_equal("quantize succeeds", 0u, short_stats.rc); + t.assert_equal("a short stats vector is not reported as a missing metric", (size_t) 0, count_matches(short_stats.log, "skipping CNIF")); + t.assert_equal("quantize succeeds", 0u, no_stats.rc); + t.assert_equal("a short stats vector, rows that differ from a left-out one", (size_t) 0, count_row_changes(no_stats, short_stats)); +} + +// counts its calls, and asks to stop at call number stop_at only +struct terminate_probe { + size_t n_calls = 0; + size_t stop_at = 0; +}; + +static bool terminate_at(void * data) { + auto * probe = static_cast(data); + return ++probe->n_calls == probe->stop_at; +} + +static void test_abort_callback(testing & t, const fixture & f) { + // full scoring no interruptions + terminate_probe counter; + llama_model_quantize_params params = base_params(f); + params.state_file = nullptr; + params.abort_callback = terminate_at; + params.abort_callback_data = &counter; + const quant_run counted = quantize(f.fname_model, f.fname_out, f.im, params); + + // interrupt at half the calls + terminate_probe stopper; + stopper.stop_at = counter.n_calls / 2; + const std::string fname = sibling_path(f, "interrupted.bpw_state"); + params.state_file = fname.c_str(); + params.abort_callback_data = &stopper; + const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params); + const bool stopped_wrote = std::filesystem::exists(f.fname_out); + params.abort_callback = nullptr; + const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params); + + const size_t n_total = count_matches(f.base.log, "processing tensor"); + const size_t n_saved = logged_number(stopped.log, "interrupted, saving progress for "); + t.log(std::to_string(n_saved) + " of " + std::to_string(n_total) + " tensors scored before the stop at call " + std::to_string(stopper.stop_at) + " of " + std::to_string(counter.n_calls)); + t.assert_equal("quantize succeeds", 0u, counted.rc); + t.assert_equal("a callback that never asks to stop, mix rows that changed", (size_t) 0, count_row_changes(f.base, counted)); + t.assert_equal("the interrupted call fails", 1u, stopped.rc); + t.assert_equal("the stop is reported", (size_t) 1, count_matches(stopped.log, "failed to quantize: interrupted")); + t.assert_true("the stop comes part way through the scoring", n_saved > 0 && n_saved < n_total); + t.assert_equal("the stopped run saves what it scored", (size_t) 1, count_matches(stopped.log, "saved target progress for " + std::to_string(n_saved) + " tensors to " + fname)); + t.assert_true("the stopped run writes no output", !stopped_wrote); + t.assert_equal("quantize succeeds", 0u, resumed.rc); + t.assert_equal("the resumed run loads the saved tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_saved) + " tensors loaded)")); + t.assert_equal("the resumed run scores the rest", n_total - n_saved, count_matches(resumed.log, "processing tensor")); + t.assert_equal("resumed, mix rows that differ from the first run", (size_t) 0, count_row_changes(f.base, resumed)); + + // without a target, the main loop calls it once per tensor + terminate_probe loop_stopper; + loop_stopper.stop_at = 2; + llama_model_quantize_params plain = llama_model_quantize_default_params(); + plain.nthread = 4; + plain.abort_callback = terminate_at; + plain.abort_callback_data = &loop_stopper; + const quant_run main_loop = quantize(f.fname_model, f.fname_out, f.im, plain); + t.assert_equal("a stop in the main loop fails the call", 1u, main_loop.rc); + t.assert_equal("a stop in the main loop is reported", (size_t) 1, count_matches(main_loop.log, "failed to quantize: interrupted")); + t.assert_equal("the main loop stops at the call that asks", (size_t) 2, loop_stopper.n_calls); +} + +static void test_interrupt_first_call(testing & t, const fixture & f) { + // a copy of the checkpoint, stopped at the first call, before the workers read it back + const size_t n_total = count_matches(f.base.log, "processing tensor"); + const std::string fname = sibling_path(f, "first-call.bpw_state"); + write_file(fname, read_file(f.fname_state)); + terminate_probe stopper; + stopper.stop_at = 1; + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.abort_callback = terminate_at; + params.abort_callback_data = &stopper; + const quant_run stopped = quantize(f.fname_model, f.fname_out, f.im, params); + params.abort_callback = nullptr; + const quant_run resumed = quantize(f.fname_model, f.fname_out, f.im, params); + + t.assert_equal("the stopped call fails", 1u, stopped.rc); + t.assert_equal("the checkpoint keeps its tensors", (size_t) 1, count_matches(resumed.log, "using " + fname + " (data for " + std::to_string(n_total) + " tensors loaded)")); + t.assert_equal("the next run scores nothing", (size_t) 0, count_matches(resumed.log, "processing tensor")); +} + +#ifndef _WIN32 +static void app_signal_handler(int, siginfo_t *, void *) {} + +// true when both have the same handler, flags and mask +static bool same_action(const struct sigaction & a, const struct sigaction & b) { + if (a.sa_flags != b.sa_flags) { return false; } + if ((a.sa_flags & SA_SIGINFO) ? a.sa_sigaction != b.sa_sigaction : a.sa_handler != b.sa_handler) { return false; } + for (int sig = 1; sig < NSIG; sig++) { + if (sigismember(&a.sa_mask, sig) != sigismember(&b.sa_mask, sig)) { return false; } + } + + return true; +} + +// read SIGINT and SIGTERM disposition +struct disposition_probe { + size_t n_calls = 0; + struct sigaction during[2]; +}; + +static bool probe_dispositions(void * data) { + auto * probe = static_cast(data); + if (probe->n_calls++ == 0) { + sigaction(SIGINT, nullptr, &probe->during[0]); + sigaction(SIGTERM, nullptr, &probe->during[1]); + } + + return false; +} +#endif + +static void test_signal_handlers(testing & t, const fixture & f) { +#ifdef _WIN32 + GGML_UNUSED(f); + t.skip("POSIX signals only"); +#else + struct sigaction app = {}; + app.sa_sigaction = app_signal_handler; + app.sa_flags = SA_SIGINFO; + sigemptyset(&app.sa_mask); + sigaddset(&app.sa_mask, SIGTERM); + + const int signals[] = { SIGINT, SIGTERM }; + struct sigaction prev[2], before[2], after[2]; + for (int i = 0; i < 2; i++) { + sigaction(signals[i], &app, &prev[i]); + sigaction(signals[i], nullptr, &before[i]); + } + + // checkpoint exists, should not score + const std::string fname = sibling_path(f, "signals.bpw_state"); + write_file(fname, read_file(f.fname_state)); + disposition_probe probe = {}; + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.abort_callback = probe_dispositions; + params.abort_callback_data = &probe; + const quant_run run = quantize(f.fname_model, f.fname_out, f.im, params); + + for (int i = 0; i < 2; i++) { + sigaction(signals[i], nullptr, &after[i]); + sigaction(signals[i], &prev[i], nullptr); + } + t.assert_equal("quantize succeeds", 0u, run.rc); + t.assert_true("the callback is called", probe.n_calls > 0); + t.assert_true("SIGINT keeps its handler, flags and mask during a call", same_action(before[0], probe.during[0])); + t.assert_true("SIGTERM keeps its handler, flags and mask during a call", same_action(before[1], probe.during[1])); + t.assert_true("SIGINT keeps its handler, flags and mask after a call", same_action(before[0], after[0])); + t.assert_true("SIGTERM keeps its handler, flags and mask after a call", same_action(before[1], after[1])); +#endif +} + +static void test_type_flags(testing & t, const fixture & f) { + t.assert_true("without the flags, neither tensor has its flag's type", type_name_of(f.base, "token_embd.weight") != "q8_0" && type_name_of(f.base, "output.weight") != "q6_K"); + + // a copy of the checkpoint, so that nothing is scored + const std::string fname = sibling_path(f, "flags.bpw_state"); + write_file(fname, read_file(f.fname_state)); + llama_model_quantize_params params = base_params(f); + params.state_file = fname.c_str(); + params.token_embedding_type = GGML_TYPE_Q8_0; + params.output_tensor_type = GGML_TYPE_Q6_K; + const quant_run flags = quantize(f.fname_model, f.fname_out, f.im, params); + + // the same two tensors pinned through --tensor-type + const llama_model_tensor_override same[] = { + { "^token_embd\\.weight$", GGML_TYPE_Q8_0 }, { "^output\\.weight$", GGML_TYPE_Q6_K }, { nullptr, GGML_TYPE_COUNT }, + }; + llama_model_quantize_params patterns = base_params(f); + patterns.state_file = fname.c_str(); + patterns.tt_overrides = same; + const quant_run by_pattern = quantize(f.fname_model, f.fname_out, f.im, patterns); + + // --tensor-type names both tensors too, at another type + const llama_model_tensor_override other[] = { + { "^token_embd\\.weight$", GGML_TYPE_Q5_0 }, { "^output\\.weight$", GGML_TYPE_Q5_0 }, { nullptr, GGML_TYPE_COUNT }, + }; + params.tt_overrides = other; + const quant_run named = quantize(f.fname_model, f.fname_out, f.im, params); + + // the flags' types barred + constexpr ggml_type exclude[] = { GGML_TYPE_Q8_0, GGML_TYPE_Q6_K, GGML_TYPE_COUNT }; + params.tt_overrides = nullptr; + params.target_exclude = exclude; + const quant_run barred = quantize(f.fname_model, f.fname_out, f.im, params); + + // only --output-tensor-type: the model is not tied, so the token embedding is not pinned + params.token_embedding_type = GGML_TYPE_COUNT; + params.target_exclude = nullptr; + const quant_run output_only = quantize(f.fname_model, f.fname_out, f.im, params); + + const double bpw = 8.0 * flags.n_bytes / flags.n_elements; + t.log("realised bpw with the flags " + std::to_string(bpw)); + t.assert_equal("quantize succeeds", 0u, flags.rc); + t.assert_equal("--token-embedding-type sets the token embedding", std::string("q8_0"), type_name_of(flags, "token_embd.weight")); + t.assert_equal("--output-tensor-type sets the output", std::string("q6_K"), type_name_of(flags, "output.weight")); + t.assert_equal("flags pin two tensors", (size_t) 2, count_matches(flags.log, "(pinned)")); + t.assert_true("bpw does not exceed the target", bpw <= target_bpw); + t.assert_true("bpw is within 0.05 of the target", bpw > target_bpw - 0.05); + t.assert_equal("quantize succeeds", 0u, by_pattern.rc); + t.assert_equal("flags and same --tensor-type pins, mix rows that differ", (size_t) 0, count_row_changes(by_pattern, flags)); + t.assert_equal("quantize succeeds", 0u, named.rc); + t.assert_equal("--token-embedding-type beats --tensor-type", std::string("q8_0"), type_name_of(named, "token_embd.weight")); + t.assert_equal("--output-tensor-type beats --tensor-type", std::string("q6_K"), type_name_of(named, "output.weight")); + t.assert_equal("quantize succeeds", 0u, barred.rc); + t.assert_equal("excluded --token-embedding-type is reported", (size_t) 1, count_matches(barred.log, "--token-embedding-type pins type q8_0 which is ignored by --target-exclude, keeping the pinned type")); + t.assert_equal("excluded --output-tensor-type is reported", (size_t) 1, count_matches(barred.log, "--output-tensor-type pins type q6_K which is ignored by --target-exclude, keeping the pinned type")); + t.assert_equal("excluded --token-embedding-type keeps its type", std::string("q8_0"), type_name_of(barred, "token_embd.weight")); + t.assert_equal("excluded --output-tensor-type keeps its type", std::string("q6_K"), type_name_of(barred, "output.weight")); + t.assert_equal("quantize succeeds", 0u, output_only.rc); + t.assert_equal("--output-tensor-type alone sets the output", std::string("q6_K"), type_name_of(output_only, "output.weight")); + t.assert_equal("--output-tensor-type alone pins one tensor", (size_t) 1, count_matches(output_only.log, "(pinned)")); +} + +static int run_tests(testing & t, const std::filesystem::path & dir) { + fixture f; + f.fname_model = (dir / "model-f32.gguf").string(); + f.fname_out = (dir / "model-out.gguf").string(); + f.fname_state = (dir / "model.bpw_state").string(); + if (!save_model(f.fname_model)) { + fprintf(stderr, "failed to create the model\n"); + return 1; + } + + f.im = make_imatrix(f.fname_model, 1234); + if (f.im.names.empty()) { + fprintf(stderr, "failed to read the model\n"); + return 1; + } + + f.base = quantize(f.fname_model, f.fname_out, f.im, base_params(f)); + if (f.base.rc != 0) { + fprintf(stderr, "the first quantization failed:\n%s", f.base.log.c_str()); + return 1; + } + + t.test("target_bpw", [&](testing & t) { test_target_bpw(t, f); }); + t.test("target_size", [&](testing & t) { test_target_size(t, f); }); + t.test("state_checkpoint", [&](testing & t) { test_state_checkpoint(t, f); }); + t.test("excluded_type", [&](testing & t) { test_excluded_type(t, f); }); + t.test("unknown_type", [&](testing & t) { test_unknown_type(t, f); }); + t.test("zero_candidates", [&](testing & t) { test_zero_candidates(t, f); }); + t.test("truncated", [&](testing & t) { test_truncated(t, f); }); + t.test("missing_dir", [&](testing & t) { test_missing_dir(t, f); }); + t.test("unreadable_file", [&](testing & t) { test_unreadable_file(t, f); }); + t.test("directory_path", [&](testing & t) { test_directory_path(t, f); }); + t.test("save_error", [&](testing & t) { test_save_error(t, f); }); + t.test("imatrix_swap", [&](testing & t) { test_imatrix_swap(t, f); }); + t.test("imatrix_parts", [&](testing & t) { test_imatrix_parts(t, f); }); + t.test("imatrix_order", [&](testing & t) { test_imatrix_order(t, f); }); + t.test("pruned_layer", [&](testing & t) { test_pruned_layer(t, f); }); + t.test("stats_order", [&](testing & t) { test_stats_order(t, f); }); + t.test("stats_missing", [&](testing & t) { test_stats_missing(t, f); }); + t.test("abort_callback", [&](testing & t) { test_abort_callback(t, f); }); + t.test("interrupt_first_call", [&](testing & t) { test_interrupt_first_call(t, f); }); + t.test("signal_handlers", [&](testing & t) { test_signal_handlers(t, f); }); + t.test("type_flags", [&](testing & t) { test_type_flags(t, f); }); + + return t.summary(); +} + +int main(int argc, char ** argv) { + testing t; + + const char * env = getenv("LLAMA_TEST_VERBOSE"); + verbose = env && std::string(env) == "1"; + t.verbose = verbose; + llama_log_set(log_callback, nullptr); + + if (argc > 1) { t.set_filter(argv[1]); } + + llama_backend_init(); + const std::filesystem::path dir = std::filesystem::temp_directory_path() / ("test-quantize-target-" + std::to_string(std::random_device{}())); + std::filesystem::create_directories(dir); + const int ret = run_tests(t, dir); + std::filesystem::remove_all(dir); + llama_backend_free(); + + return ret; +} diff --git a/tools/quantize/README.md b/tools/quantize/README.md index 27384bebf697..3d5cb72ce447 100644 --- a/tools/quantize/README.md +++ b/tools/quantize/README.md @@ -60,11 +60,19 @@ Options: * `--output-tensor-type` use a specific quant type for the output.weight tensor * `--token-embedding-type` use a specific quant type for the token embeddings tensor * `--keep-split` generate the quantized model in the same shards as the input file instead of a single quantized file +* `--dry-run` simulate the quantization process +* `--max-buffer-size MiB` cap the amount of tensor rows kept in memory while quantizing one tensor (default: 8192). Lower it to quantize models with very large tensors on a machine with little RAM Advanced options: -* `--tensor-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times. +* `--tensor-type` quantize specific tensor(s) to specific quant types. Supports regex syntax. May be specified multiple times * `--prune-layers` prune (remove) the layers in the list -* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times. +* `--override-kv` option to override model metadata by key in the quantized model. May be specified multiple times +* `--target-bpw` automatically choose quant types to meet an overall bits per weight (bpw) target +* `--target-size` automatically choose quant types to meet a file size target +* `--state-file` file name to store or load the bpw/size scores. If left unspecified it defaults to `-.bpw_state`; progress is automatically preserved upon interruptions (SIGTERM or Ctrl-C) allowing execution of the same command to resume the process +* `--target-exclude` comma-separated list of quant types (names or ordinals) that automatic quant type selection must ignore; for use with `--target-bpw`/`--target-size`. May be specified multiple times. A state checkpoint is not written while this option is active + +When using `--target-bpw` or `--target-size`, any tensors specified by `--tensor-type`, `--token-embedding-type`, or `--output-tensor-type` retain their defined types, with their total size counted toward the overall target. Quantization will fail if the budget allocated to these tensors leaves insufficient capacity for the remainder of the model. ## (Optional) Convert the multimodal components @@ -92,6 +100,16 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf ./llama-quantize input-model-f32.gguf q4_k_m 8 ``` +```bash +# simulate naive Q4_K_M quantization process. No model will be generated +./llama-quantize --dry-run input-model-f32.gguf q4_k_m 8 +``` + +```bash +# naive Q4_K_M quantization overriding general.name and model.rope.freq_base metadata values +./llama-quantize --override-kv general.name=str:"New model name" --override-kv model.rope.freq_base=float:1.234e+08 input-model-f32.gguf q4_k_m 8 +``` + ```bash # quantize model enabling re-quantization, leaving the output tensor unquantized and all others quantized at the same level (Q4_K) ./llama-quantize --allow-requantize --leave-output-tensor --pure input-model-f32.gguf q4_k_m 8 @@ -122,59 +140,69 @@ python convert_hf_to_gguf.py --mmproj --outfile mmproj-gemma-4-E2B-it-Q8_0.gguf ./llama-quantize --imatrix imatrix.gguf --override-kv qwen3moe.expert_used_count=int:16 --prune-layers 20,21,22 input-model-f32.gguf pruned-model-f32.gguf copy 8 ``` +```bash +# quantize model targeting a specific bpw average and save the target computations to the default file. Model type is optional and can be omitted +./llama-quantize --target-bpw 4.5678 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + +```bash +# quantize model targeting a specific bpw average using the default state checkpoint (if available) and ignoring IQ2_XXS, IQ2_XS and IQ2_S types (checkpoint is not saved) +./llama-quantize --target-bpw 4.5678 --target-exclude IQ2_XXS,IQ2_XS,IQ2_S --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + +```bash +# quantize model targeting a specific bpw average reusing previous target computations in default file (e.g. input-model-8fd7a8bef0803042.bpw_state) +./llama-quantize --target-bpw 2.345 --state-file --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + +```bash +# quantize model targeting a specific file size and save the target computations to a custom file. +./llama-quantize --target-size 1.5g --state-file my-state-file.dat --imatrix imatrix.gguf input-model-f32.gguf output-model.gguf +``` + ## Memory/Disk Requirements When running the larger models, make sure you have enough disk space to store all the intermediate files. As the models are currently fully loaded into memory, you will need adequate disk space to save them and sufficient RAM to load them. At the moment, memory and disk requirements are the same. For example (Llama 3.1): | Model | Original size | Quantized size (Q4_K_M) | -| ----: | ------------: | ----------------------: | +|------:|--------------:|------------------------:| | 8B | 32.1 GB | 4.9 GB | | 70B | 280.9 GB | 43.1 GB | | 405B | 1,625.1 GB | 249.1 GB | - ## Quantization Several quantization methods are supported. They differ in the resulting model disk size and inference speed. For example, ### [meta-llama/Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B) -| Measure | IQ1_S | IQ1_M | IQ2_XXS | IQ2_XS | IQ2_S | IQ2_M | -| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ | -| bits/weight | 2.0042 | 2.1460 | 2.3824 | 2.5882 | 2.7403 | 2.9294 | -| size (GiB) | 1.87 | 2.01 | 2.23 | 2.42 | 2.56 | 2.74 | -| prompt processing t/s @ 512 | 858.88 ±1.22 | 847.99 ±0.47 | 852.39 ±0.85 | 826.99 ±12.51 | 783.55 ±13.73 | 787.68 ±7.00 | -| text generation t/s @ 128 | 79.73 ±0.79 | 72.92 ±0.14 | 79.86 ±0.22 | 78.04 ±0.46 | 77.30 ±2.47 | 74.44 ±0.15 | - -| Measure | IQ3_XXS | IQ3_XS | IQ3_S | IQ3_M | IQ4_XS | IQ4_NL | -| --------------------------- | ------------ | ------------ | ------------ | ------------- | ------------- | ------------ | -| bits/weight | 3.2548 | 3.4977 | 3.6606 | 3.7628 | 4.4597 | 4.6818 | -| size (GiB) | 3.04 | 3.27 | 3.42 | 3.52 | 4.17 | 4.38 | -| prompt processing t/s @ 512 | 813.88 ±6.53 | 708.71 ±1.26 | 798.78 ±8.81 | 768.70 ±13.73 | 771.80 ±11.38 | 806.03 ±7.07 | -| text generation t/s @ 128 | 73.95 ±0.20 | 71.67 ±0.54 | 69.31 ±0.63 | 70.15 ±0.33 | 77.51 ±0.20 | 76.63 ±0.28 | - - -| Measure | Q2_K_S | Q2_K | Q3_K_S | Q3_K_M | Q3_K_L | Q4_K_S | -| --------------------------- | ------------ | ------------ | ------------ | ------------ | ------------ | ------------ | -| bits/weight | 2.9697 | 3.1593 | 3.6429 | 3.9960 | 4.2979 | 4.6672 | -| size (GiB) | 2.78 | 2.95 | 3.41 | 3.74 | 4.02 | 4.36 | -| prompt processing t/s @ 512 | 798.91 ±6.40 | 784.45 ±7.85 | 752.17 ±7.94 | 783.44 ±9.92 | 761.17 ±7.55 | 818.55 ±9.58 | -| text generation t/s @ 128 | 90.01 ±0.12 | 79.85 ±0.20 | 69.84 ±0.18 | 71.68 ±0.22 | 69.38 ±0.49 | 76.71 ±0.20 | - -| Measure | Q4_K_S | Q4_K_M | Q5_K_S | Q5_K_M | Q6_K | Q8_0 | -| --------------------------- | ------------ | ------------- | ------------ | ------------ | ------------- | ------------ | -| bits/weight | 4.6672 | 4.8944 | 5.5704 | 5.7036 | 6.5633 | 8.5008 | -| size (GiB) | 4.36 | 4.58 | 5.21 | 5.33 | 6.14 | 7.95 | -| prompt processing t/s @ 512 | 818.55 ±9.58 | 821.81 ±21.44 | 752.52 ±0.99 | 758.69 ±7.43 | 812.01 ±10.82 | 865.09 ±8.30 | -| text generation t/s @ 128 | 76.71 ±0.20 | 71.93 ±1.52 | 69.53 ±0.18 | 67.23 ±1.08 | 58.67 ±3.13 | 50.93 ±0.08 | - -| Measure | F16 | -| --------------------------- | ------------ | -| bits/weight | 16.0005 | -| size (GiB) | 14.96 | -| prompt processing t/s @ 512 | 923.49 ±0.53 | -| text generation t/s @ 128 | 29.17 ±0.04 | +| Quant Type | bits/weight | size (GiB) | prompt processing t/s @ 512 | text generation t/s @ 128 | +|:----------:|------------:|-----------:|----------------------------:|--------------------------:| +| IQ1_S | 2.0042 | 1.87 | 858.88 ±1.22 | 79.73 ±0.79 | +| IQ1_M | 2.1460 | 2.01 | 847.99 ±0.47 | 72.92 ±0.14 | +| IQ2_XXS | 2.3824 | 2.23 | 852.39 ±0.85 | 79.86 ±0.22 | +| IQ2_XS | 2.5882 | 2.42 | 826.99 ±12.51 | 78.04 ±0.46 | +| IQ2_S | 2.7403 | 2.56 | 783.55 ±13.73 | 77.30 ±2.47 | +| IQ2_M | 2.9294 | 2.74 | 787.68 ±7.00 | 74.44 ±0.15 | +| IQ3_XXS | 3.2548 | 3.04 | 813.88 ±6.53 | 73.95 ±0.20 | +| IQ3_XS | 3.4977 | 3.27 | 708.71 ±1.26 | 71.67 ±0.54 | +| IQ3_S | 3.6606 | 3.42 | 798.78 ±8.81 | 69.31 ±0.63 | +| IQ3_M | 3.7628 | 3.52 | 768.70 ±13.73 | 70.15 ±0.33 | +| IQ4_XS | 4.4597 | 4.17 | 771.80 ±11.38 | 77.51 ±0.20 | +| IQ4_NL | 4.6818 | 4.38 | 806.03 ±7.07 | 76.63 ±0.28 | +| Q2_K_S | 2.9697 | 2.78 | 798.91 ±6.40 | 90.01 ±0.12 | +| Q2_K | 3.1593 | 2.95 | 784.45 ±7.85 | 79.85 ±0.20 | +| Q3_K_S | 3.6429 | 3.41 | 752.17 ±7.94 | 69.84 ±0.18 | +| Q3_K_M | 3.9960 | 3.74 | 783.44 ±9.92 | 71.68 ±0.22 | +| Q3_K_L | 4.2979 | 4.02 | 761.17 ±7.55 | 69.38 ±0.49 | +| Q4_K_S | 4.6672 | 4.36 | 818.55 ±9.58 | 76.71 ±0.20 | +| Q4_K_M | 4.8944 | 4.58 | 821.81 ±21.44 | 71.93 ±1.52 | +| Q5_K_S | 5.5704 | 5.21 | 752.52 ±0.99 | 69.53 ±0.18 | +| Q5_K_M | 5.7036 | 5.33 | 758.69 ±7.43 | 67.23 ±1.08 | +| Q6_K | 6.5633 | 6.14 | 812.01 ±10.82 | 58.67 ±3.13 | +| Q8_0 | 8.5008 | 7.95 | 865.09 ±8.30 | 50.93 ±0.08 | +| F16 | 16.0005 | 14.96 | 923.49 ±0.53 | 29.17 ±0.04 | ## Background information on llama-quantize @@ -194,3 +222,4 @@ Several quantization methods are supported. They differ in the resulting model d - [#5060 - Q3_K_XS](https://github.com/ggml-org/llama.cpp/pull/5060) - [#5196 - 3-bit i-quants](https://github.com/ggml-org/llama.cpp/pull/5196) - [quantization tuning](https://github.com/ggml-org/llama.cpp/pull/5320), [another one](https://github.com/ggml-org/llama.cpp/pull/5334), and [another one](https://github.com/ggml-org/llama.cpp/pull/5361) +- [target bpw/size](https://github.com/ggml-org/llama.cpp/pull/15550) diff --git a/tools/quantize/quantize.cpp b/tools/quantize/quantize.cpp index 0debcfddaffa..d58695196301 100644 --- a/tools/quantize/quantize.cpp +++ b/tools/quantize/quantize.cpp @@ -1,24 +1,24 @@ -#include "llama.h" - #include "build-info.h" #include "common.h" #include "imatrix-loader.h" -#include "gguf.h" - -#include -#include -#include +#include #include -#include +#include #include -#include -#include -#include -#include #include +#include +#include +#include + +#if defined(_WIN32) +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +# define NOMINMAX +#endif +#include +#endif -// result of parsing --tensor-type option // changes to this struct must also be reflected in src/llama-quant.cpp struct tensor_type_option { std::string name; @@ -121,8 +121,8 @@ static bool try_parse_ftype(const std::string & ftype_str_in, llama_ftype & ftyp [[noreturn]] static void usage(const char * executable) { printf("usage: %s [--help] [--allow-requantize] [--leave-output-tensor] [--pure] [--imatrix] [--include-weights]\n", executable); - printf(" [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file]\n"); - printf(" [--prune-layers] [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size]\n"); + printf(" [--exclude-weights] [--output-tensor-type] [--token-embedding-type] [--tensor-type] [--tensor-type-file] [--prune-layers]\n"); + printf(" [--keep-split] [--override-kv] [--dry-run] [--max-buffer-size] [--target-bpw] [--target-size] [--target-exclude] [--state-file]\n"); printf(" model-f32.gguf [model-quant.gguf] type [nthreads]\n\n"); printf(" --allow-requantize\n"); printf(" allow requantizing tensors that have already been quantized\n"); @@ -145,7 +145,7 @@ static void usage(const char * executable) { printf(" use this ggml_type for the token embeddings tensor\n"); printf(" --tensor-type tensor_name=ggml_type\n"); printf(" quantize this tensor to this ggml_type\n"); - printf(" this is an advanced option to selectively quantize tensors. may be specified multiple times.\n"); + printf(" this is an advanced option to selectively quantize tensors; may be specified multiple times.\n"); printf(" example: --tensor-type attn_q=q8_0\n"); printf(" --tensor-type-file tensor_types.txt\n"); printf(" list of tensors to quantize to a specific ggml_type\n"); @@ -157,7 +157,7 @@ static void usage(const char * executable) { printf(" --keep-split\n"); printf(" generate quantized model in the same shards as input\n"); printf(" --override-kv KEY=TYPE:VALUE\n"); - printf(" override model metadata by key in the quantized model. may be specified multiple times.\n"); + printf(" override model metadata by key in the quantized model; may be specified multiple times.\n"); printf(" WARNING: this is an advanced option, use with care.\n"); printf(" --dry-run\n"); printf(" calculate and show the final quantization size without performing quantization\n"); @@ -165,7 +165,21 @@ static void usage(const char * executable) { printf(" --max-buffer-size MiB\n"); printf(" max amount of tensor rows kept in memory while quantizing one tensor (default: 8192)\n"); printf(" lower it to quantize models with very large tensors on a machine with little RAM\n\n"); - printf("note: --include-weights and --exclude-weights cannot be used together\n\n"); + printf(" --target-bpw n\n"); + printf(" target a bits per weight (bpw); must be a number between 0.0 and 16.0, 0 means the smallest possible model\n"); + printf(" advanced option to automatically select quantization types to achieve a total bits per weight (bpw) target\n\n"); + printf(" --target-size n\n"); + printf(" target a file size; must be 0 or more, 0 means the smallest possible model\n"); + printf(" advanced option to automatically select quantization types to achieve a total file size\n"); + printf(" allowed units: b, k|kib, m|mib, g|gib, t|tib; defaults to b (bytes) if none is provided\n\n"); + printf(" --state-file [filename]\n"); + printf(" file name to use/save; if none is provided, the default name will be used\n\n"); + printf(" --target-exclude type[,type...]\n"); + printf(" comma-separated ggml_type (names or ordinals) that automatic quant type selection must ignore\n"); + printf(" advanced option for --target-bpw/--target-size; may be specified multiple times\n\n"); + printf("note: --include-weights and --exclude-weights cannot be used together\n"); + printf(" --target-bpw and --target-size cannot be used together\n"); + printf(" --exclude-weights excludes tensor NAMES, while --target-exclude excludes quant TYPES\n\n"); printf("-----------------------------------------------------------------------------\n"); printf(" allowed quantization types\n"); printf("-----------------------------------------------------------------------------\n\n"); @@ -180,7 +194,13 @@ static void usage(const char * executable) { exit(1); } -static int load_imatrix(const std::string & imatrix_file, std::vector & imatrix_datasets, std::unordered_map> & imatrix_data) { +static int load_imatrix(const std::string & imatrix_file, + std::vector & imatrix_datasets, + std::unordered_map> & values_data, + std::unordered_map> & activations_data, + std::unordered_map> & statistics_data, + std::vector & statistics_schema) +{ common_imatrix loaded; if (!common_imatrix_load(imatrix_file, loaded)) { fprintf(stderr, "%s: failed to load imatrix from '%s'\n", __func__, imatrix_file.c_str()); @@ -193,59 +213,84 @@ static int load_imatrix(const std::string & imatrix_file, std::vector 0.0f) { for (int64_t i = 0; i < ne0; ++i) { - e[j*ne0 + i] = entry.sums[j*ne0 + i] / count; + values[j*ne0 + i] = entry.sums[j*ne0 + i] / count; } } else { for (int64_t i = 0; i < ne0; ++i) { - e[j*ne0 + i] = 1; + values[j*ne0 + i] = 1; } } } + } else { + const int64_t ncall = entry.counts[0]; + if (ncall > 0) { + for (int64_t i = 0; i < nsums; ++i) { + values[i] = entry.sums[i] / ncall; + } + } else { + for (int64_t i = 0; i < nsums; ++i) { + values[i] = entry.sums[i]; + } + } + } - if (getenv("LLAMA_TRACE")) { - float max_count = 0.0f; + if (!entry.activations.empty()) { + auto & activations = activations_data[name]; + activations.resize(entry.activations.size()); + if (!loaded.is_legacy) { for (int64_t j = 0; j < ncounts; ++j) { const float count = (float) entry.counts[j]; - if (count > max_count) { - max_count = count; + if (count > 0.0f) { + for (int64_t i = 0; i < ne0; ++i) { + activations[j*ne0 + i] = entry.activations[j*ne0 + i] / count; + } + } else { + for (int64_t i = 0; i < ne0; ++i) { + activations[j*ne0 + i] = 0; + } } } - printf("%s: loaded data (size = %6d, n_tokens = %6d, n_chunks = %6d) for '%s'\n", - __func__, int(e.size()), int(max_count), int(max_count / loaded.chunk_size), name.c_str()); - } - } else { - // Legacy format: sums contain (raw/count)*ncall, divide by ncall - const int64_t ncall = entry.counts.empty() ? 0 : entry.counts[0]; - if (ncall > 0) { - for (size_t i = 0; i < entry.sums.size(); ++i) { - e[i] = entry.sums[i] / ncall; - } } else { - for (size_t i = 0; i < entry.sums.size(); ++i) { - e[i] = entry.sums[i]; + const int64_t ncall = entry.counts[0]; + if (ncall > 0) { + for (size_t i = 0; i < entry.activations.size(); ++i) { + activations[i] = entry.activations[i] / ncall; + } + } else { + for (size_t i = 0; i < entry.activations.size(); ++i) { + activations[i] = entry.activations[i]; + } } } + } - if (getenv("LLAMA_TRACE")) { - printf("%s: loaded data (size = %6d, ncall = %6d) for '%s'\n", - __func__, int(e.size()), int(ncall), name.c_str()); - } + if (!entry.stats.empty()) { + statistics_data[name] = entry.stats; } } imatrix_datasets = std::move(loaded.datasets); + statistics_schema = std::move(loaded.stats_schema); if (!imatrix_datasets.empty()) { printf("%s: imatrix datasets=['%s'", __func__, imatrix_datasets[0].c_str()); @@ -255,7 +300,7 @@ static int load_imatrix(const std::string & imatrix_file, std::vector & imatrix_dataset, const std::vector & included_weights, const std::vector & excluded_weights, - std::unordered_map> & imatrix_data) { + std::unordered_map> & values_data, + std::unordered_map> & activations_data, + std::unordered_map> & statistics_data, + std::vector & stats_schema) { int m_last_call = -1; if (!imatrix_file.empty()) { - m_last_call = load_imatrix(imatrix_file, imatrix_dataset, imatrix_data); + m_last_call = load_imatrix(imatrix_file, imatrix_dataset, values_data, activations_data, statistics_data, stats_schema); } - if (imatrix_data.empty()) { + if (values_data.empty()) { return m_last_call; } if (!excluded_weights.empty()) { for (const auto & name : excluded_weights) { - for (auto it = imatrix_data.begin(); it != imatrix_data.end();) { - auto pos = it->first.find(name); + for (auto vt = values_data.begin(); vt != values_data.end();) { + auto pos = vt->first.find(name); + if (pos != std::string::npos) { + vt = values_data.erase(vt); + } else { + ++vt; + } + } + for (auto at = activations_data.begin(); at != activations_data.end();) { + auto pos = at->first.find(name); + if (pos != std::string::npos) { + at = activations_data.erase(at); + } else { + ++at; + } + } + for (auto st = statistics_data.begin(); st != statistics_data.end();) { + auto pos = st->first.find(name); if (pos != std::string::npos) { - it = imatrix_data.erase(it); + st = statistics_data.erase(st); } else { - ++it; + ++st; } } } } if (!included_weights.empty()) { - std::unordered_map> tmp; + std::unordered_map> tmp_values; + std::unordered_map> tmp_activations; + std::unordered_map> tmp_statistics; for (const auto & name : included_weights) { - for (auto & e : imatrix_data) { + for (auto & e : values_data) { auto pos = e.first.find(name); if (pos != std::string::npos) { - tmp.emplace(std::move(e)); + tmp_values.emplace(std::move(e)); + } + } + for (auto & a : activations_data) { + auto pos = a.first.find(name); + if (pos != std::string::npos) { + tmp_activations.emplace(std::move(a)); + } + } + for (auto & s : statistics_data) { + auto pos = s.first.find(name); + if (pos != std::string::npos) { + tmp_statistics.emplace(std::move(s)); } } } - imatrix_data = std::move(tmp); - } - if (!imatrix_data.empty()) { - printf("%s: have %d importance matrix entries\n", __func__, int(imatrix_data.size())); + values_data = std::move(tmp_values); + activations_data = std::move(tmp_activations); + statistics_data = std::move(tmp_statistics); } + return m_last_call; } @@ -389,6 +467,139 @@ static bool parse_layer_prune(const char * data, std::vector & prune_layers return true; } +static bool parse_target_bpw(const char * data, float & target_bpw) { + if (!data) { + printf("\n%s: no target bits per weight (bpw) provided\n\n", __func__); + return false; + } + + try { + target_bpw = std::stof(data); + if (!std::isfinite(target_bpw) || target_bpw < 0.0f || target_bpw > 16.0f) { + printf("\n%s: target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__); + return false; + } + } + catch (const std::exception & e) { + printf("\n%s: '%s' is not valid. Target bits per weight (bpw) must be a number between 0.0 and 16.0\n\n", __func__, data); + return false; + } + + return true; +} + +static bool parse_target_size(const char * data, int64_t & target_size) { + if (!data) { + printf("\n%s: no target file size provided\n\n", __func__); + return false; + } + + char * end = nullptr; + const double val = std::strtod(data, &end); + if (end == data || !std::isfinite(val) || val < 0) { + printf("\n%s: invalid target file size '%s'\n\n", __func__, data); + return false; + } + + std::string suffix(end); + for (auto & c : suffix) { c = std::tolower(c); } + + int64_t mul = 0; + if (suffix.empty() || suffix == "b") { + mul = 1; + } else if (suffix == "k" || suffix == "kib") { + mul = 1024; + } else if (suffix == "m" || suffix == "mib") { + mul = 1024 * 1024; + } else if (suffix == "g" || suffix == "gib") { + mul = 1024 * 1024 * 1024; + } else if (suffix == "t" || suffix == "tib") { + mul = 1024LL * 1024 * 1024 * 1024; + } else { + printf("\n%s: invalid unit '%s' in '%s'. Allowed: b, k or kib, m or mib, g or gib, t or tib\n\n", __func__, suffix.c_str(), data); + return false; + } + + if (val * mul >= (double)INT64_MAX) { + printf("\n%s: invalid target file size '%s'\n\n", __func__, data); + return false; + } + + target_size = (int64_t)(val * mul); + return true; +} + +static bool parse_target_exclude(const char * data, std::vector & target_exclude) { + if (!data) { + printf("\n%s: no quant types provided\n\n", __func__); + return false; + } + + const auto tokens = string_split(data, ','); + for (const auto & token : tokens) { + ggml_type type = GGML_TYPE_COUNT; + for (int i = 0; i < GGML_TYPE_COUNT; ++i) { + const char * name = ggml_type_name((ggml_type)i); + if (name && striequals(name, token.c_str())) { + type = (ggml_type)i; + break; + } + } + + if (type == GGML_TYPE_COUNT) { + const bool numeric = !token.empty() && std::all_of(token.begin(), token.end(), [](unsigned char c) { return std::isdigit(c); }); + const long ordinal = numeric ? std::strtol(token.c_str(), nullptr, 10) : -1; + if (ordinal >= 0 && ordinal < GGML_TYPE_COUNT) { + type = (ggml_type)ordinal; + } + } + + if (type == GGML_TYPE_COUNT) { + printf("\n%s: invalid quant type '%s' for --target-exclude\n\n", __func__, token.c_str()); + return false; + } + + if (std::find(target_exclude.begin(), target_exclude.end(), type) == target_exclude.end()) { + target_exclude.emplace_back(type); + } + } + + return true; +} + +static const char * get_ftype(const float bpw) { + const std::map quant_bpw = { + {1.5625, "IQ1_S"}, + {1.7500, "IQ1_M"}, + {2.0625, "IQ2_XXS"}, + {2.3125, "IQ2_XS"}, + {2.5625, "IQ2_S"}, + {2.6250, "Q2_K"}, + {3.0625, "IQ3_XXS"}, + {3.4375, "Q3_K"}, + {4.2500, "IQ4_XS"}, + {4.5000, "Q4_K"}, + {5.5000, "Q5_K"}, + {6.5625, "Q6_K"}, + {8.5000, "Q8_0"}, + {16.0000, "F16"} + }; + + return quant_bpw.lower_bound(bpw)->second; +} + +static std::atomic interrupt_signal{ 0 }; + +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32) +// try to save the state checkpoint if interrupted while scoring +static void signal_handler(int signo) { + int expected = 0; + interrupt_signal.compare_exchange_strong(expected, signo); +} +#endif + +static bool is_interrupted(void * /*data*/) { return interrupt_signal.load() != 0; } + // satisfies -Wmissing-declarations int llama_quantize(int argc, char ** argv); @@ -402,10 +613,14 @@ int llama_quantize(int argc, char ** argv) { int arg_idx = 1; std::string imatrix_file; - std::vector included_weights, excluded_weights; + std::vector included_weights; + std::vector excluded_weights; std::vector kv_overrides; std::vector tensor_type_opts; std::vector prune_layers; + std::vector target_exclude; + float target_bpw = -1.0f; + int64_t target_size = -1; for (; arg_idx < argc && strncmp(argv[arg_idx], "--", 2) == 0; arg_idx++) { if (strcmp(argv[arg_idx], "--leave-output-tensor") == 0) { @@ -436,6 +651,25 @@ int llama_quantize(int argc, char ** argv) { if (arg_idx == argc-1 || !parse_tensor_type_file(argv[++arg_idx], tensor_type_opts)) { usage(argv[0]); } + } else if (strcmp(argv[arg_idx], "--target-bpw") == 0) { + if (arg_idx == argc-1 || !parse_target_bpw(argv[++arg_idx], target_bpw)) { + usage(argv[0]); + } + } else if (strcmp(argv[arg_idx], "--target-size") == 0) { + if (arg_idx == argc-1 || !parse_target_size(argv[++arg_idx], target_size)) { + usage(argv[0]); + } + } else if (strcmp(argv[arg_idx], "--target-exclude") == 0) { + if (arg_idx == argc-1 || !parse_target_exclude(argv[++arg_idx], target_exclude)) { + usage(argv[0]); + } + } else if (strcmp(argv[arg_idx], "--state-file") == 0) { + if (arg_idx + 1 < argc && argv[arg_idx + 1][0] != '-') { + params.state_file = argv[++arg_idx]; + } else { + static char empty[] = ""; + params.state_file = empty; + } } else if (strcmp(argv[arg_idx], "--prune-layers") == 0) { if (arg_idx == argc-1 || !parse_layer_prune(argv[++arg_idx], prune_layers)) { usage(argv[0]); @@ -492,20 +726,28 @@ int llama_quantize(int argc, char ** argv) { if (!included_weights.empty() && !excluded_weights.empty()) { usage(argv[0]); } + if (target_bpw != -1.0f && target_size != -1) { + usage(argv[0]); + } std::vector imatrix_datasets; - std::unordered_map> imatrix_data; - int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, imatrix_data); - - std::vector i_data; - std::vector t_override; - if (!imatrix_data.empty()) { - i_data.reserve(imatrix_data.size() + 1); - for (const auto & kv : imatrix_data) { - i_data.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); - } - i_data.push_back({nullptr, nullptr, 0}); // array terminator - params.imatrix = i_data.data(); + std::unordered_map> values_data; + std::unordered_map> activations_data; + std::unordered_map> statistics_data; + std::vector stats_schema; + int m_last_call = prepare_imatrix(imatrix_file, imatrix_datasets, included_weights, excluded_weights, values_data, activations_data, statistics_data, stats_schema); + + std::vector vdata; + std::vector adata; + std::vector sdata; + std::vector sschema; + std::vector tto; + + if (!values_data.empty()) { + vdata.reserve(values_data.size() + 1); + for (const auto & kv : values_data) { vdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); } + vdata.push_back({nullptr, nullptr, 0}); // array terminator + params.imatrix = vdata.data(); { llama_model_kv_override kvo; std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_FILE); @@ -529,7 +771,7 @@ int llama_quantize(int argc, char ** argv) { llama_model_kv_override kvo; std::strcpy(kvo.key, LLM_KV_QUANTIZE_IMATRIX_N_ENTRIES); kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT; - kvo.val_i64 = imatrix_data.size(); + kvo.val_i64 = values_data.size(); kv_overrides.emplace_back(std::move(kvo)); } if (m_last_call > 0) { @@ -540,23 +782,47 @@ int llama_quantize(int argc, char ** argv) { kv_overrides.emplace_back(std::move(kvo)); } } + if (!activations_data.empty()) { + adata.reserve(activations_data.size() + 1); + for (const auto & kv : activations_data) { adata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); } + adata.push_back({nullptr, nullptr, 0}); // array terminator + params.activations = adata.data(); + } + if (!statistics_data.empty()) { + sdata.reserve(statistics_data.size() + 1); + for (const auto & kv : statistics_data) { sdata.push_back({kv.first.c_str(), kv.second.data(), kv.second.size()}); } + sdata.push_back({nullptr, nullptr, 0}); // array terminator + params.statistics = sdata.data(); + sschema.reserve(stats_schema.size() + 1); + for (const auto & name : stats_schema) { sschema.push_back(name.c_str()); } + sschema.push_back(nullptr); // array terminator + params.stats_schema = sschema.data(); + } if (!kv_overrides.empty()) { kv_overrides.emplace_back(); kv_overrides.back().key[0] = 0; params.kv_overrides = kv_overrides.data(); } if (!tensor_type_opts.empty()) { - t_override.reserve(tensor_type_opts.size() + 1); - for (const auto & tt : tensor_type_opts) { - t_override.push_back({tt.name.c_str(), tt.type}); - } - t_override.push_back({nullptr, GGML_TYPE_COUNT}); // array terminator - params.tt_overrides = t_override.data(); + tto.reserve(tensor_type_opts.size() + 1); + for (const auto & tt : tensor_type_opts) { tto.push_back({tt.name.c_str(), tt.type}); } + tto.push_back({nullptr, GGML_TYPE_COUNT}); // array terminator + params.tt_overrides = tto.data(); + } + if (!target_exclude.empty()) { + target_exclude.push_back(GGML_TYPE_COUNT); // array terminator + params.target_exclude = target_exclude.data(); } if (!prune_layers.empty()) { prune_layers.push_back(-1); // array terminator params.prune_layers = prune_layers.data(); } + if (target_bpw != -1.0f) { + params.target_bpw = target_bpw; + } + if (target_size != -1) { + params.target_size = target_size; + } llama_backend_init(); @@ -567,6 +833,7 @@ int llama_quantize(int argc, char ** argv) { std::string ftype_str; std::string suffix = ".gguf"; + std::vector tmp_argv(argv, argv + argc); if (try_parse_ftype(argv[arg_idx], params.ftype, ftype_str)) { // argv[arg_idx] is the ftype directly: if (!params.dry_run) { @@ -594,7 +861,22 @@ int llama_quantize(int argc, char ** argv) { } arg_idx++; - if (argc <= arg_idx) { + // If --target-bpw or --target-size are set, select a quantization type and ignore any user specified type + if (params.target_bpw != -1.0f || params.target_size != -1) { + auto * ftype = params.target_bpw != -1.0f ? const_cast(get_ftype(params.target_bpw)) : const_cast("F16"); + bool added_type = false; + if (argc == arg_idx) { + tmp_argv.push_back(ftype); + added_type = true; + } else { + tmp_argv[arg_idx] = ftype; + } + tmp_argv.push_back(nullptr); + argv = const_cast(tmp_argv.data()); + if (added_type) { + argc++; + } + } else if (argc <= arg_idx) { fprintf(stderr, "%s: missing ftype\n", __func__); return 1; } @@ -639,6 +921,24 @@ int llama_quantize(int argc, char ** argv) { } fprintf(stderr, "\n"); + // handle SIGINT and SIGTERM + { +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) + struct sigaction sigint_action; + sigint_action.sa_handler = signal_handler; + sigemptyset(&sigint_action.sa_mask); + sigint_action.sa_flags = SA_RESTART; + sigaction(SIGINT, &sigint_action, nullptr); + sigaction(SIGTERM, &sigint_action, nullptr); +#elif defined (_WIN32) + auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL { + return (ctrl_type == CTRL_C_EVENT) ? (signal_handler(SIGINT), true) : false; + }; + SetConsoleCtrlHandler(reinterpret_cast(console_ctrl_handler), true); +#endif + params.abort_callback = is_interrupted; + } + const int64_t t_main_start_us = llama_time_us(); int64_t t_quantize_us = 0; @@ -649,7 +949,16 @@ int llama_quantize(int argc, char ** argv) { if (llama_model_quantize(fname_inp.c_str(), fname_out.c_str(), ¶ms)) { fprintf(stderr, "%s: failed to quantize model from '%s'\n", __func__, fname_inp.c_str()); - return 1; + const int signo = interrupt_signal.load(); +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) + // ensure that a calling shell or script stops too... + if (signo) { + signal(signo, SIG_DFL); + raise(signo); + } +#endif + // ...as a shell reports a process that the signal killed + return signo ? 128 + signo : 1; } t_quantize_us = llama_time_us() - t_start_us; From 239242322dc24e8c15a458b1beae5064e3358cf8 Mon Sep 17 00:00:00 2001 From: "Piotr Wilkin (ilintar)" Date: Mon, 23 Nov 2026 18:17:11 +0100 Subject: [PATCH 075/401] ggml: compact bias on the existing FLASH_ATTN_EXT (#32740) * compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan * fixup! compact bias on the existing FLASH_ATTN_EXT for CUDA, ROCm and Vulkan * remove the Vulkan support from this PR * move the CUDA/HIP and Inkling 2 graph changes out of this PR * CPU reference implementation of the indexed bias * move the indexed bias test to test-backend-ops, add the bias in F32 on CPU * incorporate review remarks --- ggml/include/ggml.h | 9 ++ ggml/src/ggml-backend-meta.cpp | 4 + ggml/src/ggml-cann/ggml-cann.cpp | 4 +- ggml/src/ggml-cpu/ggml-cpu.cpp | 4 + ggml/src/ggml-cpu/ops.cpp | 28 +++- ggml/src/ggml-cuda/fattn.cu | 4 + ggml/src/ggml-et/ggml-et.cpp | 1 + ggml/src/ggml-hexagon/htp-kparams.cpp | 4 +- ggml/src/ggml-metal/ggml-metal-device.m | 3 + ggml/src/ggml-opencl/ggml-opencl.cpp | 4 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 4 + ggml/src/ggml-sycl/ggml-sycl.cpp | 4 +- ggml/src/ggml-virtgpu/ggml-backend-device.cpp | 4 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 3 +- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 5 +- ggml/src/ggml-zdnn/fattn.cpp | 2 +- ggml/src/ggml.c | 27 ++++ tests/test-backend-ops.cpp | 133 ++++++++++++++++++ 18 files changed, 232 insertions(+), 15 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 2f466e2e4e46..161e8e0cef47 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2292,6 +2292,15 @@ extern "C" { struct ggml_tensor * a, struct ggml_tensor * sinks); + GGML_API bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a); + + // Add table[indices[key, query], head, query] to the mask, in F32. + // Queries from all streams are flattened in stream order. Indices must be in [0, table->ne[0]). + GGML_API void ggml_flash_attn_ext_add_indexed_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * indices); + // TODO: needs to be adapted to ggml_flash_attn_ext GGML_API struct ggml_tensor * ggml_flash_attn_back( struct ggml_context * ctx, diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 54d85b597fda..9aed3b7808b8 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -152,6 +152,10 @@ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_buffer_type(ggml_ static ggml_backend_buffer_type_t ggml_backend_meta_device_get_host_buffer_type(ggml_backend_dev_t dev); static bool ggml_backend_meta_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + GGML_ASSERT(ggml_backend_dev_is_meta(dev)); const ggml_backend_meta_device_context * meta_dev_ctx = (const ggml_backend_meta_device_context *) dev->context; return std::all_of(meta_dev_ctx->simple_devs.begin(), meta_dev_ctx->simple_devs.end(), diff --git a/ggml/src/ggml-cann/ggml-cann.cpp b/ggml/src/ggml-cann/ggml-cann.cpp index 0adc8680f5a4..4ea2f216d066 100644 --- a/ggml/src/ggml-cann/ggml-cann.cpp +++ b/ggml/src/ggml-cann/ggml-cann.cpp @@ -2679,8 +2679,8 @@ static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_ten return true; case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } #ifdef ASCEND_310P diff --git a/ggml/src/ggml-cpu/ggml-cpu.cpp b/ggml/src/ggml-cpu/ggml-cpu.cpp index 29783400186d..f6a9f5cba20a 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.cpp +++ b/ggml/src/ggml-cpu/ggml-cpu.cpp @@ -422,6 +422,10 @@ static ggml_backend_buffer_t ggml_backend_cpu_device_buffer_from_host_ptr(ggml_b } static bool ggml_backend_cpu_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + const struct ggml_tensor * src0 = op->src[0]; const struct ggml_tensor * src1 = op->src[1]; diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index f984f13a6c3c..26b4a01c96eb 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -8981,6 +8981,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const ggml_tensor * mask = dst->src[3]; const ggml_tensor * sinks = dst->src[4]; const ggml_tensor * kv_rows = dst->src[5]; + const ggml_tensor * bias_table = dst->src[6]; + const ggml_tensor * bias_indices = dst->src[7]; GGML_TENSOR_LOCALS(int64_t, neq, q, ne) GGML_TENSOR_LOCALS(size_t, nbq, q, nb) @@ -9022,6 +9024,8 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const int64_t rv2 = neq2/nev2; const int64_t rv3 = neq3/nev3; + const int64_t n_bins = bias_table ? bias_table->ne[0] : 0; + // parallelize by q rows using ggml_vec_dot_f32 float scale = 1.0f; @@ -9085,12 +9089,21 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk( const int32_t * rows = kv_rows ? (const int32_t *) ((const char *) kv_rows->data + iq3*kv_rows->nb[1]) : nullptr; + // bias rows of this query and head, queries of all streams are flattened + const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr; + const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1)*bias_indices->nb[1]) : nullptr; + // online softmax / attention // loop over n_kv and n_head_kv // ref: https://arxiv.org/pdf/2112.05682.pdf for (int64_t ic = ic_start; ic < ic_end; ++ic) { - const float mv = mp ? slope*GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; + float mv = mp ? GGML_CPU_FP16_TO_FP32(mp[ic]) : 0.0f; + if (bias) { + GGML_ASSERT(bins[ic] >= 0 && bins[ic] < n_bins); + mv += bias[bins[ic]]; + } + mv *= slope; if (mv == -INFINITY) { continue; } @@ -9268,6 +9281,10 @@ static void ggml_compute_forward_flash_attn_ext_tiled( const ggml_tensor * kv_rows = dst->src[5]; const int64_t n_kv_cols = kv_rows ? kv_rows->ne[0] : nek1; + const ggml_tensor * bias_table = dst->src[6]; + const ggml_tensor * bias_indices = dst->src[7]; + const int64_t n_bins = bias_table ? bias_table->ne[0] : 0; + int ir = ir0; while (ir < ir1) { // q indices for the start of this tile @@ -9346,8 +9363,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled( bool can_skip = true; for (int tq = 0; tq < tile_rows; tq++) { const ggml_fp16_t * mp_row = (const ggml_fp16_t *)((const char *) mask->data + (iq1 + tq)*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]); + const float * bias = bias_table ? (const float *) ((const char *) bias_table->data + (iq3*neq1 + iq1 + tq)*bias_table->nb[2] + iq2*bias_table->nb[1]) : nullptr; + const int32_t * bins = bias_indices ? (const int32_t *) ((const char *) bias_indices->data + (iq3*neq1 + iq1 + tq)*bias_indices->nb[1]) : nullptr; for (int tk = 0; tk < kv_tile; tk++) { - mask32[tq * KV_TILE_SZ + tk] = slope * GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]); + float m = GGML_CPU_FP16_TO_FP32(mp_row[ic + tk]); + if (bias) { + GGML_ASSERT(bins[ic + tk] >= 0 && bins[ic + tk] < n_bins); + m += bias[bins[ic + tk]]; + } + mask32[tq * KV_TILE_SZ + tk] = slope * m; if (mask32[tq * KV_TILE_SZ + tk] != -INFINITY) { can_skip = false; } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 10aa5af15863..b37065c31dfb 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -582,6 +582,10 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_NONE; #endif// FLASH_ATTN_AVAILABLE + if (ggml_flash_attn_ext_has_indexed_bias(dst)) { + return BEST_FATTN_KERNEL_NONE; + } + const ggml_tensor * KQV = dst; const ggml_tensor * Q = dst->src[0]; const ggml_tensor * K = dst->src[1]; diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp index 53e64b323e5a..e575ee78b45c 100644 --- a/ggml/src/ggml-et/ggml-et.cpp +++ b/ggml/src/ggml-et/ggml-et.cpp @@ -1277,6 +1277,7 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm if (op->type == GGML_TYPE_F32 && op->src[0] && op->src[0]->type == GGML_TYPE_F32 && op->src[1] && (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16) && op->src[2] && (op->src[2]->type == GGML_TYPE_F32 || op->src[2]->type == GGML_TYPE_F16) && op->src[4] == nullptr && op->src[5] == nullptr && + !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_is_contiguous_rows(op) && ggml_is_contiguous_rows(op->src[0])) { float max_bias = 0.0f; float logit_softcap = 0.0f; diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 6d365b8119c7..4e3c5cb8d3df 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -355,8 +355,8 @@ static bool htp_kparams_solve_flash_attn( return false; } - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 293400ff256f..9afaaca3697c 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1747,6 +1747,9 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_OP_ROLL: return ggml_is_contiguous(op->src[0]); case GGML_OP_FLASH_ATTN_EXT: + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } // K/V row lists (ggml_flash_attn_ext_rows): one list of cache rows per q slice if (op->src[5] != NULL) { const struct ggml_tensor * kv_rows = op->src[5]; diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 05a05fe9f95f..2a3f709a2f30 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -12662,8 +12662,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te case GGML_OP_MEAN: return op->src[0]->type == GGML_TYPE_F32; case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + // K/V row lists and indexed bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index b331349d1262..7e64c03c2bc1 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1929,6 +1929,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"}; } + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return {false, "FLASH_ATTN_EXT with indexed bias is not supported"}; + } + // K/V row lists (ggml_flash_attn_ext_rows) are not supported if (op->src[5] != nullptr) { return {false, "FLASH_ATTN_EXT with K/V row lists is not supported"}; diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 7dda19dfd761..75df12c733cb 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7741,8 +7741,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_SOLVE_TRI: return op->src[0]->ne[0] <= SYCL_SOLVE_TRI_MAX_N && op->src[1]->ne[0] <= SYCL_SOLVE_TRI_MAX_K; case GGML_OP_FLASH_ATTN_EXT: - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - return op->src[5] == nullptr && ggml_sycl_flash_attn_ext_supported(device, op); + // K/V row lists and indexed bias are not supported + return op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && ggml_sycl_flash_attn_ext_supported(device, op); default: return false; } diff --git a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp index 86df4cc5f3b2..e4d84fc98d27 100644 --- a/ggml/src/ggml-virtgpu/ggml-backend-device.cpp +++ b/ggml/src/ggml-virtgpu/ggml-backend-device.cpp @@ -30,6 +30,10 @@ static void ggml_backend_remoting_device_get_memory(ggml_backend_dev_t dev, size } static bool ggml_backend_remoting_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) { + if (ggml_flash_attn_ext_has_indexed_bias(op)) { + return false; + } + if ((op->op == GGML_OP_ROPE || op->op == GGML_OP_ROPE_BACK) && !ggml_rope_get_truncate(op)) { return false; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 60cebe49445e..0711166f9671 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -16774,8 +16774,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm } case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - if (op->src[5] != nullptr) { + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op)) { return false; } bool coopmat2 = device->coopmat2; diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index b857f4927764..4bb43926daaa 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -5086,8 +5086,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const { // conservative support checks for whether the more resource-intensive shader paths // can be used, to avoid cases where flash_attn is assigned to the CPU later on - // K/V row lists (ggml_flash_attn_ext_rows) are not supported - supports_op = op->src[5] == nullptr && src0->type == GGML_TYPE_F32 && + // K/V row lists and indexed bias are not supported + supports_op = op->src[5] == nullptr && !ggml_flash_attn_ext_has_indexed_bias(op) && + src0->type == GGML_TYPE_F32 && (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_Q4_0 || src1->type == GGML_TYPE_Q8_0) && (src2->type == GGML_TYPE_F32 || src2->type == GGML_TYPE_F16 || diff --git a/ggml/src/ggml-zdnn/fattn.cpp b/ggml/src/ggml-zdnn/fattn.cpp index e6a0c24cadaf..5e74e67a4936 100644 --- a/ggml/src/ggml-zdnn/fattn.cpp +++ b/ggml/src/ggml-zdnn/fattn.cpp @@ -21,7 +21,7 @@ bool ggml_zdnn_supports_flash_attn_ext(const ggml_backend_zdnn_device_context * memcpy(&logit_softcap, (const float *) op->op_params + 2, sizeof(float)); // sinks, alibi, softcap, sparse k/v sets and k/v row lists are not implemented - if (op->src[4] != nullptr || op->src[5] != nullptr || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { + if (op->src[4] != nullptr || op->src[5] != nullptr || ggml_flash_attn_ext_has_indexed_bias(op) || max_bias != 0.0f || logit_softcap != 0.0f || ggml_get_op_params_i32(op, 4) != 0) { return false; } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 3389dcd63d7c..947342125327 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5545,6 +5545,33 @@ void ggml_flash_attn_ext_add_sinks( a->src[4] = sinks; } +bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { + return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0; +} + +void ggml_flash_attn_ext_add_indexed_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * indices) { + GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT); + GGML_ASSERT((table == NULL) == (indices == NULL)); + a->src[6] = table; + a->src[7] = indices; + ggml_set_op_params_i32(a, 5, table != NULL); + if (!table) { + return; + } + + const struct ggml_tensor * q = a->src[0]; + const struct ggml_tensor * mask = a->src[3]; + GGML_ASSERT(mask && mask->ne[0] == (a->src[5] ? a->src[5]->ne[0] : a->src[1]->ne[1]) && mask->ne[1] == q->ne[1]); + GGML_ASSERT(mask->ne[2] == 1 && mask->ne[3] == q->ne[3]); + GGML_ASSERT(table->type == GGML_TYPE_F32 && ggml_is_contiguous(table)); + GGML_ASSERT(table->ne[1] == q->ne[2] && table->ne[0] > 0 && table->ne[2] == q->ne[1]*q->ne[3] && table->ne[3] == 1); + GGML_ASSERT(indices->type == GGML_TYPE_I32 && ggml_is_contiguous(indices) && ggml_is_matrix(indices)); + GGML_ASSERT(indices->ne[0] == mask->ne[0] && indices->ne[1] == table->ne[2]); +} + // ggml_flash_attn_back struct ggml_tensor * ggml_flash_attn_back( diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 318225c8509a..84f0e5709031 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -9551,6 +9551,124 @@ struct test_flash_attn_ext_kv_rows : public test_case { } }; +// GGML_OP_FLASH_ATTN_EXT with an indexed bias: mask[key, query] += table[indices[key, query], head, query] +struct test_flash_attn_ext_indexed_bias : public test_case { + const int64_t hs; + const int64_t nh; // K/V heads + const int64_t gqa; + const int64_t kv; // mask columns + const int64_t nb; // queries per stream + const int64_t n_stream; + const int64_t n_bins; + const bool kv_rows; // all streams read one K/V cache of 2*kv rows through kv_rows + const bool sinks; + const ggml_type type_KV; + + std::vector rows; + + std::string vars() override { + return VARS_TO_STR10(hs, nh, gqa, kv, nb, n_stream, n_bins, kv_rows, sinks, type_KV); + } + + double max_nmse_err() override { + return 5e-4; + } + + test_flash_attn_ext_indexed_bias(int64_t hs = 128, int64_t nh = 2, int64_t gqa = 3, int64_t kv = 768, int64_t nb = 7, int64_t n_stream = 2, + int64_t n_bins = 17, bool kv_rows = false, bool sinks = true, ggml_type type_KV = GGML_TYPE_F16) + : hs(hs), nh(nh), gqa(gqa), kv(kv), nb(nb), n_stream(n_stream), n_bins(n_bins), kv_rows(kv_rows), sinks(sinks), type_KV(type_KV) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, hs, nb, nh*gqa, n_stream); + ggml_set_name(q, "q"); + + ggml_tensor * k = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream); + ggml_tensor * v = ggml_new_tensor_4d(ctx, type_KV, hs, kv_rows ? 2*kv : kv, nh, kv_rows ? 1 : n_stream); + ggml_set_name(k, "k"); + ggml_set_name(v, "v"); + + ggml_tensor * m = ggml_new_tensor_4d(ctx, GGML_TYPE_F16, kv, nb, 1, n_stream); + ggml_set_name(m, "m"); + + ggml_tensor * r = nullptr; + if (kv_rows) { + r = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, n_stream); + ggml_set_name(r, "r"); + } + + ggml_tensor * table = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_bins, nh*gqa, nb*n_stream); + ggml_set_name(table, "table"); + + ggml_tensor * indices = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, kv, nb*n_stream); + ggml_set_name(indices, "indices"); + + ggml_tensor * out = ggml_flash_attn_ext_rows(ctx, q, k, v, m, r, 1.0f/sqrtf(hs), 0.0f, 0.0f); + if (sinks) { + ggml_tensor * s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nh*gqa); + ggml_set_name(s, "s"); + ggml_flash_attn_ext_add_sinks(out, s); + } + ggml_flash_attn_ext_add_indexed_bias(out, table, indices); + ggml_prec_set_acc(out, GGML_PREC_F32); + ggml_set_name(out, "out"); + + return out; + } + + void initialize_tensors(ggml_context * ctx) override { + std::mt19937 gen(0x1B1A); + + // distinct random cells per stream, some of them padding + rows.assign(kv*n_stream, -1); + if (kv_rows) { + std::vector order(2*kv); + for (int64_t s = 0; s < n_stream; ++s) { + for (int64_t i = 0; i < 2*kv; ++i) { + order[i] = i; + } + std::shuffle(order.begin(), order.end(), gen); + for (int64_t i = 0; i < kv; ++i) { + rows[s*kv + i] = i % 19 == 7 ? -1 : order[i]; + } + } + } + + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + if (strcmp(t->name, "r") == 0) { + ggml_backend_tensor_set(t, rows.data(), 0, rows.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "m") == 0) { + std::vector f(ggml_nelements(t)); + std::uniform_real_distribution dis(-1.0f, 1.0f); + for (int64_t s = 0; s < n_stream; ++s) { + for (int64_t j = 0; j < nb; ++j) { + for (int64_t i = 0; i < kv; ++i) { + const bool pad = kv_rows && rows[s*kv + i] < 0; + const bool drop = (i + 3*j + 5*s) % 11 == 0; + f[(s*nb + j)*kv + i] = pad || drop ? -INFINITY : dis(gen); + } + } + } + std::vector h(f.size()); + ggml_fp32_to_fp16_row(f.data(), h.data(), f.size()); + ggml_backend_tensor_set(t, h.data(), 0, h.size()*sizeof(ggml_fp16_t)); + } else if (strcmp(t->name, "indices") == 0) { + std::vector idx(ggml_nelements(t)); + std::uniform_int_distribution dis(0, n_bins - 1); + for (auto & i : idx) { + i = dis(gen); + } + ggml_backend_tensor_set(t, idx.data(), 0, idx.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "table") == 0) { + init_tensor_uniform(t, -4.0f, 4.0f); + } else if (strcmp(t->name, "s") == 0) { + init_tensor_uniform(t, -10.0f, 10.0f); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_CROSS_ENTROPY_LOSS struct test_cross_entropy_loss : public test_case { const ggml_type type; @@ -13544,6 +13662,21 @@ static std::vector> make_test_cases_eval() { } } + // flash attention with an indexed bias (Inkling 2 relative-position bias) + for (bool kv_rows : {false, true}) { + for (int64_t nb : {1, 7, 65}) { + for (int64_t n_stream : {1, 2}) { + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, nb, n_stream, 17, kv_rows)); + } + } + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias( 64, 2, 3, 768, 7, 2, 17, kv_rows, false)); + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 8, 3, 512, 65, 1, 1025, kv_rows)); + for (ggml_type type : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) { + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 1, 1, 17, kv_rows, true, type)); + test_cases.emplace_back(new test_flash_attn_ext_indexed_bias(128, 2, 3, 768, 7, 2, 17, kv_rows, true, type)); + } + } + // sparse mask with large batch size test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 512)); test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, 4096, 64, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, 2048)); From ab789a246c1a59fbade35a28100bc2d38ea19188 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Mon, 23 Nov 2026 21:01:41 +0200 Subject: [PATCH 076/401] metal : batch concat rows and copy them in vector chunks (#32824) * metal : batch concat rows and copy them in vector chunks The concat kernel copied one element per thread, so wide rows with many rows ran at a fraction of the memory bandwidth. Batch several rows per threadgroup and copy the contiguous dim-0 elements in 4-element chunks when the row is contiguous. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * test : cover concat vector and misaligned row paths Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : hoist the concat src1 row offset into scalars Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : peel to align the concat vector copy Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : vectorize concat rows along any dimension Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : specialize concat with function constants Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : drop the concat row-batch dispatch Batching several rows per threadgroup reduces the number of threads by the batch factor. On machines with a large GPU this leaves too few requests in flight and the copy becomes latency bound: M5 Ultra (36 CPU) f16 [1024,8,256,1] d=0 8.1 us -> 17.2 us f32 [4096,8,256,1] d=0 35.4 us -> 118.5 us f16 [4096,8,256,1] d=2 50.9 us -> 102.0 us An interleaved sweep of the (nth, nrptg) dispatch over the concat perf cases on an M2 Ultra and an M5 Ultra shows that the base dispatch is best or tied for every shape once the rows are vectorized, and that the gains of the previous commit come from the vector copy alone: M2 Ultra f16 [1024,8,256,1] d=0 32.4 us -> 17.0 us M5 Ultra f16 [1024,8,256,1] d=0 13.3 us -> 8.1 us Keep the vector copy and the function-constant specialization, and return to the original dispatch. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) * metal : revert the concat function constants Specializing the concat kernel on the concat dimension and on whether a row is split across threadgroups with function constants makes the strided scalar path slower. Interleaved over the concat perf cases on an M5 Ultra, the specialized kernel is not faster than the plain one, and it costs up to 18% on shapes that are already at the memory bandwidth limit: f32 [2050,8,256,1] b=255 d=0 21.0 us -> 25.1 us f32 [2050,8,256,1] b=256 d=2 31.1 us -> 36.7 us f16 [4096,8,256,1] b=256 d=2 31.2 us -> 36.7 us Revert the specialization and keep copying rows with the runtime arguments. The concat change is now limited to the kernel itself. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) --- ggml/src/ggml-metal/kernels/quantize.metal | 78 +++++++++++++++++++--- tests/test-backend-ops.cpp | 28 ++++++++ 2 files changed, 98 insertions(+), 8 deletions(-) diff --git a/ggml/src/ggml-metal/kernels/quantize.metal b/ggml/src/ggml-metal/kernels/quantize.metal index 663e47d5fd2f..b2624565d8a6 100644 --- a/ggml/src/ggml-metal/kernels/quantize.metal +++ b/ggml/src/ggml-metal/kernels/quantize.metal @@ -159,6 +159,47 @@ template [[host_name("kernel_cpy_q8_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32< template [[host_name("kernel_cpy_tq2_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; +template +static void concat_copy(device const char * src, device char * dst, const int n, const int tid, const int nth) { + if (n <= 0) { + return; + } + + constexpr int N = 16/sizeof(T); + typedef vec T16; + + device const T * x = (device const T *)src; + device T * y = (device T *)dst; + + const size_t rx = (size_t)x % 16; + + if (rx != (size_t)y % 16 || rx % sizeof(T) != 0) { + for (int i = tid; i < n; i += nth) { + y[i] = x[i]; + } + + return; + } + + const int np = min((int)(((16 - rx) % 16)/sizeof(T)), n); + const int n16 = (n - np)/N; + + for (int i = tid; i < np; i += nth) { + y[i] = x[i]; + } + + device const T16 * x16 = (device const T16 *)(x + np); + device T16 * y16 = (device T16 *)(y + np); + + for (int i = tid; i < n16; i += nth) { + y16[i] = x16[i]; + } + + for (int i = np + n16*N + tid; i < n; i += nth) { + y[i] = x[i]; + } +} + template kernel void kernel_concat( constant ggml_metal_kargs_concat & args, @@ -178,20 +219,39 @@ kernel void kernel_concat( return; } - int o[4] = {0, 0, 0, 0}; - o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03)); + const int o0 = args.dim == 0 ? args.ne00 : 0; + const int o1 = args.dim == 1 ? args.ne01 : 0; + const int o2 = args.dim == 2 ? args.ne02 : 0; + const int o3 = args.dim == 3 ? args.ne03 : 0; // chunk ic of nc0 along the row const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0; - const int i0e = min(args.ne0, (ic + 1)*n0); + const int i0b = ntg.y == 1 ? ic*n0 : 0; + const int i0e = ntg.y == 1 ? min(args.ne0, (ic + 1)*n0) : args.ne0; - for (int i0 = ic*n0 + tpitg.x; i0 < i0e; i0 += ntg.x) { + if (args.nb0 == sizeof(T) && args.nb00 == sizeof(T) && args.nb10 == sizeof(T)) { + const bool in0 = i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03; + + const int na = in0 ? min(i0e - i0b, max(0, args.ne00 - i0b)) : 0; + const int nb = i0e - i0b - na; + + device const char * r0 = src0 + i3*args.nb03 + i2*args.nb02 + i1*args.nb01; + device const char * r1 = src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11; + device char * rd = dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1; + + concat_copy(r0 + i0b*sizeof(T), rd + i0b*sizeof(T), na, tpitg.x, ntg.x); + concat_copy(r1 + (i0b + na - o0)*sizeof(T), rd + (i0b + na)*sizeof(T), nb, tpitg.x, ntg.x); + + return; + } + + for (int i0 = i0b + tpitg.x; i0 < i0e; i0 += ntg.x) { device const T * x; if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) { x = (device const T *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00); } else { - x = (device const T *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10); + x = (device const T *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10); } device T * y = (device T *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0); @@ -232,8 +292,10 @@ kernel void kernel_concat_q( return; } - int o[4] = {0, 0, 0, 0}; - o[args.dim] = args.dim == 0 ? args.ne00 : (args.dim == 1 ? args.ne01 : (args.dim == 2 ? args.ne02 : args.ne03)); + const int o0 = args.dim == 0 ? args.ne00 : 0; + const int o1 = args.dim == 1 ? args.ne01 : 0; + const int o2 = args.dim == 2 ? args.ne02 : 0; + const int o3 = args.dim == 3 ? args.ne03 : 0; // chunk ic of nc0 along the row const int n0 = (args.ne0 + args.nc0 - 1)/args.nc0; @@ -245,7 +307,7 @@ kernel void kernel_concat_q( if (i0 < args.ne00 && i1 < args.ne01 && i2 < args.ne02 && i3 < args.ne03) { x = (device const block_q *)(src0 + (i3 )*args.nb03 + (i2 )*args.nb02 + (i1 )*args.nb01 + (i0 )*args.nb00); } else { - x = (device const block_q *)(src1 + (i3 - o[3])*args.nb13 + (i2 - o[2])*args.nb12 + (i1 - o[1])*args.nb11 + (i0 - o[0])*args.nb10); + x = (device const block_q *)(src1 + (i3 - o3)*args.nb13 + (i2 - o2)*args.nb12 + (i1 - o1)*args.nb11 + (i0 - o0)*args.nb10); } device block_q * y = (device block_q *)(dst + i3*args.nb3 + i2*args.nb2 + i1*args.nb1 + i0*args.nb0); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 84f0e5709031..a0268b638a5e 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13201,6 +13201,21 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_concat(GGML_TYPE_Q8_0, {8192, 2, 1, 1}, dim == 0 ? 4096 : 1, dim, 0)); } + for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) { + test_cases.emplace_back(new test_concat(type, {64, 4, 512, 1}, 512, 2, 0)); + test_cases.emplace_back(new test_concat(type, {66, 4, 512, 1}, 512, 2, 0)); + test_cases.emplace_back(new test_concat(type, {128, 4, 512, 1}, 512, 2, 1)); + + for (int dim : { 0, 1, 3 }) { + test_cases.emplace_back(new test_concat(type, {300, 4, 5, 1}, 300, dim, 0)); + } + test_cases.emplace_back(new test_concat(type, {1025, 4, 512, 1}, 1025, 0, 0)); + test_cases.emplace_back(new test_concat(type, {3, 4, 512, 1}, 5, 0, 0)); + } + + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {98306, 8, 1, 1}, 286, 0, 0)); + test_cases.emplace_back(new test_concat(GGML_TYPE_F16, {98306, 8, 1, 1}, 286, 0, 0)); + // GDN conv_input for (int64_t ne_b_d : { 31, 32, 33, 64 }) { test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {3, 10240, 1, 1}, ne_b_d, 0, 16)); @@ -14195,6 +14210,19 @@ static std::vector> make_test_cases_perf() { } } + for (ggml_type type : { GGML_TYPE_F32, GGML_TYPE_F16 }) { + for (int64_t ne0 : { 64, 1024, 4096, 16384 }) { + test_cases.emplace_back(new test_concat(type, {ne0, 8, 256, 1}, 256, 2, 0)); + } + test_cases.emplace_back(new test_concat(type, {2050, 8, 256, 1}, 256, 2, 0)); + test_cases.emplace_back(new test_concat(type, {1024, 8, 2048, 1}, 2048, 2, 0)); + + for (int64_t ne0 : { 64, 1024, 4096, 16384 }) { + test_cases.emplace_back(new test_concat(type, {ne0, 8, 256, 1}, 256, 0, 0)); + } + test_cases.emplace_back(new test_concat(type, {2050, 8, 256, 1}, 255, 0, 0)); + } + // CONT of a 0<->2 permute at DeepSeek-V4 lightning-indexer shapes: // indexer_kq is [n_kv, n_tokens, n_head=64] and gets ggml_cont(ggml_permute(.., 2,1,0,3)). for (int64_t n_kv : { 1024, 1280, 2048, 2304 }) { From 51831d47d0a47b8a7d07c9ff262ebe4b0a211790 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Mon, 23 Nov 2026 21:02:30 +0200 Subject: [PATCH 077/401] metal : add NVFP4 support (#32825) * metal : add NVFP4 support Follow the MXFP4 path: add the UE4M3 scale decode, the NVFP4 dequantizers, a dedicated mat-vec kernel with its MUL_MAT_ID, small-batch and MMA variants, the mul_mm / mul_mm_id and tensor-op variants, and the get_rows and cpy kernels. Enable the type in supports_op. Tested on an M5 Max with ggml-org/NVIDIA-Nemotron-3.5-Lightning-30B-A3B-GGUF:NVFP4 and test-backend-ops (MUL_MAT, MUL_MAT_ID, W4A8/W4A4, CPY, GET_ROWS). Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2)) * metal : skip the small-batch path for NVFP4 With the few-row MMA kernels covering ne11 3..16, the small-batch mat-vec kernels are only reachable at ne11 = 2, where they are 17-59% slower than the generic mat-vec kernel on an M2 Ultra and an M5 Max. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (2x DGX Spark (RDMA, TP=2)) --- ggml/src/ggml-metal/ggml-metal-common.cpp | 2 + ggml/src/ggml-metal/ggml-metal-device.cpp | 12 +- ggml/src/ggml-metal/ggml-metal-device.m | 5 +- ggml/src/ggml-metal/ggml-metal-impl.h | 3 + ggml/src/ggml-metal/kernels/common.h | 13 ++ ggml/src/ggml-metal/kernels/dequantize.h | 39 +++++ ggml/src/ggml-metal/kernels/mul_mm.metal | 9 ++ .../ggml-metal/kernels/mul_mm_tensor.metal | 6 + ggml/src/ggml-metal/kernels/mul_mv.metal | 134 ++++++++++++++++-- ggml/src/ggml-metal/kernels/mul_mv_mma.metal | 1 + ggml/src/ggml-metal/kernels/quantize.metal | 3 + 11 files changed, 214 insertions(+), 13 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-common.cpp b/ggml/src/ggml-metal/ggml-metal-common.cpp index f363122540cf..e8c3cdcc1d37 100644 --- a/ggml/src/ggml-metal/ggml-metal-common.cpp +++ b/ggml/src/ggml-metal/ggml-metal-common.cpp @@ -85,6 +85,7 @@ static bool ggml_metal_mul_mv_mma_type_supported(enum ggml_type type) { case GGML_TYPE_Q1_0: case GGML_TYPE_Q2_0: case GGML_TYPE_MXFP4: + case GGML_TYPE_NVFP4: case GGML_TYPE_Q2_K: case GGML_TYPE_Q3_K: case GGML_TYPE_IQ2_XXS: @@ -134,6 +135,7 @@ static int64_t ggml_metal_mul_mv_mma_rows_min(enum ggml_type type) { case GGML_TYPE_Q2_K: case GGML_TYPE_IQ4_NL: case GGML_TYPE_MXFP4: + case GGML_TYPE_NVFP4: return 3; default: return 2; diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 88ca0b832738..7a732e29e73c 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -1116,6 +1116,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv(ggml_meta nsg = N_SG_MXFP4; nr0 = N_R0_MXFP4; } break; + case GGML_TYPE_NVFP4: + { + nsg = N_SG_NVFP4; + nr0 = N_R0_NVFP4; + } break; case GGML_TYPE_Q2_K: { nsg = N_SG_Q2_K; @@ -1321,7 +1326,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mm_id(ggml_m const bool prec_bf16 = props_dev->has_bfloat && ggml_prec_get_src(op, 1) == GGML_PREC_BF16 && tsrc1 == GGML_TYPE_F32 && - tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4; + tsrc0 != GGML_TYPE_BF16 && tsrc0 != GGML_TYPE_MXFP4 && tsrc0 != GGML_TYPE_NVFP4; const bool prec_f32 = ggml_prec_get_src(op, 1) == GGML_PREC_F32 && tsrc1 == GGML_TYPE_F32; @@ -1423,6 +1428,11 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mv_id(ggml_m nsg = N_SG_MXFP4; nr0 = N_R0_MXFP4; } break; + case GGML_TYPE_NVFP4: + { + nsg = N_SG_NVFP4; + nr0 = N_R0_NVFP4; + } break; case GGML_TYPE_Q2_K: { nsg = N_SG_Q2_K; diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 9afaaca3697c..da2f0acee316 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1532,7 +1532,6 @@ static bool ggml_metal_supports_mul_mat_op( bool mm_path) { if (!has_simdgroup_reduction || op->src[0]->type == GGML_TYPE_F8_E4M3 || - op->src[0]->type == GGML_TYPE_NVFP4 || op->src[0]->type == GGML_TYPE_TQ1_0) { return false; } @@ -1981,6 +1980,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: case GGML_TYPE_TQ2_0: + case GGML_TYPE_NVFP4: switch (op->type) { case GGML_TYPE_F32: case GGML_TYPE_F16: @@ -1995,8 +1995,7 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te }; } case GGML_OP_GET_ROWS: - return op->src[0]->type != GGML_TYPE_NVFP4 && - op->src[0]->type != GGML_TYPE_TQ1_0 && + return op->src[0]->type != GGML_TYPE_TQ1_0 && op->src[0]->type != GGML_TYPE_F8_E4M3; case GGML_OP_SET_ROWS: { diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index aad014d837e9..4e28b2cb99b9 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -50,6 +50,9 @@ #define N_R0_MXFP4 2 #define N_SG_MXFP4 2 +#define N_R0_NVFP4 2 +#define N_SG_NVFP4 2 + #define N_R0_Q2_K 4 #define N_SG_Q2_K 2 diff --git a/ggml/src/ggml-metal/kernels/common.h b/ggml/src/ggml-metal/kernels/common.h index 551a4d7c8e81..237ccfb26b03 100644 --- a/ggml/src/ggml-metal/kernels/common.h +++ b/ggml/src/ggml-metal/kernels/common.h @@ -41,6 +41,7 @@ constexpr constant static float kvalues_iq4nl_f[16] = { -127.f, -104.f, -83.f, -65.f, -49.f, -35.f, -22.f, -10.f, 1.f, 13.f, 25.f, 38.f, 53.f, 69.f, 89.f, 113.f }; +// E2M1 values, shared by MXFP4 and NVFP4 constexpr constant static float kvalues_mxfp4_f[16] = { 0, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f, -0, -.5f, -1.f, -1.5f, -2.f, -3.f, -4.f, -6.f }; @@ -68,6 +69,18 @@ static inline float e8m0_to_fp32(uint8_t x) { return as_type(bits); } +// UE4M3: unsigned, 4 exponent bits with bias 7, 3 mantissa bits - the NVFP4 sub-block scale +static inline float ue4m3_to_fp32(uint8_t x) { + if (x == 0x7F) { + return 0.0f; + } + + const int e = (x >> 3) & 0xF; + const int m = x & 0x7; + + return e == 0 ? m*(1.0f/512.0f) : as_type((uint32_t) (((e + 120) << 23) | (m << 20))); +} + static inline float dot(float x, float y) { return x*y; } diff --git a/ggml/src/ggml-metal/kernels/dequantize.h b/ggml/src/ggml-metal/kernels/dequantize.h index 96b16d7fb442..d99a48666ca9 100644 --- a/ggml/src/ggml-metal/kernels/dequantize.h +++ b/ggml/src/ggml-metal/kernels/dequantize.h @@ -378,6 +378,45 @@ void dequantize_mxfp4_t4(device const block_mxfp4 * xb, short il, thread type4 & reg[3] = d * kvalues_mxfp4_f[(q2[4*il4 + 3] >> shr) & 0x0F]; } +// NVFP4: 64 weights per block split into four 16-weight sub-blocks, each with its own UE4M3 scale. +// the 16 weights of a sub-block are the low nibbles of its 8 bytes followed by the high nibbles +template +void dequantize_nvfp4(device const block_nvfp4 * xb, short il, thread type4x4 & reg) { + device const uint8_t * q = (device const uint8_t *)xb->qs + 8*il; + + const float d = ue4m3_to_fp32(xb->d[il]); + + float4x4 reg_f; + + for (int i = 0; i < 4; ++i) { + device const uint8_t * qb = q + 4*(i % 2); + const uint8_t shr = i < 2 ? 0 : 4; + + reg_f[i][0] = d * kvalues_mxfp4_f[(qb[0] >> shr) & 0x0F]; + reg_f[i][1] = d * kvalues_mxfp4_f[(qb[1] >> shr) & 0x0F]; + reg_f[i][2] = d * kvalues_mxfp4_f[(qb[2] >> shr) & 0x0F]; + reg_f[i][3] = d * kvalues_mxfp4_f[(qb[3] >> shr) & 0x0F]; + } + + reg = (type4x4) reg_f; +} + +template +void dequantize_nvfp4_t4(device const block_nvfp4 * xb, short il, thread type4 & reg) { + const short s = il/4; // sub-block + const short il4 = il%4; // 4-weight chunk within the sub-block + + device const uint8_t * q = (device const uint8_t *)xb->qs + 8*s + 4*(il4 % 2); + + const float d = ue4m3_to_fp32(xb->d[s]); + const uint8_t shr = il4 >= 2 ? 4 : 0; + + reg[0] = d * kvalues_mxfp4_f[(q[0] >> shr) & 0x0F]; + reg[1] = d * kvalues_mxfp4_f[(q[1] >> shr) & 0x0F]; + reg[2] = d * kvalues_mxfp4_f[(q[2] >> shr) & 0x0F]; + reg[3] = d * kvalues_mxfp4_f[(q[3] >> shr) & 0x0F]; +} + template void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg) { const float d = xb->d; diff --git a/ggml/src/ggml-metal/kernels/mul_mm.metal b/ggml/src/ggml-metal/kernels/mul_mm.metal index e16a8ec79649..1d47b9166158 100644 --- a/ggml/src/ggml-metal/kernels/mul_mm.metal +++ b/ggml/src/ggml-metal/kernels/mul_mm.metal @@ -677,6 +677,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32_prec_bf16")]] kernel mul_mm_t ke template [[host_name("kernel_mul_mm_q5_1_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f32_prec_bf16")]] kernel mul_mm_t kernel_mul_mm; @@ -703,6 +704,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32_prec_f32")]] kernel mul_mm_t ker template [[host_name("kernel_mul_mm_q5_1_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f32_prec_f32")]] kernel mul_mm_t kernel_mul_mm; @@ -732,6 +734,7 @@ template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mul_mm_t kernel_mul_m template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f32")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mul_mm_t kernel_mul_mm; @@ -758,6 +761,7 @@ template [[host_name("kernel_mul_mm_q5_0_f16")]] kernel mul_mm_t kernel_mul_m template [[host_name("kernel_mul_mm_q5_1_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q8_0_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_mxfp4_f16")]] kernel mul_mm_t kernel_mul_mm; +template [[host_name("kernel_mul_mm_nvfp4_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q2_K_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q3_K_f16")]] kernel mul_mm_t kernel_mul_mm; template [[host_name("kernel_mul_mm_q4_K_f16")]] kernel mul_mm_t kernel_mul_mm; @@ -794,8 +798,10 @@ template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mul_mm_id kernel_m template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #else template [[host_name("kernel_mul_mm_id_mxfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f32")]] kernel mul_mm_id kernel_mul_mm_id; #endif template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mul_mm_id kernel_mul_mm_id; @@ -853,6 +859,7 @@ template [[host_name("kernel_mul_mm_id_q5_0_f32_prec_f32")]] kernel mul_mm_id template [[host_name("kernel_mul_mm_id_q5_1_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q8_0_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_mxfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q2_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q3_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q4_K_f32_prec_f32")]] kernel mul_mm_id kernel_mul_mm_id; @@ -884,8 +891,10 @@ template [[host_name("kernel_mul_mm_id_q5_1_f16")]] kernel mul_mm_id kernel_m template [[host_name("kernel_mul_mm_id_q8_0_f16")]] kernel mul_mm_id kernel_mul_mm_id; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #else template [[host_name("kernel_mul_mm_id_mxfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; +template [[host_name("kernel_mul_mm_id_nvfp4_f16")]] kernel mul_mm_id kernel_mul_mm_id; #endif template [[host_name("kernel_mul_mm_id_q2_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; template [[host_name("kernel_mul_mm_id_q3_K_f16")]] kernel mul_mm_id kernel_mul_mm_id; diff --git a/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal index 9c1aee0c5690..2ccce5f41358 100644 --- a/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal +++ b/ggml/src/ggml-metal/kernels/mul_mm_tensor.metal @@ -393,6 +393,7 @@ template [[host_name("kernel_mul_mm_tensor_q5_0_f32")]] kernel mul_mm_tensor_ template [[host_name("kernel_mul_mm_tensor_q5_1_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q8_0_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_mxfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_nvfp4_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q2_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q3_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q4_K_f32")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; @@ -419,6 +420,7 @@ template [[host_name("kernel_mul_mm_tensor_q5_0_f16")]] kernel mul_mm_tensor_ template [[host_name("kernel_mul_mm_tensor_q5_1_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q8_0_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_mxfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; +template [[host_name("kernel_mul_mm_tensor_nvfp4_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q2_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q3_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; template [[host_name("kernel_mul_mm_tensor_q4_K_f16")]] kernel mul_mm_tensor_t kernel_mul_mm_tensor; @@ -455,8 +457,10 @@ template [[host_name("kernel_mul_mm_id_tensor_q5_1_f32")]] kernel mul_mm_id_t template [[host_name("kernel_mul_mm_id_tensor_q8_0_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #else template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #endif template [[host_name("kernel_mul_mm_id_tensor_q2_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; template [[host_name("kernel_mul_mm_id_tensor_q3_K_f32")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; @@ -515,8 +519,10 @@ template [[host_name("kernel_mul_mm_id_tensor_q5_1_f16")]] kernel mul_mm_id_t template [[host_name("kernel_mul_mm_id_tensor_q8_0_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #if defined(GGML_METAL_HAS_BF16) template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #else template [[host_name("kernel_mul_mm_id_tensor_mxfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; +template [[host_name("kernel_mul_mm_id_tensor_nvfp4_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; #endif template [[host_name("kernel_mul_mm_id_tensor_q2_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; template [[host_name("kernel_mul_mm_id_tensor_q3_K_f16")]] kernel mul_mm_id_tensor_t kernel_mul_mm_id_tensor; diff --git a/ggml/src/ggml-metal/kernels/mul_mv.metal b/ggml/src/ggml-metal/kernels/mul_mv.metal index 95e9515d5a23..1d6123f42e97 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv.metal @@ -894,6 +894,11 @@ template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_3")]] kernel mul_mv_ext_q4 template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_mxfp4, 32, dequantize_mxfp4_t4>; template [[host_name("kernel_mul_mv_ext_mxfp4_f32_r1_5")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<5, block_mxfp4, 32, dequantize_mxfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_2")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<2, block_nvfp4, 64, dequantize_nvfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_3")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<3, block_nvfp4, 64, dequantize_nvfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_nvfp4, 64, dequantize_nvfp4_t4>; +template [[host_name("kernel_mul_mv_ext_nvfp4_f32_r1_5")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<5, block_nvfp4, 64, dequantize_nvfp4_t4>; + template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_2")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<2, block_iq4_nl, 32, dequantize_iq4_nl_t4>; template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_3")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<3, block_iq4_nl, 32, dequantize_iq4_nl_t4>; template [[host_name("kernel_mul_mv_ext_iq4_nl_f32_r1_4")]] kernel mul_mv_ext_q4_f32_t kernel_mul_mv_ext_q4_f32_disp<4, block_iq4_nl, 32, dequantize_iq4_nl_t4>; @@ -3035,18 +3040,18 @@ kernel void kernel_mul_mv_iq4_xs_f32( // decode the E2M1 value in the low nibble of n, scaled by 2^-14, without a lookup table: the 3 magnitude bits // land in the fp16 exponent/mantissa (e=0 gives the 0.5 subnormal). same decode as MLX's fp4_e2m1 -static inline half mxfp4_dq1(uint32_t n) { +static inline half e2m1_dq1(uint32_t n) { const half c = as_type(ushort((n & 7) << 9)); return (n & 8) ? -c : c; } // low / high nibbles of the 4 bytes of w, in byte order, scaled by 2^-14 -static inline float4 mxfp4_lo4(uint32_t w) { - return float4(mxfp4_dq1(w), mxfp4_dq1(w >> 8), mxfp4_dq1(w >> 16), mxfp4_dq1(w >> 24)); +static inline float4 e2m1_lo4(uint32_t w) { + return float4(e2m1_dq1(w), e2m1_dq1(w >> 8), e2m1_dq1(w >> 16), e2m1_dq1(w >> 24)); } -static inline float4 mxfp4_hi4(uint32_t w) { - return float4(mxfp4_dq1(w >> 4), mxfp4_dq1(w >> 12), mxfp4_dq1(w >> 20), mxfp4_dq1(w >> 28)); +static inline float4 e2m1_hi4(uint32_t w) { + return float4(e2m1_dq1(w >> 4), e2m1_dq1(w >> 12), e2m1_dq1(w >> 20), e2m1_dq1(w >> 28)); } template @@ -3111,10 +3116,10 @@ void kernel_mul_mv_mxfp4_f32_impl( const uint32_t w0 = (a >> sh) | ((b << 1) << (31 - sh)); const uint32_t w1 = (b >> sh) | ((c << 1) << (31 - sh)); - float4 acc1 = yl[0]*mxfp4_lo4(w0); - float4 acc2 = yl[1]*mxfp4_hi4(w0); - float4 acc3 = yl[2]*mxfp4_lo4(w1); - float4 acc4 = yl[3]*mxfp4_hi4(w1); + float4 acc1 = yl[0]*e2m1_lo4(w0); + float4 acc2 = yl[1]*e2m1_hi4(w0); + float4 acc3 = yl[2]*e2m1_lo4(w1); + float4 acc4 = yl[3]*e2m1_hi4(w1); acc1 = (acc1 + acc3) + (acc2 + acc4); @@ -3149,6 +3154,116 @@ kernel void kernel_mul_mv_mxfp4_f32( kernel_mul_mv_mxfp4_f32_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); } +// NVFP4: a 64-weight block holds four 16-weight sub-blocks, each scaled by its own UE4M3 value. +// a thread handles the two sub-blocks of one half of the block, so 16 blocks per loop iteration +template +void kernel_mul_mv_nvfp4_f32_impl( + args_t args, + device const char * src0, + device const char * src1, + device char * dst, + threadgroup char * shmem, + uint3 tgpig, + ushort tiisg, + ushort sgitg) { + const short NSG = FC_mul_mv_nsg; + + const int r0 = tgpig.x; + const int r1 = tgpig.y; + const int im = tgpig.z; + + const int first_row = (r0 * NSG + sgitg) * NR0; + + const uint i12 = im%FC_mul_mv_ne12; + const uint i13 = im/FC_mul_mv_ne12; + + const uint64_t offset0 = first_row*args.nb01 + (i12/FC_mul_mv_r2)*args.nb02 + (i13/FC_mul_mv_r3)*args.nb03; + const uint64_t offset1 = r1*args.nb11 + (i12 )*args.nb12 + (i13 )*args.nb13; + + device const block_nvfp4 * x = (device const block_nvfp4 *) (src0 + offset0); + device const float * y = (device const float *) (src1 + offset1); + + const int nb = args.ne00/QK_NVFP4; + const int ns01 = args.nb01/args.nb00; // this can be larger than nb for permuted src0 tensors + + const short ix = tiisg/2; // 0...15 + const short it = tiisg%2; // 0 or 1 + + float4 yl[8]; + float sumf[NR0]={0.f}; + + device const float * yb = y + ix*QK_NVFP4 + it*32; + + // note: just the check `ib < nb` is enough, but adding the redundant `&& ib < ns01` check makes the kernel a bit faster + // no idea why that is - needs some deeper investigation [TAG_MUL_MV_WEIRD] + for (int ib = ix; ib < nb && ib < ns01; ib += 16) { + device const float4 * y4 = (device const float4 *) yb; + + yl[0] = y4[0]; + yl[1] = y4[2]; + yl[2] = y4[1]; + yl[3] = y4[3]; + yl[4] = y4[4]; + yl[5] = y4[6]; + yl[6] = y4[5]; + yl[7] = y4[7]; + + FOR_UNROLL (short row = 0; row < NR0; row++) { + device const block_nvfp4 & xb = x[row*ns01 + ib]; + + // a block is 36 bytes, so its 16 quant bytes are 4-byte aligned and read as four words + device const uint32_t * pw = (device const uint32_t *)(xb.qs + 16*it); + + const uint32_t w0 = pw[0]; + const uint32_t w1 = pw[1]; + const uint32_t w2 = pw[2]; + const uint32_t w3 = pw[3]; + + float4 acc1 = yl[0]*e2m1_lo4(w0); + float4 acc2 = yl[1]*e2m1_hi4(w0); + float4 acc3 = yl[2]*e2m1_lo4(w1); + float4 acc4 = yl[3]*e2m1_hi4(w1); + + float4 acc5 = yl[4]*e2m1_lo4(w2); + float4 acc6 = yl[5]*e2m1_hi4(w2); + float4 acc7 = yl[6]*e2m1_lo4(w3); + float4 acc8 = yl[7]*e2m1_hi4(w3); + + acc1 = (acc1 + acc3) + (acc2 + acc4); + acc5 = (acc5 + acc7) + (acc6 + acc8); + + // 16384 undoes the 2^-14 of the decode + sumf[row] += ue4m3_to_fp32(xb.d[2*it + 0])*16384.0f*((acc1[0] + acc1[1]) + (acc1[2] + acc1[3])) + + ue4m3_to_fp32(xb.d[2*it + 1])*16384.0f*((acc5[0] + acc5[1]) + (acc5[2] + acc5[3])); + } + + yb += 16 * QK_NVFP4; + } + + device float * dst_f32 = (device float *) dst + (uint64_t)im*args.ne0*args.ne1 + (uint64_t)r1*args.ne0; + + for (int row = 0; row < NR0 && first_row + row < args.ne0; ++row) { + float sum_all = simd_sum(sumf[row]); + if (tiisg == 0) { + dst_f32[first_row + row] = sum_all; + } + } +} + +[[host_name("kernel_mul_mv_nvfp4_f32")]] +kernel void kernel_mul_mv_nvfp4_f32( + constant ggml_metal_kargs_mul_mv & args, + device const char * src0, + device const char * src1, + device char * dst, + threadgroup char * shmem [[threadgroup(0)]], + uint3 tgpig[[threadgroup_position_in_grid]], + ushort tiisg[[thread_index_in_simdgroup]], + ushort sgitg[[simdgroup_index_in_threadgroup]]) { + + kernel_mul_mv_nvfp4_f32_impl(args, src0, src1, dst, shmem, tgpig, tiisg, sgitg); +} + template void kernel_mul_mv_tq2_0_f32_impl( args_t args, @@ -3415,6 +3530,7 @@ template [[host_name("kernel_mul_mv_id_q5_0_f32")]] kernel kernel_mul_mv_id_t template [[host_name("kernel_mul_mv_id_q5_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_mxfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; +template [[host_name("kernel_mul_mv_id_nvfp4_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_q2_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; template [[host_name("kernel_mul_mv_id_q3_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id>>; diff --git a/ggml/src/ggml-metal/kernels/mul_mv_mma.metal b/ggml/src/ggml-metal/kernels/mul_mv_mma.metal index 5cf245d5210d..287834e3e9e3 100644 --- a/ggml/src/ggml-metal/kernels/mul_mv_mma.metal +++ b/ggml/src/ggml-metal/kernels/mul_mv_mma.metal @@ -611,6 +611,7 @@ MUL_MV_MMA_GEN("bf16", bfloat4x4, 1, dequantize_bf16) MUL_MV_MMA_GEN("q1_0", block_q1_0, 8, dequantize_q1_0) MUL_MV_MMA_GEN("q2_0", block_q2_0, 4, dequantize_q2_0) MUL_MV_MMA_GEN("mxfp4", block_mxfp4, 2, dequantize_mxfp4) +MUL_MV_MMA_GEN("nvfp4", block_nvfp4, 4, dequantize_nvfp4) MUL_MV_MMA_GEN("q2_K", block_q2_K, QK_NL, dequantize_q2_K) MUL_MV_MMA_GEN("q3_K", block_q3_K, QK_NL, dequantize_q3_K) MUL_MV_MMA_GEN("iq2_xxs", block_iq2_xxs, QK_NL, dequantize_iq2_xxs) diff --git a/ggml/src/ggml-metal/kernels/quantize.metal b/ggml/src/ggml-metal/kernels/quantize.metal index b2624565d8a6..d2940ed763b4 100644 --- a/ggml/src/ggml-metal/kernels/quantize.metal +++ b/ggml/src/ggml-metal/kernels/quantize.metal @@ -146,6 +146,7 @@ template [[host_name("kernel_cpy_q4_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32< template [[host_name("kernel_cpy_q5_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q5_1_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q8_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; +template [[host_name("kernel_cpy_nvfp4_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_tq2_0_f32")]] kernel cpy_q_f_t kernel_cpy_q_f32; @@ -156,6 +157,7 @@ template [[host_name("kernel_cpy_q4_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32< template [[host_name("kernel_cpy_q5_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q5_1_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_q8_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; +template [[host_name("kernel_cpy_nvfp4_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; template [[host_name("kernel_cpy_tq2_0_f16")]] kernel cpy_q_f_t kernel_cpy_q_f32; @@ -403,6 +405,7 @@ template [[host_name("kernel_get_rows_q5_0")]] kernel get_rows_q_t kernel_get template [[host_name("kernel_get_rows_q5_1")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q8_0")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_mxfp4")]] kernel get_rows_q_t kernel_get_rows_q; +template [[host_name("kernel_get_rows_nvfp4")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q2_K")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q3_K")]] kernel get_rows_q_t kernel_get_rows_q; template [[host_name("kernel_get_rows_q4_K")]] kernel get_rows_q_t kernel_get_rows_q; From 8355b886250efcb490dec7431c3c0ec1463277a5 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Mon, 23 Nov 2026 21:38:18 +0100 Subject: [PATCH 078/401] ui: remove the Matte theme and the Light surfaces setting (#32906) Paper is now the only light theme: its surface tokens stay the base values, and the theme-matte overrides, the setting, its enum and the Storybook surface switch are gone. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/.storybook/preview.ts | 23 +----------------- ui/apps/chat/DESIGN.md | 24 ++++--------------- ui/apps/chat/scripts/design-md.js | 5 +--- .../settings/SettingsChat/SettingsChat.svelte | 5 ---- .../lib/constants/settings-keys.constants.ts | 1 - .../src/lib/constants/settings.constants.ts | 15 +----------- ui/apps/chat/src/lib/enums/index.ts | 1 - ui/apps/chat/src/lib/enums/ui.enums.ts | 6 ----- ui/apps/chat/src/lib/utils/css.ts | 12 ---------- ui/apps/chat/src/lib/utils/index.ts | 2 +- ui/apps/chat/src/routes/+layout.svelte | 7 +----- ui/lib/ui/.storybook/preview.ts | 23 ------------------ ui/lib/ui/README.md | 2 +- ui/lib/ui/src/lib/styles/theme.css | 2 +- .../ui/src/lib/styles/tokens/components.css | 5 ---- ui/lib/ui/src/lib/styles/tokens/semantic.css | 18 ++++---------- 16 files changed, 16 insertions(+), 135 deletions(-) diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 7e7a58d167a8..22f04dd88609 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -1,7 +1,5 @@ import '../src/app.css'; import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; -import { SurfaceTheme } from '#lib/enums/ui.enums.ts'; -import { applySurfaceTheme } from '#lib/utils/css.ts'; // the docs pages' styles, shared with the library's Storybook import '../../../lib/ui/.storybook/docs.css'; import { applyColorScheme } from './color-scheme'; @@ -97,31 +95,12 @@ const preview: Preview = { ], title: 'Interaction pace' } - }, - // the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white) - surface: { - description: 'Light surface theme', - toolbar: { - dynamicTitle: true, - icon: 'paintbrush', - items: [ - { title: 'Paper', value: SurfaceTheme.PAPER }, - { title: 'Matte', value: SurfaceTheme.MATTE } - ], - title: 'Surface' - } } }, initialGlobals: { - interactionPace: 'human', - surface: SurfaceTheme.PAPER + interactionPace: 'human' }, decorators: [ - (story, context) => { - applySurfaceTheme(context.globals.surface); - - return story(); - }, // `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot) (story, context) => ({ Component: ModeWatcherDecorator, diff --git a/ui/apps/chat/DESIGN.md b/ui/apps/chat/DESIGN.md index efbc65d93685..fc624676d487 100644 --- a/ui/apps/chat/DESIGN.md +++ b/ui/apps/chat/DESIGN.md @@ -5,8 +5,7 @@ description: >- Llama UI, the design system and components of Llama Chat, the chat client llama-server bundles. Neutral and quiet: frosted matte surfaces with faint blue-grey hairlines, near-flat fills, and status colours for success, warning, error and info. Tokens come in - three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs and a - "-matte" twin where the Matte light theme does) and components. The colors, typography and + three tiers: primitives, semantic tokens (with a "-dark" twin where dark mode differs) and components. The colors, typography and rounded sections are generated from ui/lib/ui/src/lib/styles by `npm run design:tokens` in ui/apps/chat; spacing, components and the prose are kept in sync with the CSS by hand. colors: @@ -123,14 +122,6 @@ colors: highlight-inverse: '{colors.white-a12}' sheen-start: '{colors.white-a20}' elevation-ring: '{colors.black-a5}' - surface-page-matte: '{colors.neutral-0}' - surface-glass-matte: 'oklch(0.97 0 0 / 0.6)' - surface-code-matte: '{colors.neutral-50}' - surface-success-matte: 'color-mix(in oklab, {colors.fill-success} 11%, {colors.surface-page-matte})' - surface-warning-matte: 'color-mix(in oklab, {colors.fill-warning} 11%, {colors.surface-page-matte})' - surface-danger-matte: 'color-mix(in oklab, {colors.fill-danger} 11%, {colors.surface-page-matte})' - surface-info-matte: 'color-mix(in oklab, {colors.fill-info} 11%, {colors.surface-page-matte})' - field-background-matte: '{colors.surface-page-matte}' surface-page-dark: '{colors.neutral-925}' surface-muted-dark: '{colors.neutral-800}' surface-emphasis-dark: '{colors.neutral-750}' @@ -815,9 +806,8 @@ here. The `spacing` and `components` sections and the prose are written by hand; disagree with the CSS, the CSS wins and this file is updated to match. Storybook shows every tier under **Llama UI › Foundations › Colors**. -Paper light mode is the base. A semantic token that resolves differently in dark mode has a -`-dark` twin here, and one that resolves differently in Matte a `-matte` twin; components list -a `-dark` entry wherever their colours change. Translucent component +Light mode is the base. A semantic token that resolves differently in dark mode has a +`-dark` twin here; components list a `-dark` entry wherever their colours change. Translucent component fills are given as they render over the page, so contrast checks see the real colour. ## Colors @@ -841,12 +831,8 @@ creative (a shape, a numeral, an illustration). Artwork takes its colours from t the `art-*` primitives: the day sky and the night sky (llama.app's light and dark hero grounds) and cinder, the accent orange; never from the status colours, and never red. -Light mode has two surface themes, which share everything else (the palette, buttons, fields, -badges, shadows and dark mode): **Paper**, the default, sets white panels, fields and keys on a -faint grey page (`neutral-25`); **Matte** sets grey glass on a white page. Matte is the -`theme-matte` class on ``, chosen with the Light surfaces setting (Settings → General) or -the Surface switch in Storybook's toolbar, and only its surface tokens differ: `surface-page`, -`surface-glass`, `surface-code`, `field-background` and `float-panel-background-modal`. +Light mode sets white panels, fields and keys on a faint grey page (`neutral-25`). Dark mode shares the +palette, buttons, fields, badges and shadows. - **Surfaces:** `surface-page` for the page, `surface-muted` for quiet panels, `surface-emphasis` and `surface-selected` for stronger fills and hover or selected rows, diff --git a/ui/apps/chat/scripts/design-md.js b/ui/apps/chat/scripts/design-md.js index 94c90b1f5452..385d99e3c102 100644 --- a/ui/apps/chat/scripts/design-md.js +++ b/ui/apps/chat/scripts/design-md.js @@ -28,10 +28,7 @@ const SOURCES = { theme: fileURLToPath(new URL('theme.css', styles)) }; // the selectors of the themes a semantic token may change in, and the suffix its twin takes here -const THEMES = [ - { selector: '.theme-matte:not(.dark)', suffix: '-matte' }, - { selector: '.dark', suffix: '-dark' } -]; +const THEMES = [{ selector: '.dark', suffix: '-dark' }]; // the type roles, by the @theme names Tailwind turns into text-body, text-label-sm, ...: a size with a line height const TYPE_ROLE = /^--text-([a-z]+(?:-[a-z]+)*)$/; // body and caption text takes the weight around it, which is regular unless a parent says otherwise diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte index d54d56a20017..fd058cea6679 100644 --- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte +++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChat.svelte @@ -21,7 +21,6 @@ import { ColorMode } from '#lib/enums/ui.enums.ts'; import { modelsStore, serverStore, settingsStore } from '#lib/stores/index.ts'; import type { SettingsSection, SettingsSectionTitle } from '#lib/types/index.ts'; - import { applySurfaceTheme } from '#lib/utils/index.ts'; import { setMode } from 'mode-watcher'; import { fade } from 'svelte/transition'; interface Props { @@ -91,9 +90,6 @@ function handleConfigChange(key: string, value: string | boolean) { localConfig[key] = value; - // the surface theme previews at once, like the colour theme - if (key === SETTINGS_KEYS.SURFACE_THEME) applySurfaceTheme(value); - // discover needs the hub metadata reads: checking it turns the hub on, // unchecking it turns the hub back off, so the checkbox never lies if (key === SETTINGS_KEYS.ENABLE_DISCOVER_MODELS) { @@ -108,7 +104,6 @@ function handleReset() { localConfig = { ...settingsStore.config }; setMode(localConfig.theme as ColorMode); - applySurfaceTheme(localConfig[SETTINGS_KEYS.SURFACE_THEME]); mobileHeader?.updateCarousel(); } diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts index b3d37b0e0826..375b935b0a5a 100644 --- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts @@ -73,7 +73,6 @@ export const SETTINGS_KEYS = { SHOW_THOUGHT_IN_PROGRESS: 'showThoughtInProgress', SHOW_TOOL_CALL_IN_PROGRESS: 'showToolCallInProgress', SINGLE_ROW_CHAT_FORM: 'singleRowChatForm', - SURFACE_THEME: 'surfaceTheme', SYMBOLIC_MATH_ENABLED: 'symbolicMathEnabled', SYSTEM_MESSAGE: 'systemMessage', // Sampling diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index 0c4d4c25078e..3109299c3feb 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -11,9 +11,7 @@ import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice'; import AudioLines from '@lucide/svelte/icons/audio-lines'; import Code from '@lucide/svelte/icons/code'; import Database from '@lucide/svelte/icons/database'; -import File from '@lucide/svelte/icons/file'; import Funnel from '@lucide/svelte/icons/funnel'; -import GlassWater from '@lucide/svelte/icons/glass-water'; import ListRestart from '@lucide/svelte/icons/list-restart'; import Mic from '@lucide/svelte/icons/mic'; import Monitor from '@lucide/svelte/icons/monitor'; @@ -22,7 +20,7 @@ import PencilRuler from '@lucide/svelte/icons/pencil-ruler'; import SlidersVertical from '@lucide/svelte/icons/sliders-vertical'; import Sun from '@lucide/svelte/icons/sun'; import TextCursorInput from '@lucide/svelte/icons/text-cursor-input'; -import { SurfaceTheme, SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts'; +import { SyncableParameterType, VoiceInputMode } from '#lib/enums/index.ts'; import { SettingsFieldType } from '#lib/enums/settings.enums.ts'; import { ColorMode } from '#lib/enums/ui.enums.ts'; import type { @@ -84,17 +82,6 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [ ], type: SettingsFieldType.SELECT }, - { - defaultValue: SurfaceTheme.PAPER, - help: 'Choose how the light theme draws its surfaces: Paper puts white panels, fields and buttons on a faint grey page; Matte puts grey glass on a white page. Dark mode is the same for both.', - key: SETTINGS_KEYS.SURFACE_THEME, - label: 'Light surfaces', - options: [ - { icon: File, label: 'Paper', value: SurfaceTheme.PAPER }, - { icon: GlassWater, label: 'Matte', value: SurfaceTheme.MATTE } - ], - type: SettingsFieldType.SELECT - }, { defaultValue: '', help: `Set the API Key if you are using ${CLI_FLAGS.API_KEY} option for the server.`, diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 1c42190aa41d..9fb53f8af05c 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -105,7 +105,6 @@ export { ScrollCarouselVariant, SidebarAction, SidebarSectionKind, - SurfaceTheme, TooltipSide, UrlProtocol } from './ui.enums'; diff --git a/ui/apps/chat/src/lib/enums/ui.enums.ts b/ui/apps/chat/src/lib/enums/ui.enums.ts index c4605943408c..fd55508d0a0d 100644 --- a/ui/apps/chat/src/lib/enums/ui.enums.ts +++ b/ui/apps/chat/src/lib/enums/ui.enums.ts @@ -1,11 +1,5 @@ export { ColorMode, MouseButton, PointerType, TooltipSide } from '@ggml-org/llama-ui/enums'; -/** The light surface theme: Paper (white panels on a faint grey page) or Matte (grey glass on white). */ -export enum SurfaceTheme { - MATTE = 'matte', - PAPER = 'paper' -} - /** * ScrollCarousel arrow placement. */ diff --git a/ui/apps/chat/src/lib/utils/css.ts b/ui/apps/chat/src/lib/utils/css.ts index eaca26f1b501..99351a7f4493 100644 --- a/ui/apps/chat/src/lib/utils/css.ts +++ b/ui/apps/chat/src/lib/utils/css.ts @@ -1,15 +1,3 @@ -import { SurfaceTheme } from '#lib/enums/index.ts'; - -/** - * Applies the light surface theme: Matte sets the theme-matte class on , which the tokens - * read (see tokens/semantic.css); Paper, the default, needs no class. - */ -export function applySurfaceTheme(theme: unknown): void { - if (typeof document === 'undefined') return; - - document.documentElement.classList.toggle('theme-matte', theme === SurfaceTheme.MATTE); -} - /** * Converts a rem CSS value to pixels based on the document root font size. */ diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index c1e2ee4a129d..ae28ff9cd23c 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -390,7 +390,7 @@ export { type GgufMetadata, type GgufValue, readGgufMetadata } from './gguf-meta export { uuid } from './uuid'; // CSS utilities -export { applySurfaceTheme, remToPx } from './css'; +export { remToPx } from './css'; // Audio format helper (used by agentic store and chat service) export { getAudioInputFormat } from './audio-format'; diff --git a/ui/apps/chat/src/routes/+layout.svelte b/ui/apps/chat/src/routes/+layout.svelte index 8dfebfe4c394..8fcef551be52 100644 --- a/ui/apps/chat/src/routes/+layout.svelte +++ b/ui/apps/chat/src/routes/+layout.svelte @@ -33,7 +33,7 @@ } from '#lib/stores/index.ts'; import { initStores } from '#lib/stores/init.ts'; import { withBase } from '#lib/utils/base-path.ts'; - import { applySurfaceTheme, hapticTap } from '#lib/utils/index.ts'; + import { hapticTap } from '#lib/utils/index.ts'; import { browser } from '$app/env'; import { afterNavigate, goto } from '$app/navigation'; import { page } from '$app/state'; @@ -53,11 +53,6 @@ let chatSidebar: { editActiveConversation?: () => void } | undefined = $state(); - // the light surface theme (Paper or Matte) follows the saved setting - $effect(() => { - applySurfaceTheme(settingsStore.config[SETTINGS_KEYS.SURFACE_THEME]); - }); - let showBuildVersion = $derived( settingsStore.config[SETTINGS_KEYS.SHOW_BUILD_VERSION] as boolean ); diff --git a/ui/lib/ui/.storybook/preview.ts b/ui/lib/ui/.storybook/preview.ts index 05ff2ad7c38d..c1793e1040ea 100644 --- a/ui/lib/ui/.storybook/preview.ts +++ b/ui/lib/ui/.storybook/preview.ts @@ -49,30 +49,7 @@ const preview: Preview = { test: 'todo' } }, - globalTypes: { - // the light surface theme: Paper (white panels on a grey page) or Matte (grey glass on white) - surface: { - description: 'Light surface theme', - toolbar: { - dynamicTitle: true, - icon: 'paintbrush', - items: [ - { title: 'Paper', value: 'paper' }, - { title: 'Matte', value: 'matte' } - ], - title: 'Surface' - } - } - }, - initialGlobals: { - surface: 'paper' - }, decorators: [ - (story, context) => { - document.documentElement.classList.toggle('theme-matte', context.globals.surface === 'matte'); - - return story(); - }, // `parameters.colorScheme` fixes a story to light or dark, whatever the viewer chose (a scene in a store screenshot) (story, context) => ({ Component: ModeWatcherDecorator, diff --git a/ui/lib/ui/README.md b/ui/lib/ui/README.md index 60abf7592c04..83a42f33d063 100644 --- a/ui/lib/ui/README.md +++ b/ui/lib/ui/README.md @@ -27,7 +27,7 @@ beside the apps built on it in `ui/apps`. `tw-animate-css` (both peer dependencies) and `@ggml-org/llama-brand`'s `css/colors.css` imported before it. - `tokens.css`: the three tiers of tokens only, also after `@ggml-org/llama-brand`'s `css/colors.css`. `fonts.css`: Llama Sans and Llama Mono. `surfaces.css`: the matte surface utilities. -- Dark mode is the `dark` class on ``; the Matte light surfaces are the `theme-matte` class. +- Dark mode is the `dark` class on ``. ## What's in it diff --git a/ui/lib/ui/src/lib/styles/theme.css b/ui/lib/ui/src/lib/styles/theme.css index 4f89b25718be..03ff92773c1e 100644 --- a/ui/lib/ui/src/lib/styles/theme.css +++ b/ui/lib/ui/src/lib/styles/theme.css @@ -10,7 +10,7 @@ * @import '@ggml-org/llama-brand/css/colors.css'; * @import '@ggml-org/llama-ui/theme.css'; * - * Dark mode is the `dark` class on ; the Matte light surfaces are the `theme-matte` class. + * Dark mode is the `dark` class on . */ @import './fonts.css'; diff --git a/ui/lib/ui/src/lib/styles/tokens/components.css b/ui/lib/ui/src/lib/styles/tokens/components.css index 43e5fc345911..24e6143b4d57 100644 --- a/ui/lib/ui/src/lib/styles/tokens/components.css +++ b/ui/lib/ui/src/lib/styles/tokens/components.css @@ -71,11 +71,6 @@ /* status lamps and orbs read the status tokens through orb-danger and friends */ } -/* Matte: dialogs on the page colour (white), like the page under them */ -.theme-matte:not(.dark) { - --float-panel-background-modal: var(--surface-page); -} - .dark { /* in dark the keys stay frosted glass and quiet fills, lighter than the page */ --button-secondary-background: var(--surface-glass); diff --git a/ui/lib/ui/src/lib/styles/tokens/semantic.css b/ui/lib/ui/src/lib/styles/tokens/semantic.css index 2301689a08d8..842e7085912f 100644 --- a/ui/lib/ui/src/lib/styles/tokens/semantic.css +++ b/ui/lib/ui/src/lib/styles/tokens/semantic.css @@ -6,15 +6,13 @@ * mixed from another semantic token by a fixed rule and so follows it through every theme. The rules: * soft text is the text colour at 70%; a hover fill is the fill at 90%; a status surface is its fill mixed * into the page and a status line its fill mixed into the default line; a dark shadow is the light one, - * --elevation-strength times as dense. Derivations are declared once, in :root: .dark and .theme-matte sit - * on the same element, so they resolve from that theme's picks. + * --elevation-strength times as dense. Derivations are declared once, in :root: .dark sits on the + * same element, so they resolve from that theme's picks. * - * Light mode comes in two surface themes that share everything else (colours, buttons, fields, - * shadows): Paper, the default, puts white panels, fields and keys on a faint grey page; Matte - * (the theme-matte class on ) puts grey glass on a white page. + * The light surfaces are paper: white panels, fields and keys on a faint grey page. */ :root { - /* surfaces: what a region of the page sits on. Paper: the page a faint grey, so glass, fields + /* surfaces: what a region of the page sits on. The page a faint grey, so glass, fields and keys, white, sit lighter than it */ --surface-page: var(--neutral-25); --surface-muted: var(--neutral-100); @@ -133,14 +131,6 @@ --blur-control: 0.75rem; } -/* Matte, the alternative light theme: grey glass on a white page, fields on the page colour */ -.theme-matte:not(.dark) { - --surface-page: var(--neutral-0); - --surface-glass: color-mix(in oklch, var(--neutral-100) 60%, transparent); - --surface-code: var(--neutral-50); - --field-background: var(--surface-page); -} - .dark { --surface-page: var(--neutral-925); --surface-muted: var(--neutral-800); From fd24ee26ade8e39a1722aac1b08976fec29f5e17 Mon Sep 17 00:00:00 2001 From: Hongqiang Wang Date: Mon, 23 Nov 2026 12:39:04 -0800 Subject: [PATCH 079/401] opencl: fetch the Adreno binary kernel library at configure time for Windows on Snapdragon (#31759) * opencl: fetch the Adreno binary kernel library at configure time Make GGML_OPENCL_USE_ADRENO_BIN_KERNELS an option, default ON, and add GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH, default ON. On Windows, CMake downloads the pinned adreno-opencl-kernels release from the Qualcomm Software Center, verifies its SHA256, and copies the DLL and its license next to the executables. A failed download is only a warning; the backend then uses its builtin kernels. The opencl-adreno release job turns the fetch off, since it ships only ggml-opencl.dll. * opencl: fetch the Adreno binary kernel library only on ARM64 The library is built for Windows on ARM64 only. * opencl: add download timeout and better handle output dir Assisted-by: Codex * opencl: add .txt to license file Assisted-by: Codex --------- Co-authored-by: Li He --- .github/workflows/release.yml | 2 +- docs/backend/OPENCL.md | 25 ++++++---- ggml/CMakeLists.txt | 2 + ggml/src/ggml-opencl/CMakeLists.txt | 72 +++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 10 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c918feb06916..11c97ea2cee4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1129,7 +1129,7 @@ jobs: target: 'ggml-vulkan' - backend: 'opencl-adreno' arch: 'arm64' - defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON' + defines: '-G "Ninja Multi-Config" -D CMAKE_TOOLCHAIN_FILE=cmake/arm64-windows-llvm.cmake -DCMAKE_PREFIX_PATH="$env:RUNNER_TEMP/opencl-arm64-release" -DGGML_OPENCL=ON -DGGML_OPENCL_USE_ADRENO_KERNELS=ON -DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF' target: 'ggml-opencl' steps: diff --git a/docs/backend/OPENCL.md b/docs/backend/OPENCL.md index 0a9a324fd68d..c912d331cbc2 100644 --- a/docs/backend/OPENCL.md +++ b/docs/backend/OPENCL.md @@ -83,22 +83,29 @@ Since common quantizations are supported now, it is recommanded to download GGUF A prebuilt binary kernel library has been introduced for Adreno GPUs. It currently targets X2 GPUs (X2-90, X2-85 and X2-45) found in Snapdragon X2 SoC. The library currently contains kernels for MUL_MAT_ID with Q4_0, Q4_1, Q4_K, MXFP4. -The library must be manually downloaded from https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML. - -To allow using the kernel library, add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON` when configuring with CMake. -Then, extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables. +The library is published at https://softwarecenter.qualcomm.com/catalog/item/Adreno_Kernel_Library_GGML. +Its use is subject to the license in the `license.txt` file shipped with it. + +The library is enabled by default (`GGML_OPENCL_USE_ADRENO_BIN_KERNELS=ON`). +On Windows on ARM64, CMake downloads the library version pinned in `ggml/src/ggml-opencl/CMakeLists.txt` during configuration (`GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=ON`). +The download is verified against a SHA256 hash, and the build copies `adreno-opencl-kernels.dll` and `LICENSE-adreno-opencl-kernels.txt` alongside the executables. +If the download fails, configuration continues with a warning. +To skip the download, add `-DGGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF`, then extract `adreno-opencl-kernels.dll` from the zip file downloaded from the above URL and put it alongside the executables yourself. If kernels compatible with the current GPU are found in the library, they will be loaded and used. +If the library is missing, the builtin kernels are used. +Add `-DGGML_OPENCL_USE_ADRENO_BIN_KERNELS=OFF` to disable the library entirely. ## CMake Options The OpenCL backend has the following CMake options that control the behavior of the backend. -| CMake options | Default value | Description | -|:------------------------------------:|:--------------:|:------------------------------------------| -| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. | -| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. | -| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `OFF` | Allow using binary kernel lib for Adreno. | +| CMake options | Default value | Description | +|:--------------------------------------:|:--------------:|:--------------------------------------------------------| +| `GGML_OPENCL_EMBED_KERNELS` | `ON` | Embed OpenCL kernels into the executable. | +| `GGML_OPENCL_USE_ADRENO_KERNELS` | `ON` | Use kernels optimized for Adreno. | +| `GGML_OPENCL_USE_ADRENO_BIN_KERNELS` | `ON` | Allow using binary kernel lib for Adreno. | +| `GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH` | `ON` | Download the binary kernel lib for Adreno (Windows ARM64). | ## Decomposed Flash Attention diff --git a/ggml/CMakeLists.txt b/ggml/CMakeLists.txt index 03bdb03edae1..06278c2d3433 100644 --- a/ggml/CMakeLists.txt +++ b/ggml/CMakeLists.txt @@ -269,6 +269,8 @@ option(GGML_OPENCL "ggml: use OpenCL" option(GGML_OPENCL_PROFILING "ggml: use OpenCL profiling (increases overhead)" OFF) option(GGML_OPENCL_EMBED_KERNELS "ggml: embed kernels" ON) option(GGML_OPENCL_USE_ADRENO_KERNELS "ggml: use optimized kernels for Adreno" ON) +option(GGML_OPENCL_USE_ADRENO_BIN_KERNELS "ggml: load the Adreno binary kernel library" ON) +option(GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH "ggml: fetch the Adreno binary kernel library" ON) set (GGML_OPENCL_TARGET_VERSION "300" CACHE STRING "ggml: OpenCL API version to target") diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index d71802c0385c..1520f8d40e3a 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -36,6 +36,78 @@ endif () if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS) message(STATUS "OpenCL will use precompiled binary kernels for Adreno (improved performance on some platforms)") add_compile_definitions(GGML_OPENCL_USE_ADRENO_BIN_KERNELS) + target_link_libraries(${TARGET_NAME} PRIVATE ${CMAKE_DL_LIBS}) +endif () + +# The library is only published for Windows on ARM64. A failed download is not +# fatal: without the library the backend uses its builtin kernels. +string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR) +if (GGML_OPENCL_USE_ADRENO_BIN_KERNELS AND GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH AND + WIN32 AND ADRENO_BIN_KERNELS_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64)$") + # Bump the version and hash together when a new library release is published. + set(ADRENO_BIN_KERNELS_VERSION "0.0.15") + set(ADRENO_BIN_KERNELS_ZIP_SHA256 "325c89a3bce51abe95f40c6bacece005d5ca9cf6166eb5f17d33592cd13ab795") + set(ADRENO_BIN_KERNELS_URL "https://softwarecenter.qualcomm.com/api/download/software/tools/Adreno_Kernel_Library_GGML/Windows/${ADRENO_BIN_KERNELS_VERSION}/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}.zip") + + set(ADRENO_BIN_KERNELS_ROOT "${CMAKE_BINARY_DIR}/_deps/adreno-opencl-kernels-${ADRENO_BIN_KERNELS_VERSION}") + set(ADRENO_BIN_KERNELS_ZIP "${ADRENO_BIN_KERNELS_ROOT}.zip") + set(ADRENO_BIN_KERNELS_DLL "${ADRENO_BIN_KERNELS_ROOT}/adreno-opencl-kernels.dll") + set(ADRENO_BIN_KERNELS_LICENSE "${ADRENO_BIN_KERNELS_ROOT}/license.txt") + + if (NOT EXISTS "${ADRENO_BIN_KERNELS_DLL}" OR NOT EXISTS "${ADRENO_BIN_KERNELS_LICENSE}") + message(STATUS "OpenCL: fetching Adreno binary kernel library ${ADRENO_BIN_KERNELS_VERSION} from Qualcomm; its use is subject to the license in license.txt") + file(DOWNLOAD "${ADRENO_BIN_KERNELS_URL}" "${ADRENO_BIN_KERNELS_ZIP}" + TLS_VERIFY ON + TIMEOUT 120 + INACTIVITY_TIMEOUT 30 + STATUS ADRENO_BIN_KERNELS_DOWNLOAD_STATUS) + list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 0 ADRENO_BIN_KERNELS_DOWNLOAD_RESULT) + if (ADRENO_BIN_KERNELS_DOWNLOAD_RESULT EQUAL 0) + file(SHA256 "${ADRENO_BIN_KERNELS_ZIP}" ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256) + if (NOT ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256 STREQUAL ADRENO_BIN_KERNELS_ZIP_SHA256) + file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}") + message(FATAL_ERROR "Adreno binary kernel library hash mismatch: expected ${ADRENO_BIN_KERNELS_ZIP_SHA256}, got ${ADRENO_BIN_KERNELS_ZIP_ACTUAL_SHA256}") + endif () + + file(MAKE_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}") + execute_process( + COMMAND ${CMAKE_COMMAND} -E tar xf "${ADRENO_BIN_KERNELS_ZIP}" + WORKING_DIRECTORY "${ADRENO_BIN_KERNELS_ROOT}" + RESULT_VARIABLE ADRENO_BIN_KERNELS_EXTRACT_RESULT) + if (NOT ADRENO_BIN_KERNELS_EXTRACT_RESULT EQUAL 0) + message(WARNING "Failed to extract the Adreno binary kernel library from ${ADRENO_BIN_KERNELS_ZIP}") + endif () + else () + list(GET ADRENO_BIN_KERNELS_DOWNLOAD_STATUS 1 ADRENO_BIN_KERNELS_DOWNLOAD_ERROR) + message(WARNING "Failed to download the Adreno binary kernel library (${ADRENO_BIN_KERNELS_DOWNLOAD_ERROR}); " + "the builtin kernels will be used. Set GGML_OPENCL_ADRENO_BIN_KERNELS_FETCH=OFF to skip the download.") + endif () + file(REMOVE "${ADRENO_BIN_KERNELS_ZIP}") + endif () + + if (EXISTS "${ADRENO_BIN_KERNELS_DLL}" AND EXISTS "${ADRENO_BIN_KERNELS_LICENSE}") + if (COMMAND license_add_file) + license_add_file("Adreno OpenCL kernels" "${ADRENO_BIN_KERNELS_LICENSE}") + endif () + + set(ADRENO_BIN_KERNELS_OUTPUT_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}") + if (CMAKE_CONFIGURATION_TYPES AND NOT ADRENO_BIN_KERNELS_OUTPUT_DIR MATCHES "\\$<") + string(APPEND ADRENO_BIN_KERNELS_OUTPUT_DIR "/$") + endif () + foreach (CONFIG IN LISTS CMAKE_CONFIGURATION_TYPES CMAKE_BUILD_TYPE) + string(TOUPPER "${CONFIG}" CONFIG_UPPER) + if (DEFINED CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER}) + set(ADRENO_BIN_KERNELS_OUTPUT_DIR "$<$:${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${CONFIG_UPPER}}>$<$>:${ADRENO_BIN_KERNELS_OUTPUT_DIR}>") + endif () + endforeach () + add_custom_target(ggml-opencl-adreno-bin-kernels ALL + COMMAND ${CMAKE_COMMAND} -E make_directory "${ADRENO_BIN_KERNELS_OUTPUT_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_DLL}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/adreno-opencl-kernels.dll" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${ADRENO_BIN_KERNELS_LICENSE}" "${ADRENO_BIN_KERNELS_OUTPUT_DIR}/LICENSE-adreno-opencl-kernels.txt") + add_dependencies(${TARGET_NAME} ggml-opencl-adreno-bin-kernels) + install(FILES "${ADRENO_BIN_KERNELS_DLL}" DESTINATION ${CMAKE_INSTALL_BINDIR}) + install(FILES "${ADRENO_BIN_KERNELS_LICENSE}" DESTINATION ${CMAKE_INSTALL_BINDIR} RENAME LICENSE-adreno-opencl-kernels.txt) + endif () endif () function(ggml_opencl_add_kernel KNAME) From c212d25ad34ff1fdf775793cda07e009560cf66b Mon Sep 17 00:00:00 2001 From: Evan Huus Date: Mon, 23 Nov 2026 15:50:29 -0500 Subject: [PATCH 080/401] server : preserve a prompt-cache entry until restores succeed (#32828) Assisted-by: Codex --- tools/server/server-slot-sched.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp index 9f977934828f..fccfb709a6db 100644 --- a/tools/server/server-slot-sched.cpp +++ b/tools/server/server-slot-sched.cpp @@ -211,7 +211,7 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok const int64_t t_start = ggml_time_us(); { - auto & data = it_best->data.main; + const auto & data = it_best->data.main; const size_t size = data.size(); const size_t n = llama_state_seq_set_data_ext(ctx_tgt, data.data(), size, id_slot, 0); @@ -220,13 +220,10 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok return false; } - - data.clear(); - data.shrink_to_fit(); } { - auto & data = it_best->data.drft; + const auto & data = it_best->data.drft; if (!data.empty()) { GGML_ASSERT(ctx_dft); @@ -238,9 +235,6 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok return false; } - - data.clear(); - data.shrink_to_fit(); } } From d35dc4d9e6827db8e08426a2340d8a71ea863cd9 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 07:06:02 +0800 Subject: [PATCH 081/401] GDN: use replay instead of rollback (#31669) * GDN: use replay instead of rollback [WIP] * memory : move rs_max with the sequence when find_slot swaps cells find_slot swapped pos/src/rs_pend/seq_id of the cell it moves out of the way, but not rs_max, so that sequence inherited the rollback depth of the cell's previous owner. A smaller value made seq_rm refuse the rollback (#31656), a larger one made snapshot mode restore the previous owner's snapshots. With rs_replay the pending columns are copied along with the state, so rs_max follows the sequence. Without it only the final state is copied and the snapshots stay behind, so the moved sequence gets rs_max 0. * delta_net: drop the graph replay fallback The graph fallback ran the replay as two gdn ops and copied the committed state from the replay gdn when keep, from the main gdn otherwise. Backends whose graph_optimize reorders nodes (Metal, Vulkan) then give keep and non keep ubatches a different node order for the same node count, and the scheduler reallocates on every switch (abort under GGML_SCHED_DEBUG_REALLOC). The replay now always runs in the gdn op. A device without the replay in its gdn op leaves the op to the CPU through the scheduler, as for any unsupported op. This removes LLAMA_RS_REPLAY=2, the replay probe, rs_replay_fused and the rep_mask input. * metal: replay the pending gated delta net tokens in the kernel The gated delta net kernel replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a function constant of the pipeline, keep is a kernel argument as on CUDA. The pending buffers fall back to src0 when the op has no replay. * vulkan: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a specialization constant of the pipeline, keep is a push constant as on CUDA. The pending buffers bind q when the op has no replay. The result checker clones the op with its replay sources. * webgpu: replay the pending gated delta net tokens in the shader The gated delta net shader replays the pending tokens of each seq before the new ones, with the same state update as the main loop and no attention output. With keep, it writes the state after the replay and skips the final state. The replay is a define of the pipeline, keep is a param as on CUDA. The replay count goes through workgroupUniformLoad, so that the loop around the workgroup barriers stays uniform. * delta_net: share the replay conv window views across layers Each replay layer took its own view of the rs_rep_cols input. The scheduler copies every view of a host input as a separate split input, so a verify graph uploaded one copy per layer. The views of the delta net and the PLE conv windows are now built once per graph, like the s_copy views. * vulkan: clamp the gated delta net replay count to n_pend The replay count comes from a buffer, so the shader bounds it to the pending rows before looping over them. The pipeline array comment now names the replay index next to the other ones. Address review from 0cc4m. * hex-gdn: add support for replay Enable replay in HVX path Enable replay in HMX path * gdn: fix rebase conflicts (missing cparams, etc) * llama : drop the fused GDN probes brought back by the rebase il parameter of build_delta_net. The rebase kept them (unused, auto_fgdn was always false), so restore master's version of that code. * delta_net : replay for the KDA models and Clover-MoE Clover-MoE has the Qwen 3.5 layout and only needs the arch gate. Kimi K3, Kimi K3.1, GLM5-Next and BailingMoE3 keep the q, k and v conv windows one after the other in a row. With replay the row holds three channels-first histories [d_inner, window + pending]: build_conv_state_replay takes the gathered rows of the layer and the block index. The pending gate rows hold S_v gates per head (KDA). GLM5-Next gets the -sm tensor split rules for the replay rows. Tested with test-llama-archs models: logits match snapshots bit for bit with random rollbacks (CUDA, Vulkan, CPU), no graph re-plans, and test-llama-context passes in both modes. * cuda : same KDA update in the gated delta net main and replay loops The KDA main loop called expf(g) twice inline, the replay loop reads g from registers. On sm_89 nvcc fused the two loops differently, so a replayed state was a few ulp off the state of the first pass. Compute g into registers in the main loop too: replay matches snapshots bit for bit on sm_89, and the sm_120 output does not change. * opencl: support replay in GDN * llama : replay inputs for the hybrid iswa rel memory input build_inp_mem_hybrid_iswa_rel came in with the rebase: pass hparams and cparams to build_rs_inp_impl and fill the replay inputs in set_input, like the other hybrid inputs. * webgpu: keep the gated delta net replay within the storage buffer limit * delta_net : add ggml_gated_delta_net_ext, replay is the only rollback ggml_gated_delta_net_ext takes the optional replay inputs and always outputs one state. ggml_gated_delta_net(..., K) is back to its master signature and is deprecated; both build the same op, so the backends are unchanged. The delta-net models (qwen35, qwen35moe, qwen4exp, clover-moe and the KDA models) now always replay the kept tokens when n_rs_seq > 0. The LLAMA_RS_REPLAY env flag and the snapshot branch of build_recurrent_attn are removed. test-backend-ops drops the K > 1 snapshot cases and the K parameter of the gated delta net tests. The cache fusion test copies the single state. * ggml-cpu : spacemit: leave the gdn replay to the generic kernel The RVV gated delta net kernel does not read the replay inputs. Return false when op param 1 (n_pend) is set, so that the generic kernel runs the op. * vulkan : fill views at any offset ggml_vk_fill bound dst without allowing a misaligned offset, so a fill of a view whose offset is not a multiple of minStorageBufferOffsetAlignment aborted. The recurrent state zeroing in build_rs hits this with the wider replay conv rows on devices with a 64-byte alignment. Bind dst from the aligned offset below it and pass the element offset in KY. test_fill gets an offset to fill a view in place. --------- Co-authored-by: Pascal Co-authored-by: Max Krasnyansky Co-authored-by: Li He --- ggml/include/ggml.h | 36 ++- ggml/src/ggml-backend-meta.cpp | 11 + ggml/src/ggml-cpu/ggml-cpu.c | 7 +- ggml/src/ggml-cpu/ops.cpp | 56 +++- ggml/src/ggml-cpu/spacemit/ime.cpp | 3 +- ggml/src/ggml-cuda/gated-delta-net-mma.cu | 4 + ggml/src/ggml-cuda/gated-delta-net-mma.cuh | 2 + ggml/src/ggml-cuda/gated_delta_net.cu | 204 ++++++++++++-- ggml/src/ggml-cuda/gated_delta_net.cuh | 5 + ggml/src/ggml-cuda/ggml-cuda.cu | 41 +++ ggml/src/ggml-et/ggml-et.cpp | 3 +- ggml/src/ggml-hexagon/htp-kparams.cpp | 21 ++ .../ggml-hexagon/htp/gated-delta-net-ops.c | 98 +++++-- ggml/src/ggml-metal/ggml-metal-device.cpp | 11 +- ggml/src/ggml-metal/ggml-metal-impl.h | 11 + ggml/src/ggml-metal/ggml-metal-ops.cpp | 21 ++ .../ggml-metal/kernels/gated_delta_net.metal | 64 ++++- ggml/src/ggml-opencl/ggml-opencl.cpp | 76 +++++- .../ggml-opencl/kernels/gated_delta_net.cl | 86 ++++++ ggml/src/ggml-openvino/ggml-openvino.cpp | 3 + ggml/src/ggml-sycl/ggml-sycl.cpp | 4 +- ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp | 7 +- .../ggml-vulkan/ggml-vulkan-push-constants.h | 4 + ggml/src/ggml-vulkan/ggml-vulkan-types.h | 4 +- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 54 +++- ggml/src/ggml-vulkan/vulkan-shaders/fill.comp | 4 +- .../vulkan-shaders/gated_delta_net.comp | 63 ++++- .../ggml-webgpu/ggml-webgpu-shader-lib.hpp | 11 +- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 42 ++- .../wgsl-shaders/gated_delta_net.wgsl | 109 +++++++- ggml/src/ggml.c | 61 ++++- src/llama-context.cpp | 9 + src/llama-cparams.h | 1 + src/llama-graph.cpp | 75 +++++- src/llama-graph.h | 13 + src/llama-memory-hybrid-idx.cpp | 3 +- src/llama-memory-hybrid-idx.h | 1 + src/llama-memory-hybrid-iswa.cpp | 1 + src/llama-memory-hybrid.cpp | 2 + src/llama-memory-hybrid.h | 1 + src/llama-memory-recurrent.cpp | 167 ++++++++++-- src/llama-memory-recurrent.h | 20 +- src/llama-model.cpp | 68 ++++- src/models/bailingmoe3.cpp | 33 ++- src/models/delta-net-base.cpp | 232 ++++++++++++---- src/models/glm5-next.cpp | 33 ++- src/models/kimi-k3.cpp | 33 ++- src/models/kimi-k31.cpp | 33 ++- src/models/models.h | 33 ++- src/models/qwen4exp.cpp | 4 + tests/llama-context/cases-rs.cpp | 2 +- tests/test-backend-ops.cpp | 253 +++++++++++++----- 52 files changed, 1827 insertions(+), 316 deletions(-) diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 161e8e0cef47..0007fa18f80e 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2435,11 +2435,17 @@ extern "C" { // beta : [1, H_v, n_tokens, n_seqs] // state : [S_v, S_v, H_v, n_seqs] -- initial recurrent state s0 // - // the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by K state - // snapshots, most-recent first (slot 0 = final state, slot s = state s tokens back). K == 1 - // keeps only the final state; when n_tokens < K only slots 0..n_tokens-1 are written. - // when n_tokens > K only slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten. - GGML_API struct ggml_tensor * ggml_gated_delta_net( + // the output packs the attention scores [S_v, H_v, n_tokens, n_seqs] followed by the final state [S_v, S_v, H_v, n_seqs] + // + // replay (optional, set all of pend_k, pend_v, pend_gb and n_rep, or none): first runs the pending tokens of the + // previous ubatch, so that a rollback only drops pending tokens instead of restoring a snapshot + // pend_k : [S_k, H_k, n_pend, n_seqs] + // pend_v : [S_v, H_v, n_pend, n_seqs] + // pend_gb : [g0, H_v, 2*n_pend, n_seqs], the gates of the n_pend tokens, then their betas (in element 0) + // n_rep : I32 [n_seqs], number of pending tokens to replay (<= n_pend) + // the state output is the state after the replay if keep is true, else the final state. + // op param 1 is n_pend (0 without replay): backends that do not implement the replay reject the op when it is set + GGML_API struct ggml_tensor * ggml_gated_delta_net_ext( struct ggml_context * ctx, struct ggml_tensor * q, struct ggml_tensor * k, @@ -2447,7 +2453,25 @@ extern "C" { struct ggml_tensor * g, struct ggml_tensor * beta, struct ggml_tensor * state, - int64_t K); + struct ggml_tensor * pend_k, + struct ggml_tensor * pend_v, + struct ggml_tensor * pend_gb, + struct ggml_tensor * n_rep, + bool keep); + + // the output packs the attention scores followed by K state snapshots, most-recent first (slot 0 = final state, + // slot s = state s tokens back). when n_tokens < K only slots 0..n_tokens-1 are written. when n_tokens > K only + // slot 0 is guaranteed; backends may leave slots 1..K-1 unwritten. + GGML_DEPRECATED(GGML_API struct ggml_tensor * ggml_gated_delta_net( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * g, + struct ggml_tensor * beta, + struct ggml_tensor * state, + int64_t K), + "use ggml_gated_delta_net_ext instead"); // DSA lightning indexer // diff --git a/ggml/src/ggml-backend-meta.cpp b/ggml/src/ggml-backend-meta.cpp index 9aed3b7808b8..42a4b4479d04 100644 --- a/ggml/src/ggml-backend-meta.cpp +++ b/ggml/src/ggml-backend-meta.cpp @@ -875,11 +875,22 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state( }; auto handle_gated_delta_net = [&](const std::vector & src_ss) -> ggml_backend_meta_split_state { + // replay (src 6..9): the pending k, v and gates/betas are split by heads like k, v and g, n_rep is per seq + const bool replay = tensor->src[6] != nullptr; if (src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[3].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[4].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED && src_ss[5].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED) { + for (int i = 6; replay && i < 10; i++) { + GGML_ASSERT(src_ss[i].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + } return src_ss[0]; } + if (replay) { + GGML_ASSERT(src_ss[6].axis == GGML_BACKEND_SPLIT_AXIS_1); + GGML_ASSERT(src_ss[7].axis == GGML_BACKEND_SPLIT_AXIS_1); + GGML_ASSERT(src_ss[8].axis == GGML_BACKEND_SPLIT_AXIS_1); + GGML_ASSERT(src_ss[9].axis == GGML_BACKEND_SPLIT_AXIS_MIRRORED); + } GGML_ASSERT(src_ss[0].axis == GGML_BACKEND_SPLIT_AXIS_1); GGML_ASSERT(src_ss[1].axis == GGML_BACKEND_SPLIT_AXIS_1); GGML_ASSERT(src_ss[2].axis == GGML_BACKEND_SPLIT_AXIS_1); diff --git a/ggml/src/ggml-cpu/ggml-cpu.c b/ggml/src/ggml-cpu/ggml-cpu.c index ba075ff8d316..dc0c95bf40c4 100644 --- a/ggml/src/ggml-cpu/ggml-cpu.c +++ b/ggml/src/ggml-cpu/ggml-cpu.c @@ -3068,9 +3068,10 @@ struct ggml_cplan ggml_graph_plan( } break; case GGML_OP_GATED_DELTA_NET: { - const int64_t S_v = node->src[2]->ne[0]; - const int64_t K = ggml_get_op_params_i32(node, 0); - const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0); + const int64_t S_v = node->src[2]->ne[0]; + const int64_t K = ggml_get_op_params_i32(node, 0); + const bool keep = node->src[6] && ggml_get_op_params_i32(node, 2) != 0; + const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0); cur = per_thread * sizeof(float) * n_tasks; } break; case GGML_OP_COUNT: diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp index 26b4a01c96eb..72dd3e6910a2 100644 --- a/ggml/src/ggml-cpu/ops.cpp +++ b/ggml/src/ggml-cpu/ops.cpp @@ -11313,11 +11313,19 @@ static void ggml_compute_forward_gated_delta_net_one_chunk( // per-seq stride in floats (seq s starts at state + s * seq_stride) const int64_t state_seq_stride = src_state->nb[3] / sizeof(float); - const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0); + // replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) + const ggml_tensor * src_pk = dst->src[6]; + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + const ggml_tensor * src_n_rep = dst->src[9]; + const int64_t n_pend = src_pk ? ggml_get_op_params_i32(dst, 1) : 0; + const bool keep = src_pk && ggml_get_op_params_i32(dst, 2) != 0; + + const int64_t per_thread = S_v + (K > 1 || keep ? S_v * S_v : 0); const int ith = params->ith; float * delta = (float *)params->wdata + ith * per_thread + CACHE_LINE_SIZE_F32; - float * state_work = K > 1 ? (delta + S_v) : nullptr; + float * state_work = K > 1 || keep ? (delta + S_v) : nullptr; // output layout: [attn_scores | new_states] // attn_scores: S_v * H * n_tokens * n_seqs floats @@ -11351,7 +11359,7 @@ static void ggml_compute_forward_gated_delta_net_one_chunk( // For K=1, write directly to the single output slot to avoid an extra memcpy at the end. // For K>1, work in scratch and copy out per-token when the slot is in range. - float * s_out = (K > 1) + float * s_out = (K > 1 || keep) ? state_work : state_out_base + (iv3 * H + iv1) * S_v * S_v; @@ -11360,6 +11368,48 @@ static void ggml_compute_forward_gated_delta_net_one_chunk( const float * s_in = state_in_base + iv3 * state_seq_stride + iv1 * S_v * S_v; memcpy(s_out, s_in, S_v * S_v * sizeof(float)); + if (src_pk) { + const int64_t n_r = ((const int32_t *) src_n_rep->data)[iv3]; + GGML_ASSERT(n_r >= 0 && n_r <= n_pend); + + const char * pk = (const char *) src_pk->data + iv3*src_pk->nb[3] + ik1*src_pk->nb[1]; + const char * pv = (const char *) src_pv->data + iv3*src_pv->nb[3] + iv1*src_pv->nb[1]; + const char * pgb = (const char *) src_pgb->data + iv3*src_pgb->nb[3] + iv1*src_pgb->nb[1]; + + for (int64_t t = 0; t < n_r; t++) { + const float * k_d = (const float *) (pk + t*src_pk->nb[2]); + const float * v_d = (const float *) (pv + t*src_pv->nb[2]); + const float * g_d = (const float *) (pgb + t*src_pgb->nb[2]); + const float beta_val = *(const float *) (pgb + (n_pend + t)*src_pgb->nb[2]); + + if (kda) { + for (int64_t i = 0; i < S_v; ++i) { + delta[i] = expf(g_d[i]); + } + for (int64_t j = 0; j < S_v; ++j) { + ggml_vec_mul_f32(S_v, &s_out[j * S_v], &s_out[j * S_v], delta); + } + } else { + ggml_vec_scale_f32(S_v * S_v, s_out, expf(g_d[0])); + } + + for (int64_t j = 0; j < S_v; ++j) { + float sum = 0.0f; + ggml_vec_dot_f32(S_v, &sum, 0, &s_out[j * S_v], 0, k_d, 0, 1); + delta[j] = (v_d[j] - sum) * beta_val; + } + + for (int64_t j = 0; j < S_v; ++j) { + ggml_vec_mad_f32(S_v, &s_out[j * S_v], k_d, delta[j]); + } + } + + // the committed state, the new tokens go on in the scratch + if (keep) { + memcpy(state_out_base + (iv3 * H + iv1) * S_v * S_v, s_out, S_v * S_v * sizeof(float)); + } + } + // attn output pointer for first token of this (head, seq) float * attn_data = attn_out_base + (iv3 * n_tokens * H + iv1) * S_v; diff --git a/ggml/src/ggml-cpu/spacemit/ime.cpp b/ggml/src/ggml-cpu/spacemit/ime.cpp index 0794c115de47..a23e70bc415b 100644 --- a/ggml/src/ggml-cpu/spacemit/ime.cpp +++ b/ggml/src/ggml-cpu/spacemit/ime.cpp @@ -1156,7 +1156,8 @@ class tensor_traits_common : public tensor_traits_base { } return true; case GGML_OP_GATED_DELTA_NET: - if (params->use_ref) { + // the generic kernel does the replay of pending tokens (op param 1) + if (params->use_ref || ggml_get_op_params_i32(op, 1) != 0) { return false; } switch (op->src[0]->type) { diff --git a/ggml/src/ggml-cuda/gated-delta-net-mma.cu b/ggml/src/ggml-cuda/gated-delta-net-mma.cu index 427a334747e6..8fdb1edd4d28 100644 --- a/ggml/src/ggml-cuda/gated-delta-net-mma.cu +++ b/ggml/src/ggml-cuda/gated-delta-net-mma.cu @@ -485,6 +485,10 @@ static gdn_path select_gdn_mma_path(int device, const ggml_cuda_gdn_mma_args & a } // namespace using namespace ggml_cuda_gated_delta_net_mma; +bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & a) { + return a.state_out && select_gdn_mma_path(device, a) != gdn_path::ar; +} + bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & a, cudaStream_t stream) { if (!a.state_out) { return false; diff --git a/ggml/src/ggml-cuda/gated-delta-net-mma.cuh b/ggml/src/ggml-cuda/gated-delta-net-mma.cuh index 8eb7c4f33647..8659d9ffb191 100644 --- a/ggml/src/ggml-cuda/gated-delta-net-mma.cuh +++ b/ggml/src/ggml-cuda/gated-delta-net-mma.cuh @@ -32,4 +32,6 @@ struct ggml_cuda_gdn_mma_args { bool eligible; }; +// true when ggml_cuda_gdn_mma_launch would run the chunked kernel for these args +bool ggml_cuda_gdn_mma_supported(int device, const ggml_cuda_gdn_mma_args & args); bool ggml_cuda_gdn_mma_launch(int device, const ggml_cuda_gdn_mma_args & args, cudaStream_t stream); diff --git a/ggml/src/ggml-cuda/gated_delta_net.cu b/ggml/src/ggml-cuda/gated_delta_net.cu index ae2374cbcdd7..526030007ea2 100644 --- a/ggml/src/ggml-cuda/gated_delta_net.cu +++ b/ggml/src/ggml-cuda/gated_delta_net.cu @@ -6,7 +6,25 @@ constexpr int gdn_cols_per_warp = 4; -template +// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) +struct gdn_replay_args { + const float * pk; // [S_v, H_k, n_pend, n_seqs] + const float * pv; // [S_v, H, n_pend, n_seqs] + const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas + const int32_t * n_rep; // [n_seqs] + int64_t sk1, sk2, sk3; // head, token and seq strides in floats + int64_t sv1, sv2, sv3; + int64_t sg1, sg2, sg3; + int n_pend; + bool keep; // write the state after the replay, not the final one + + // optional: store the k, v, g, beta inputs of the new tokens (fused cpys) + float * st[4]; + int64_t st2[4]; // token stride in floats + int64_t st3[4]; // seq stride in floats +}; + +template __global__ void __launch_bounds__((ggml_cuda_get_physical_warp_size() < S_v ? ggml_cuda_get_physical_warp_size() : S_v) * 4, 2) gated_delta_net_cuda(const float * q, const float * k, @@ -32,7 +50,8 @@ gated_delta_net_cuda(const float * q, const uint3 rq3_magic, float scale, int64_t state_slot_stride, - int K) { + int K, + const gdn_replay_args rep) { const uint32_t h_idx = blockIdx.x; const uint32_t sequence = blockIdx.y; @@ -72,6 +91,53 @@ gated_delta_net_cuda(const float * q, s_shard[r] = curr_state[i]; } + if constexpr (replay) { + const int n_r = rep.n_rep[sequence]; + const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1; + const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1; + const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1; + + for (int t = 0; t < n_r; t++) { + const float * k_t = pk + t * rep.sk2; + const float v_col = pv[t * rep.sv2 + col]; + const float * g_t = pgb + t * rep.sg2; + const float beta_val = pgb[(rep.n_pend + t) * rep.sg2]; + + float k_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + k_reg[r] = k_t[r * lanes_per_col + lane_in_col]; + } + + float g_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + g_reg[r] = expf(KDA ? g_t[r * lanes_per_col + lane_in_col] : g_t[0]); + } + + // same update as below, without the attention output + float kv_shard = 0.0f; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + kv_shard += (KDA ? g_reg[r] : 1.0f) * s_shard[r] * k_reg[r]; + } + const float kv_col = warp_reduce_sum(kv_shard); + const float delta_col = (v_col - (KDA ? 1.0f : g_reg[0]) * kv_col) * beta_val; + +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col; + } + } + + if (rep.keep) { +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + state[col * S_v + r * lanes_per_col + lane_in_col] = s_shard[r]; + } + } + } + for (int t = 0; t < n_tokens; t++) { const float * q_t = q + iq3 * sq3 + t * sq2 + iq1 * sq1; const float * k_t = k + iq3 * sq3 + t * sq2 + iq1 * sq1; @@ -93,6 +159,27 @@ gated_delta_net_cuda(const float * q, q_reg[r] = q_t[i]; } + if constexpr (replay && !KDA) { + if (rep.st[0] != nullptr) { + // keep the inputs of this token pending: one CTA per k head writes k, each column its v + const bool first = blockIdx.z == 0 && threadIdx.y == 0 && col_in_warp == 0; + if (first && h_idx < neqk1_magic.z) { + float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + dk[r * lanes_per_col + lane_in_col] = k_reg[r]; + } + } + if (lane_in_col == 0) { + rep.st[1][sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col] = v_t[col]; + } + if (first && lane_in_col == 0) { + rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t; + rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val; + } + } + } + if constexpr (!KDA) { const float g_val = expf(*g_t); @@ -122,12 +209,18 @@ gated_delta_net_cuda(const float * q, attn_data[col] = attn_col * scale; } } else { + // same arithmetic as the replay loop, so that a replayed state matches bit for bit + float g_reg[rows_per_lane]; +#pragma unroll + for (int r = 0; r < rows_per_lane; r++) { + g_reg[r] = expf(g_t[r * lanes_per_col + lane_in_col]); + } + // kv[col] = sum_i g[i] * S[i][col] * k[i] float kv_shard = 0.0f; #pragma unroll for (int r = 0; r < rows_per_lane; r++) { - const int i = r * lanes_per_col + lane_in_col; - kv_shard += expf(g_t[i]) * s_shard[r] * k_reg[r]; + kv_shard += g_reg[r] * s_shard[r] * k_reg[r]; } float kv_col = warp_reduce_sum(kv_shard); @@ -140,8 +233,7 @@ gated_delta_net_cuda(const float * q, float attn_partial = 0.0f; #pragma unroll for (int r = 0; r < rows_per_lane; r++) { - const int i = r * lanes_per_col + lane_in_col; - s_shard[r] = expf(g_t[i]) * s_shard[r] + k_reg[r] * delta_col; + s_shard[r] = g_reg[r] * s_shard[r] + k_reg[r] * delta_col; attn_partial += s_shard[r] * q_reg[r]; } @@ -170,6 +262,9 @@ gated_delta_net_cuda(const float * q, } if constexpr (!keep_rs_t) { + if (replay && rep.keep) { + return; + } #pragma unroll for (int r = 0; r < rows_per_lane; r++) { const int i = r * lanes_per_col + lane_in_col; @@ -178,7 +273,7 @@ gated_delta_net_cuda(const float * q, } } -template +template static void launch_gated_delta_net( const float * q_d, const float * k_d, const float * v_d, const float * g_d, const float * b_d, const float * s_d, @@ -188,7 +283,7 @@ static void launch_gated_delta_net( int64_t sv1, int64_t sv2, int64_t sv3, int64_t sb1, int64_t sb2, int64_t sb3, int64_t neqk1, int64_t rq3, - float scale, int64_t state_slot_stride, int K, cudaStream_t stream) { + float scale, int64_t state_slot_stride, int K, const gdn_replay_args & rep, cudaStream_t stream) { //TODO: Add chunked kernel for even faster pre-fill const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size; // four columns per warp (see the kernel); shrink the CTA when the wider CTA would leave @@ -209,29 +304,29 @@ static void launch_gated_delta_net( const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(grid_dims, block_dims, 0, stream); switch (S_v) { case 16: - ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<16, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; case 32: - ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<32, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; case 64: { - ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<64, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; } case 128: { - ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t>, launch_params, + ggml_cuda_kernel_launch(gated_delta_net_cuda<128, KDA, keep_rs_t, replay>, launch_params, q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K); + sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep); break; } default: @@ -353,34 +448,85 @@ static void ggml_cuda_op_gated_delta_net_impl( state_slot_stride = cache->slot_stride; } - { + const ggml_tensor * src_pend = dst->src[6]; + + gdn_replay_args rep = {}; + if (src_pend) { + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + + GGML_ASSERT(K == 1); + rep.pk = (const float *) src_pend->data; + rep.pv = (const float *) src_pv->data; + rep.pgb = (const float *) src_pgb->data; + rep.n_rep = (const int32_t *) dst->src[9]->data; + rep.sk1 = src_pend->nb[1] / sizeof(float); + rep.sk2 = src_pend->nb[2] / sizeof(float); + rep.sk3 = src_pend->nb[3] / sizeof(float); + rep.sv1 = src_pv->nb[1] / sizeof(float); + rep.sv2 = src_pv->nb[2] / sizeof(float); + rep.sv3 = src_pv->nb[3] / sizeof(float); + rep.sg1 = src_pgb->nb[1] / sizeof(float); + rep.sg2 = src_pgb->nb[2] / sizeof(float); + rep.sg3 = src_pgb->nb[3] / sizeof(float); + rep.n_pend = ggml_get_op_params_i32(dst, 1); + rep.keep = ggml_get_op_params_i32(dst, 2) != 0; + if (cache != nullptr) { + for (int i = 0; i < 4; ++i) { + rep.st[i] = cache->in_dst[i]; + rep.st2[i] = cache->in_nb2[i]; + rep.st3[i] = cache->in_nb3[i]; + } + } + } + +#define GDN_LAUNCH_N(KDA, KEEP, REPLAY, N_TOKENS, REP) \ + launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, \ + S_v, H, N_TOKENS, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, \ + sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, REP, stream) +#define GDN_LAUNCH(KDA, KEEP, REPLAY) GDN_LAUNCH_N(KDA, KEEP, REPLAY, n_tokens, rep) + + if (!src_pend) { ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst); args.state_out = state_d; if (ggml_cuda_gdn_mma_launch(ctx.device, args, stream)) { return; } + } else if (!rep.keep && rep.st[0] == nullptr) { + // the chunked kernels (not KDA) do not replay: replay the pending tokens into the state output, then + // run the new tokens from there in place (each thread reads and writes the same state elements) + ggml_cuda_gdn_mma_args args = ggml_cuda_gdn_mma_args_from_tensor(dst); + args.state = state_d; + args.state_out = state_d; + if (ggml_cuda_gdn_mma_supported(ctx.device, args)) { + gdn_replay_args rep_only = rep; + rep_only.keep = true; + GDN_LAUNCH_N(false, false, true, 0, rep_only); + ggml_cuda_gdn_mma_launch(ctx.device, args, stream); + return; + } } + if (kda) { if (keep_rs) { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(true, true, false); + } else if (src_pend) { + GDN_LAUNCH(true, false, true); } else { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(true, false, false); } } else { if (keep_rs) { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(false, true, false); + } else if (src_pend) { + GDN_LAUNCH(false, false, true); } else { - launch_gated_delta_net(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, - S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3, - sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream); + GDN_LAUNCH(false, false, false); } } + +#undef GDN_LAUNCH +#undef GDN_LAUNCH_N } void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { diff --git a/ggml/src/ggml-cuda/gated_delta_net.cuh b/ggml/src/ggml-cuda/gated_delta_net.cuh index f9bf43706789..97c3e0963eff 100644 --- a/ggml/src/ggml-cuda/gated_delta_net.cuh +++ b/ggml/src/ggml-cuda/gated_delta_net.cuh @@ -5,6 +5,11 @@ struct ggml_cuda_gated_delta_net_fused_cache { float * data; // rollback slot 0 int64_t slot_stride; // between rollback slots (0 when K==1) + + // rs_replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused + float * in_dst[4] = {}; + int64_t in_nb2[4] = {}; // token stride in elements + int64_t in_nb3[4] = {}; // seq stride in elements }; void ggml_cuda_op_gated_delta_net(ggml_backend_cuda_context & ctx, ggml_tensor * dst); diff --git a/ggml/src/ggml-cuda/ggml-cuda.cu b/ggml/src/ggml-cuda/ggml-cuda.cu index 3e1f167e9936..a07e9a6226a2 100644 --- a/ggml/src/ggml-cuda/ggml-cuda.cu +++ b/ggml/src/ggml-cuda/ggml-cuda.cu @@ -3647,6 +3647,47 @@ static int ggml_cuda_try_gdn_cache_fusion( fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest) fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0; + + // rs_replay: the next 4 real nodes may store the k, v, g, beta inputs into the pending rows + if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) { + int j = node_idx + skip + 1; + int skip_in = skip; + float * in_dst[4]; + int64_t in_nb2[4]; + int64_t in_nb3[4]; + int i = 0; + for (; i < 4 && j < cgraph->n_nodes; ++j) { + const ggml_tensor * n = cgraph->nodes[j]; + if (ggml_cuda_is_view_or_noop(n)) { + continue; + } + const ggml_tensor * in = gdn->src[1 + i]; + const ggml_tensor * d = n->src[1]; + // the cpy reads the whole input, directly or through a view of the same data + const ggml_tensor * s0 = n->src[0]; + const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) && + ggml_are_same_stride(s0, in)); + if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in || + d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) || + d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) || d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float)) { + break; + } + in_dst[i] = (float *) d->data; + in_nb2[i] = d->nb[2] / sizeof(float); + in_nb3[i] = d->nb[3] / sizeof(float); + skip_in = j - node_idx; + ++i; + } + if (i == 4) { + for (int c = 0; c < 4; ++c) { + fused_state_cpy.in_dst[c] = in_dst[c]; + fused_state_cpy.in_nb2[c] = in_nb2[c]; + fused_state_cpy.in_nb3[c] = in_nb3[c]; + } + skip = skip_in; + } + } + return skip; } diff --git a/ggml/src/ggml-et/ggml-et.cpp b/ggml/src/ggml-et/ggml-et.cpp index e575ee78b45c..42aa72279625 100644 --- a/ggml/src/ggml-et/ggml-et.cpp +++ b/ggml/src/ggml-et/ggml-et.cpp @@ -1537,7 +1537,8 @@ static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggm op->src[4]->ne[0] == 1 && // beta is scalar per position et_ggml_is_row_contiguous(op->src[0]) && et_ggml_is_row_contiguous(op->src[1]) && et_ggml_is_row_contiguous(op->src[2]) && ggml_is_contiguous(op->src[3]) && - ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5])) { + ggml_is_contiguous(op->src[4]) && ggml_is_contiguous(op->src[5]) && + ggml_get_op_params_i32(op, 1) == 0) { // no replay of pending tokens supported = true; } else { supported = false; diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 4e3c5cb8d3df..122d6aee878b 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -514,7 +514,12 @@ static bool htp_kparams_solve_gated_delta_net( const struct ggml_tensor * g = op->src[3]; const struct ggml_tensor * beta = op->src[4]; const struct ggml_tensor * state = op->src[5]; + const struct ggml_tensor * pend_k = op->src[6]; + const struct ggml_tensor * pend_v = op->src[7]; + const struct ggml_tensor * pend_gb = op->src[8]; + const struct ggml_tensor * n_rep = op->src[9]; const struct ggml_tensor * dst = op; + const bool replay = pend_k != nullptr; if (q->type != GGML_TYPE_F32 || k->type != GGML_TYPE_F32 || v->type != GGML_TYPE_F32 || g->type != GGML_TYPE_F32 || beta->type != GGML_TYPE_F32 || state->type != GGML_TYPE_F32 || @@ -552,6 +557,22 @@ static bool htp_kparams_solve_gated_delta_net( dst->ne[2] != 1 || dst->ne[3] != 1) { return false; } + if ((pend_v != nullptr) != replay || (pend_gb != nullptr) != replay || (n_rep != nullptr) != replay) { + return false; + } + if (replay) { + const int64_t n_pend = ggml_get_op_params_i32(op, 1); + + if (K != 1 || n_pend < 0 || pend_k->type != GGML_TYPE_F32 || pend_v->type != GGML_TYPE_F32 || + pend_gb->type != GGML_TYPE_F32 || n_rep->type != GGML_TYPE_I32 || + pend_k->nb[0] != sizeof(float) || pend_v->nb[0] != sizeof(float) || pend_gb->nb[0] != sizeof(float) || + pend_k->ne[0] != k->ne[0] || pend_k->ne[1] != k->ne[1] || pend_k->ne[2] != n_pend || pend_k->ne[3] != n_seqs || + pend_v->ne[0] != S_v || pend_v->ne[1] != H || pend_v->ne[2] != n_pend || pend_v->ne[3] != n_seqs || + pend_gb->ne[0] != g->ne[0] || pend_gb->ne[1] != H || pend_gb->ne[2] != 2*n_pend || pend_gb->ne[3] != n_seqs || + !ggml_is_contiguous(n_rep) || ggml_nelements(n_rep) != n_seqs) { + return false; + } + } const uint32_t rq3 = (uint32_t) (n_seqs / q->ne[3]); const uint32_t rk3 = (uint32_t) (n_seqs / k->ne[3]); diff --git a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c index 0280f99a4af4..68b9c1d4767d 100644 --- a/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c +++ b/ggml/src/ggml-hexagon/htp/gated-delta-net-ops.c @@ -574,7 +574,7 @@ static inline HVX_Vector gdn_add_scaled_dot8_f32(float * restrict dst0, float * return Q6_V_vmux_QVV(q16, rA, Q6_V_vror_VR(rB, 128 - 16)); } -static inline void gdn_step_kda_f32( +static __attribute__((noinline)) void gdn_step_kda_f32( float * restrict s_work, float * restrict attn_out, const float * restrict q_t, @@ -662,7 +662,7 @@ static inline void gdn_step_kda_f32( } } -static inline void gdn_step_scalar_f32( +static __attribute__((noinline)) void gdn_step_scalar_f32( float * restrict s_work, float * restrict attn_out, const float * restrict q_t, @@ -748,6 +748,48 @@ static inline void gdn_step_scalar_f32( } } +static inline void gdn_replay_f32( + const struct htp_ops_context * octx, + float * restrict s_work, + uint32_t ik1, + uint32_t iv1, + uint32_t iv3, + bool kda, + float scale, + uint32_t S_v +) { + const struct htp_tensor * pend_k = octx->src[6]; + const struct htp_tensor * pend_v = octx->src[7]; + const struct htp_tensor * pend_gb = octx->src[8]; + const struct htp_tensor * n_rep = octx->src[9]; + + if (!pend_k) { + return; + } + + const uint32_t n_pend = (uint32_t) octx->op_params[1]; + const int32_t raw_n_rep = ((const int32_t *) (uintptr_t) n_rep->data)[iv3]; + const uint32_t n_steps = raw_n_rep <= 0 ? 0 : MIN((uint32_t) raw_n_rep, n_pend); + float unused_attn[128] __attribute__((aligned(128))); + + const uint8_t * pk = (const uint8_t *) (uintptr_t) pend_k->data + (uint64_t) iv3 * pend_k->nb[3] + (uint64_t) ik1 * pend_k->nb[1]; + const uint8_t * pv = (const uint8_t *) (uintptr_t) pend_v->data + (uint64_t) iv3 * pend_v->nb[3] + (uint64_t) iv1 * pend_v->nb[1]; + const uint8_t * pgb = (const uint8_t *) (uintptr_t) pend_gb->data + (uint64_t) iv3 * pend_gb->nb[3] + (uint64_t) iv1 * pend_gb->nb[1]; + + for (uint32_t t = 0; t < n_steps; ++t) { + const float * k_t = (const float *) (pk + (uint64_t) t * pend_k->nb[2]); + const float * v_t = (const float *) (pv + (uint64_t) t * pend_v->nb[2]); + const float * g_t = (const float *) (pgb + (uint64_t) t * pend_gb->nb[2]); + const float beta_val = *(const float *) (pgb + (uint64_t) (n_pend + t) * pend_gb->nb[2]); + + if (kda) { + gdn_step_kda_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v); + } else { + gdn_step_scalar_f32(s_work, unused_attn, k_t, k_t, v_t, g_t, beta_val, scale, S_v); + } + } +} + static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { struct htp_gdn_context * gctx = (struct htp_gdn_context *) data; struct htp_ops_context * octx = gctx->octx; @@ -792,6 +834,7 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int const uint32_t state_seq_stride = kparams->state_seq_stride; const uint64_t state_size_per_snap = (uint64_t) kparams->state_size_per_snap; const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_tokens * n_seqs * sizeof(float)); + const bool keep = octx->src[6] && octx->op_params[2] != 0; uint32_t ir_prefetch = gctx->row_start + ith; int spad_idx = 0; @@ -838,6 +881,10 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int float * attn_data = dst_base + ((uint64_t) iv3 * n_tokens * H + iv1) * S_v; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v); + if (keep) { + hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v); + } for (uint32_t t = 0; t < n_tokens; ++t) { const float * q_t = (const float *) ((const uint8_t *) (uintptr_t) q->data + (uint64_t) iq3 * q->nb[3] + (uint64_t) t * q->nb[2] + (uint64_t) iq1 * q->nb[1]); @@ -868,10 +915,9 @@ static void gated_delta_net_f32_pp_thread(const htp_thread_t * th, unsigned int } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - // Push real write-back dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr), S_v * sizeof(float), S_v * sizeof(float), - S_v * sizeof(float), S_v); + S_v * sizeof(float), keep ? 0 : S_v); // Prefetch next block (if any) if (ir_prefetch < row_end) { @@ -932,6 +978,7 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int const uint32_t state_seq_stride = kparams->state_seq_stride; const dma_addr_t state_out_dma_base = dst_cache ? dst_cache->data : (dst->data + S_v * H * n_seqs * sizeof(float)); + const bool keep = octx->src[6] && octx->op_params[2] != 0; uint32_t ir_prefetch = gctx->row_start + ith; int spad_idx = 0; @@ -989,6 +1036,10 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int (uint64_t) iv3 * beta->nb[3] + (uint64_t) iv1 * beta->nb[1]); htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); + gdn_replay_f32(octx, s_work_curr, ik1, iv1, iv3, kparams->kda, scale, S_v); + if (keep) { + hvx_copy_f32_uu((uint8_t *) (uintptr_t) s_out, (const uint8_t *) s_work_curr, S_v * S_v); + } if (kparams->kda) { gdn_step_kda_f32(s_work_curr, attn_data, q_t, k_t, v_t, g_t, beta_val, scale, S_v); } else { @@ -996,10 +1047,9 @@ static void gated_delta_net_f32_tg_thread(const htp_thread_t * th, unsigned int } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) ir); - // Push real write-back dma_queue_push(dma_q, dma_make_data(s_out, s_work_curr), S_v * sizeof(float), S_v * sizeof(float), - S_v * sizeof(float), S_v); + S_v * sizeof(float), keep ? 0 : S_v); // Prefetch next block (if any) if (ir_prefetch < row_end) { @@ -1654,13 +1704,15 @@ struct htp_gdn_batch_context { const struct htp_gdn_kernel_params * kparams; }; -static void gdn_hvx_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { +static void gdn_hvx_replay_init_state_worker(const htp_thread_t * th, unsigned int n, unsigned int i, void * data) { (void) n; struct htp_gdn_batch_context * bctx = (struct htp_gdn_batch_context *) data; struct htp_thread_trace * tr = th->trace; htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, 0); struct htp_gdn_head_ptrs * head = &bctx->heads[i]; + gdn_replay_f32(bctx->octx, head->s_state, head->ik1, head->iv1, head->iv3, + bctx->kparams->kda, bctx->scale, bctx->S_v); gdn_pack_s_col_tiles(head->s_col_tiles, head->s_f16, head->s_state, bctx->S_v); htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, 0); @@ -2038,6 +2090,7 @@ static int gated_delta_net_f32_hmx_chunked( const uint32_t chunk_size = kparams->chunk_size; const uint32_t n_chunks = kparams->n_chunks; const uint32_t n_sv_tiles = S_v / 32; + const bool keep = octx->src[6] && octx->op_params[2] != 0; struct htp_gdn_hmx_vtcm_layout L; htp_gdn_hmx_vtcm_layout_build(&L, S_v, chunk_size, kparams->n_heads_batch, kparams->n_hvx, kparams->pipeline != 0); @@ -2101,7 +2154,17 @@ static int gated_delta_net_f32_hmx_chunked( } if (n_chunks > 0) { - work_queue_run(wp, gdn_hvx_init_state_worker, &bctx, n_batch); + work_queue_run(wp, gdn_hvx_replay_init_state_worker, &bctx, n_batch); + + if (keep) { + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state), + S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + } + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_pop(dma_q); + } + } const uint32_t chunk0_tokens = hex_smin(chunk_size, n_tokens); for (uint32_t h = 0; h < n_batch; ++h) { @@ -2254,12 +2317,14 @@ static int gated_delta_net_f32_hmx_chunked( } } - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state), - S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); - } - for (uint32_t h = 0; h < n_batch; ++h) { - dma_queue_pop(dma_q); + if (!keep) { + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_push(dma_q, dma_make_data(heads[h].state_out_dma, heads[h].s_state), + S_v * sizeof(float), S_v * sizeof(float), S_v * sizeof(float), S_v); + } + for (uint32_t h = 0; h < n_batch; ++h) { + dma_queue_pop(dma_q); + } } } @@ -2270,7 +2335,7 @@ static int gated_delta_net_f32_hmx_chunked( int op_gated_delta_net(struct htp_ops_context * octx) { const struct htp_tensor * dst = octx->dst; - for (int i = 0; i < 6; i++) { + for (int i = 0; i < 10; i++) { if (htp_tensor_is_extended(octx->src[i])) { return HTP_STATUS_NO_SUPPORT; } @@ -2308,9 +2373,6 @@ int op_gated_delta_net(struct htp_ops_context * octx) { ); row_start = range.start; nrows = range.count; - } else if (octx->op_params[1] != 0) { - row_start = octx->op_params[1]; - nrows = octx->op_params[2]; } if (nrows == 0) { diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 7a732e29e73c..c4e6ded8b721 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -752,6 +752,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net( const int ne30 = op->src[3]->ne[0]; // G // state is src[5], 4D [S_v, S_v, H_v, n_seqs] (s0 only); K is op param 0. const int K = ggml_get_op_params_i32(op, 0); + // replay of pending tokens, see ggml_gated_delta_net_ext + const bool replay = op->src[6] != nullptr; const int nsg = op->src[2]->ne[0]/32; @@ -760,15 +762,16 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_gated_delta_net( GGML_ASSERT(ne20 % 32 == 0); snprintf(base, 256, "kernel_gated_delta_net_%s_%d", ggml_type_name(op->src[0]->type), nsg); - snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d", base, ne20, ne30, K); + snprintf(name, 256, "%s_ne20=%d_ne30=%d_K=%d_rep=%d", base, ne20, ne30, K, replay ? 1 : 0); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); if (!res.pipeline) { ggml_metal_cv_t cv = ggml_metal_cv_init(); - ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0); - ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1); - ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2); + ggml_metal_cv_set_int16(cv, ne20, FC_GATED_DELTA_NET + 0); + ggml_metal_cv_set_int16(cv, ne30, FC_GATED_DELTA_NET + 1); + ggml_metal_cv_set_int16(cv, K, FC_GATED_DELTA_NET + 2); + ggml_metal_cv_set_bool (cv, replay, FC_GATED_DELTA_NET + 3); res = ggml_metal_library_compile_pipeline(lib, base, name, cv); diff --git a/ggml/src/ggml-metal/ggml-metal-impl.h b/ggml/src/ggml-metal/ggml-metal-impl.h index 4e28b2cb99b9..c0042a8c1020 100644 --- a/ggml/src/ggml-metal/ggml-metal-impl.h +++ b/ggml/src/ggml-metal/ggml-metal-impl.h @@ -1037,6 +1037,17 @@ typedef struct { uint64_t nb2; uint64_t nb3; uint64_t nb_out; // 0 => snapshots are appended after the attn scores (unfused) + int32_t n_pend; // replay: pending tokens per seq in pend_k, pend_v and pend_gb + int32_t keep; // replay: write the state after the replay, not the final one + uint64_t nb61; // pend_k + uint64_t nb62; + uint64_t nb63; + uint64_t nb71; // pend_v + uint64_t nb72; + uint64_t nb73; + uint64_t nb81; // pend_gb + uint64_t nb82; + uint64_t nb83; } ggml_metal_kargs_gated_delta_net; typedef struct { diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index a7a1ef61e9cf..e1f8610c5b2d 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -2104,6 +2104,12 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) { } } + // replay of pending tokens, see ggml_gated_delta_net_ext + const ggml_tensor * pk = op->src[6]; + const ggml_tensor * pv = op->src[7]; + const ggml_tensor * pgb = op->src[8]; + const ggml_tensor * rep = op->src[9]; + int ida = 0; ggml_metal_kargs_gated_delta_net args = { @@ -2143,6 +2149,17 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) { /*.nb2 =*/ nb2, /*.nb3 =*/ nb3, /*.nb_out =*/ nb_out, + /*.n_pend =*/ pk ? ggml_get_op_params_i32(op, 1) : 0, + /*.keep =*/ pk ? ggml_get_op_params_i32(op, 2) : 0, + /*.nb61 =*/ pk ? pk->nb[1] : 0, + /*.nb62 =*/ pk ? pk->nb[2] : 0, + /*.nb63 =*/ pk ? pk->nb[3] : 0, + /*.nb71 =*/ pv ? pv->nb[1] : 0, + /*.nb72 =*/ pv ? pv->nb[2] : 0, + /*.nb73 =*/ pv ? pv->nb[3] : 0, + /*.nb81 =*/ pgb ? pgb->nb[1] : 0, + /*.nb82 =*/ pgb ? pgb->nb[2] : 0, + /*.nb83 =*/ pgb ? pgb->nb[3] : 0, }; ggml_metal_encoder_set_pipeline(enc, pipeline); @@ -2155,6 +2172,10 @@ int ggml_metal_op_gated_delta_net(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op->src[5]), ida++); // state ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), ida++); // dst (attn) ggml_metal_encoder_set_buffer (enc, bid_out, ida++); // state_out + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pk ? pk : op->src[0]), ida++); // pend_k + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pv ? pv : op->src[0]), ida++); // pend_v + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(pgb ? pgb : op->src[0]), ida++); // pend_gb + ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(rep ? rep : op->src[0]), ida++); // n_rep const int nsg = pipeline.nsg; diff --git a/ggml/src/ggml-metal/kernels/gated_delta_net.metal b/ggml/src/ggml-metal/kernels/gated_delta_net.metal index 5e4861ece360..8e8e04963f5a 100644 --- a/ggml/src/ggml-metal/kernels/gated_delta_net.metal +++ b/ggml/src/ggml-metal/kernels/gated_delta_net.metal @@ -3,6 +3,7 @@ constant short FC_gated_delta_net_ne20 [[function_constant(FC_GATED_DELTA_NET + 0)]]; constant short FC_gated_delta_net_ne30 [[function_constant(FC_GATED_DELTA_NET + 1)]]; constant short FC_gated_delta_net_K [[function_constant(FC_GATED_DELTA_NET + 2)]]; +constant bool FC_gated_delta_net_rep [[function_constant(FC_GATED_DELTA_NET + 3)]]; #if 1 template @@ -16,6 +17,10 @@ kernel void kernel_gated_delta_net_impl( device const char * s, device char * dst, device char * dst_fuse, + device const char * pk, + device const char * pv, + device const char * pgb, + device const char * n_rep, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { @@ -72,6 +77,62 @@ kernel void kernel_gated_delta_net_impl( const device float * state_out = fused ? (device float *)dst_fuse : (device float *)dst + attn_size; const uint slot_stride = fused ? (uint)args.nb_out : state_size_per_snap; + // replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) + if (FC_gated_delta_net_rep) { + const int n_r = ((device const int32_t *) n_rep)[i23]; + + device const char * pk_ptr = pk + i23*args.nb63 + i11*args.nb61; + device const char * pv_ptr = pv + i23*args.nb73 + i21*args.nb71; + device const char * pgb_ptr = pgb + i23*args.nb83 + i21*args.nb81; + + for (int t = 0; t < n_r; t++) { + device const float * k_t = (device const float *) (pk_ptr + t*args.nb62); + device const float * g_t = (device const float *) (pgb_ptr + t*args.nb82); + + const float v_t = ((device const float *) (pv_ptr + t*args.nb72))[i20]; + const float beta_t = *(device const float *) (pgb_ptr + (args.n_pend + t)*args.nb82); + + // same update as below, without the attention output + float s_k = 0.0f; + + if (G == 1) { + const float g_exp = exp(g_t[0]); + + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + ls[j] *= g_exp; + + s_k += ls[j]*k_t[is]; + } + } else { + // KDA + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + ls[j] *= exp(g_t[is]); + + s_k += ls[j]*k_t[is]; + } + } + + s_k = simd_sum(s_k); + + const float d = (v_t - s_k)*beta_t; + + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + ls[j] += k_t[is]*d; + } + } + + if (args.keep) { + device float * dst_state = (device float *)state_out + state_out_base; + FOR_UNROLL (short j = 0; j < NSG; j++) { + const short is = tx*NSG + j; + dst_state[is] = ls[j]; + } + } + } + for (short t = 0; t < args.ne22; t++) { float s_k = 0.0f; @@ -132,7 +193,8 @@ kernel void kernel_gated_delta_net_impl( } } - if (K == 1) { + // replay with keep: the state output is the state after the replay + if (K == 1 && !(FC_gated_delta_net_rep && args.keep)) { device float * dst_state = (device float *)state_out + state_out_base; FOR_UNROLL (short j = 0; j < NSG; j++) { const short is = tx*NSG + j; diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 2a3f709a2f30..54038a503ad5 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1181,9 +1181,9 @@ struct ggml_backend_opencl_context { cl_kernel kernel_conv_2d_f16_f32; cl_kernel kernel_conv2d_dw_f32_f32, kernel_conv2d_dwf16_f32; cl_kernel kernel_ssm_conv_f32_f32, kernel_ssm_conv_f32_f32_4; - // [size_idx][kda][tgpp] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1. + // [size_idx][kda][tgpp][replay] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1. // tgpp 0 = TG variant (COLS_PER_LANE_GROUP=1), tgpp 1 = prefill variant (COLS_PER_LANE_GROUP=4). - cl_kernel kernel_gated_delta_net_f32[4][2][2] = {}; + cl_kernel kernel_gated_delta_net_f32[4][2][2][2] = {}; cl_kernel kernel_ssm_scan_f32 = nullptr; cl_kernel kernel_ssm_scan_f32_mamba2_d128 = nullptr; cl_kernel kernel_ssm_scan_f32_mamba2_d256 = nullptr; @@ -5170,7 +5170,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { GGML_LOG_CONT("."); } - // gated_delta_net: one kernel per (S_V, KDA, tgpp) triple. + // gated_delta_net: one kernel per (S_V, KDA, tgpp, replay). { #ifdef GGML_OPENCL_EMBED_KERNELS const std::string kernel_src { @@ -5238,11 +5238,14 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { // Please remember to implement code to handle it. opts += " -DSUBGROUPS_PER_WG=" + std::to_string(spw); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + for (int replay = 0; replay < 2; replay++) { + const std::string opts_rep = opts + " -DREPLAY=" + std::to_string(replay); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts_rep); - CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp] = - clCreateKernel(prog, "kernel_gated_delta_net", &err), err)); - CL_CHECK(clReleaseProgram(prog)); + CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay] = + clCreateKernel(prog, "kernel_gated_delta_net", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } } } } @@ -40476,6 +40479,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { const cl_uint n_tokens = (cl_uint) src_v->ne[2]; const cl_uint n_seqs = (cl_uint) src_v->ne[3]; const cl_uint K = (cl_uint) ggml_get_op_params_i32(dst, 0); + const bool replay = dst->src[6] != nullptr; + const cl_uint n_pend = replay ? (cl_uint) ggml_get_op_params_i32(dst, 1) : 0; + const cl_uint keep = replay ? (cl_uint) ggml_get_op_params_i32(dst, 2) : 0; int si; switch (S_v) { @@ -40509,7 +40515,7 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { // spw needs adjustment when S_v != 128 const int spw = (tgpp == 0) ? 1 : 1; - cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp]; + cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay]; GGML_ASSERT(kernel != nullptr); const cl_uint s_off = S_v * H_v * n_tokens * n_seqs; @@ -40576,7 +40582,59 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_k)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &rq3)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K)); + + if (replay) { + const ggml_tensor * src_pk = dst->src[6]; + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + const ggml_tensor * src_rep = dst->src[9]; + + GGML_ASSERT(src_pk && src_pk->extra); + GGML_ASSERT(src_pv && src_pv->extra); + GGML_ASSERT(src_pgb && src_pgb->extra); + GGML_ASSERT(src_rep && src_rep->extra); + + const ggml_tensor_extra_cl * extra_pk = (const ggml_tensor_extra_cl *) src_pk->extra; + const ggml_tensor_extra_cl * extra_pv = (const ggml_tensor_extra_cl *) src_pv->extra; + const ggml_tensor_extra_cl * extra_pgb = (const ggml_tensor_extra_cl *) src_pgb->extra; + const ggml_tensor_extra_cl * extra_rep = (const ggml_tensor_extra_cl *) src_rep->extra; + + const cl_ulong off_pk = extra_pk->offset + src_pk->view_offs; + const cl_ulong off_pv = extra_pv->offset + src_pv->view_offs; + const cl_ulong off_pgb = extra_pgb->offset + src_pgb->view_offs; + const cl_ulong off_rep = extra_rep->offset + src_rep->view_offs; + + const cl_ulong spk1 = src_pk->nb[1] / sizeof(float); + const cl_ulong spk2 = src_pk->nb[2] / sizeof(float); + const cl_ulong spk3 = src_pk->nb[3] / sizeof(float); + const cl_ulong spv1 = src_pv->nb[1] / sizeof(float); + const cl_ulong spv2 = src_pv->nb[2] / sizeof(float); + const cl_ulong spv3 = src_pv->nb[3] / sizeof(float); + const cl_ulong spg1 = src_pgb->nb[1] / sizeof(float); + const cl_ulong spg2 = src_pgb->nb[2] / sizeof(float); + const cl_ulong spg3 = src_pgb->nb[3] / sizeof(float); + + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_pend)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &keep)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pk->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pk)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pv->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pv)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pgb->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pgb)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_rep->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_rep)); + } + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K)); // Subgroup size is 64 for Adreno and 32 for Intel const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1; diff --git a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl index 319c9829529a..78b807cfdbba 100644 --- a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl +++ b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl @@ -18,6 +18,9 @@ #ifndef KDA #define KDA 0 #endif +#ifndef REPLAY +#define REPLAY 0 +#endif #ifndef SUBGROUP_SIZE #define SUBGROUP_SIZE 64 #endif @@ -97,6 +100,13 @@ kernel void kernel_gated_delta_net( uint H_k, uint rq3, float scale, +#if REPLAY + uint n_pend, uint keep, + global const char * pk_buf, ulong off_pk, ulong spk1, ulong spk2, ulong spk3, + global const char * pv_buf, ulong off_pv, ulong spv1, ulong spv2, ulong spv3, + global const char * pgb_buf, ulong off_pgb, ulong spg1, ulong spg2, ulong spg3, + global const char * rep_buf, ulong off_rep, +#endif uint K) { global const float * data_q = (global const float *)(q_buf + off_q); @@ -144,6 +154,77 @@ kernel void kernel_gated_delta_net( } } +#if REPLAY + global const float * data_pk = (global const float *)(pk_buf + off_pk); + global const float * data_pv = (global const float *)(pv_buf + off_pv); + global const float * data_pgb = (global const float *)(pgb_buf + off_pgb); + global const int * data_n_rep = (global const int *)(rep_buf + off_rep); + const uint n_r = (uint)clamp(data_n_rep[seq_id], 0, (int)n_pend); + + for (uint t = 0; t < n_r; t++) { + const ulong k_off = seq_id * spk3 + t * spk2 + iq1 * spk1; + const ulong v_off = seq_id * spv3 + t * spv2 + head_id * spv1; + const ulong g_off = seq_id * spg3 + t * spg2 + head_id * spg1; + const float beta_val = data_pgb[g_off + n_pend * spg2]; + + float k_reg[ROWS_PER_LANE]; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { + k_reg[r] = data_pk[k_off + r * LANES_PER_COLUMN + lane]; + } + +#if KDA + float g_exp[ROWS_PER_LANE]; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { + g_exp[r] = exp(data_pgb[g_off + r * LANES_PER_COLUMN + lane]); + } +#else + const float g_val = exp(data_pgb[g_off]); +#endif + + // Same state update as the main loop, without the attention output. + #pragma unroll + for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) { + const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group; + float kv_shard = 0.0f; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { +#if KDA + kv_shard += g_exp[r] * s_shard[cg][r] * k_reg[r]; +#else + kv_shard += s_shard[cg][r] * k_reg[r]; +#endif + } +#if !KDA + kv_shard *= g_val; +#endif + const float kv_col = REDUCE_PARTIAL(kv_shard, temp_ptr, sg_lid); + const float delta_col = (data_pv[v_off + col] - kv_col) * beta_val; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { +#if KDA + const float gs = g_exp[r] * s_shard[cg][r]; +#else + const float gs = g_val * s_shard[cg][r]; +#endif + s_shard[cg][r] = gs + k_reg[r] * delta_col; + } + } + } + + if (keep) { + #pragma unroll + for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) { + const uint col = sg_col_base + cg * LANE_GROUPS_PER_SG + lane_group; + #pragma unroll + for (uint r = 0; r < ROWS_PER_LANE; r++) { + data_dst[s_off + state_base + col * S_V + r * LANES_PER_COLUMN + lane] = s_shard[cg][r]; + } + } + } +#endif + // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. // When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned. uint attn_off = (seq_id * n_tokens * H_v + head_id) * S_V; @@ -236,6 +317,11 @@ kernel void kernel_gated_delta_net( } } +#if REPLAY + if (keep) { + return; + } +#endif if (K == 1u) { #pragma unroll for (uint cg = 0; cg < COLS_PER_LANE_GROUP; cg++) { diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 7e64c03c2bc1..e1ba0baeb94b 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -2113,6 +2113,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { } return {false, reason}; } + if (((const int32_t *) op->op_params)[1] != 0) { + return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"}; + } break; } case GGML_OP_SSM_SCAN: { diff --git a/ggml/src/ggml-sycl/ggml-sycl.cpp b/ggml/src/ggml-sycl/ggml-sycl.cpp index 75df12c733cb..12d1bdfba36c 100644 --- a/ggml/src/ggml-sycl/ggml-sycl.cpp +++ b/ggml/src/ggml-sycl/ggml-sycl.cpp @@ -7709,10 +7709,12 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons case GGML_OP_RWKV_WKV6: case GGML_OP_RWKV_WKV7: case GGML_OP_GATED_LINEAR_ATTN: - case GGML_OP_GATED_DELTA_NET: case GGML_OP_OPT_STEP_ADAMW: case GGML_OP_OPT_STEP_SGD: return true; + case GGML_OP_GATED_DELTA_NET: + // replay of pending tokens (op param 1) is not implemented + return ggml_get_op_params_i32(op, 1) == 0; case GGML_OP_SSM_CONV: return op->type == GGML_TYPE_F32 && op->src[0]->type == GGML_TYPE_F32 && diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp index 79258b871145..42f058bd8e26 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan-debug.cpp @@ -1370,9 +1370,10 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph } else if (tensor->op == GGML_OP_LIGHTNING_INDEXER) { tensor_clone = ggml_lightning_indexer(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3]); } else if (tensor->op == GGML_OP_GATED_DELTA_NET) { - tensor_clone = ggml_gated_delta_net(ggml_ctx, src_clone[0], src_clone[1], - src_clone[2], src_clone[3], src_clone[4], src_clone[5], - ggml_get_op_params_i32(tensor, 0)); + GGML_ASSERT(ggml_get_op_params_i32(tensor, 0) == 1); // K > 1 comes from the deprecated ggml_gated_delta_net + tensor_clone = ggml_gated_delta_net_ext(ggml_ctx, src_clone[0], src_clone[1], + src_clone[2], src_clone[3], src_clone[4], src_clone[5], src_clone[6], src_clone[7], src_clone[8], src_clone[9], + ggml_get_op_params_i32(tensor, 2) != 0); } else if (tensor->op == GGML_OP_OPT_STEP_ADAMW) { src_clone[0]->flags = tensor->src[0]->flags; tensor_clone = ggml_opt_step_adamw(ggml_ctx, src_clone[0], src_clone[1], diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index 7a48c08dc3a9..026ad8935e34 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -794,6 +794,10 @@ struct vk_op_gated_delta_net_push_constants { uint32_t neq1, rq3; float scale; uint32_t K; + uint32_t n_pend, keep; // replay: pending tokens per seq, write the state after the replay + uint32_t spk1, spk2, spk3; // replay: pend_k, pend_v and pend_gb strides in floats + uint32_t spv1, spv2, spv3; + uint32_t spg1, spg2, spg3; }; struct vk_op_ssm_scan_push_constants { diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 211948ee793b..f200b43d30f5 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -1013,8 +1013,8 @@ struct vk_device_struct { vk_pipeline pipeline_rwkv_wkv7_f32; vk_pipeline pipeline_gated_linear_attn_f32; vk_pipeline pipeline_lightning_indexer_f32[GGML_TYPE_COUNT]; - // [size_idx][kda] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 - vk_pipeline pipeline_gated_delta_net[4][2]; + // [size_idx][kda][replay] where size_idx: 0=d16, 1=d32, 2=d64, 3=d128 + vk_pipeline pipeline_gated_delta_net[4][2][2]; vk_pipeline pipeline_gated_delta_net_cm; vk_pipeline pipeline_gated_delta_net_cm_v32; vk_pipeline pipeline_gated_delta_net_cm_v128; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 0711166f9671..88e595f4a8e9 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4212,9 +4212,12 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { const std::array wg_denoms = {1u, 1u, cols_per_wg}; for (uint32_t kda = 0; kda < 2; kda++) { - ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda], - gdn_names[si][kda], gdn_len, gdn_data, "main", 7, sizeof(vk_op_gated_delta_net_push_constants), - wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows)}, 1, true, use_subgroup_ops, gdn_subgroup_size); + for (uint32_t rep = 0; rep < 2; rep++) { + const std::string name = std::string(gdn_names[si][kda]) + (rep ? "_rep" : ""); + ggml_vk_create_pipeline(device, device->pipeline_gated_delta_net[si][kda][rep], + name.c_str(), gdn_len, gdn_data, "main", 11, sizeof(vk_op_gated_delta_net_push_constants), + wg_denoms, {S_V, kda, gdn_subgroup_size, lanes_per_column, uint32_t(gdn_packed_rows), rep}, 1, true, use_subgroup_ops, gdn_subgroup_size); + } } } @@ -10235,6 +10238,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { const uint32_t S_v = dst->src[2]->ne[0]; const uint32_t kda = (dst->src[3]->ne[0] == (int64_t)S_v) ? 1 : 0; + const uint32_t rep = dst->src[6] != nullptr ? 1 : 0; uint32_t si; switch (S_v) { case 16: si = 0; break; @@ -10243,7 +10247,7 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const case 128: si = 3; break; default: return nullptr; } - return ctx->device->pipeline_gated_delta_net[si][kda]; + return ctx->device->pipeline_gated_delta_net[si][kda][rep]; } return nullptr; case GGML_OP_SSM_SCAN: @@ -11357,7 +11361,8 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, const bool use_cm = (ctx->device->pipeline_gated_delta_net_cm != nullptr || ctx->device->pipeline_gated_delta_net_cm_v32 != nullptr || ctx->device->pipeline_gated_delta_net_cm_v128 != nullptr) && - src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens; + src_g->ne[0] == 1 && S_v == 128 && dst->src[0]->ne[0] == 128 && K == 1 && n_tokens >= cm_min_tokens && + dst->src[6] == nullptr; // the chunked kernels do not replay const bool use_cm2 = use_cm && ctx->device->coopmat2; const bool have_v64 = ctx->device->pipeline_gated_delta_net_cm != nullptr; @@ -11389,9 +11394,10 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst); - vk_subbuffer src_buf[6] = {}; - for (int i = 0; i < 6; i++) { - src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]); + vk_subbuffer src_buf[10] = {}; + for (int i = 0; i < 10; i++) { + // the replay sources 6..9 bind q when the op has no replay + src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i] ? dst->src[i] : src_q); } vk_subbuffer mirror_buf{}; @@ -11409,6 +11415,11 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, mirror_buf = vk_subbuffer{ ctx->prealloc_x, 0, ctx->prealloc_x->size }; } + // replay of pending tokens, see ggml_gated_delta_net_ext + const ggml_tensor * src_pk = dst->src[6]; + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + const uint32_t sq1 = (uint32_t)(src_q->nb[1] / sizeof(float)); const uint32_t sq2 = (uint32_t)(src_q->nb[2] / sizeof(float)); const uint32_t sq3 = (uint32_t)(src_q->nb[3] / sizeof(float)); @@ -11434,7 +11445,18 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, sb1, sb2, sb3, neq1, rq3, scale, - K + K, + src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 1) : 0u, + src_pk ? (uint32_t)ggml_get_op_params_i32(dst, 2) : 0u, + src_pk ? (uint32_t)(src_pk->nb[1] / sizeof(float)) : 0u, + src_pk ? (uint32_t)(src_pk->nb[2] / sizeof(float)) : 0u, + src_pk ? (uint32_t)(src_pk->nb[3] / sizeof(float)) : 0u, + src_pv ? (uint32_t)(src_pv->nb[1] / sizeof(float)) : 0u, + src_pv ? (uint32_t)(src_pv->nb[2] / sizeof(float)) : 0u, + src_pv ? (uint32_t)(src_pv->nb[3] / sizeof(float)) : 0u, + src_pgb ? (uint32_t)(src_pgb->nb[1] / sizeof(float)) : 0u, + src_pgb ? (uint32_t)(src_pgb->nb[2] / sizeof(float)) : 0u, + src_pgb ? (uint32_t)(src_pgb->nb[3] / sizeof(float)) : 0u, }; if (use_v128) { @@ -11442,10 +11464,15 @@ void ggml_vk_gated_delta_net(ggml_backend_vk_context * ctx, vk_context& subctx, {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, mirror_buf}, pc, std::array{ S_v / cm_V, n_seqs, H }); ctx->prealloc_x_need_sync = true; - } else { + } else if (use_cm) { ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf}, - pc, use_cm ? std::array{ S_v / cm_V, n_seqs, H } : std::array{ H, n_seqs, S_v }); + pc, std::array{ S_v / cm_V, n_seqs, H }); + } else { + ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, + {src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], dst_buf, + src_buf[6], src_buf[7], src_buf[8], src_buf[9]}, + pc, std::array{ H, n_seqs, S_v }); } } @@ -11692,9 +11719,10 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor const uint64_t n = ggml_nelements(dst); GGML_ASSERT(n > 0); + // dst can be a view at any offset: bind from the aligned offset below it, the shader skips KY elements vk_op_push_constants pc = { (uint32_t)n, - 1, + get_misalign_bytes(ctx, dst) / (uint32_t)ggml_type_size(dst->type), ggml_get_op_params_f32(dst, 0), 0.0f, 0.0f, 0.0f, @@ -11710,7 +11738,7 @@ void ggml_vk_fill(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor GGML_ASSERT(wg_y <= ctx->device->properties.limits.maxComputeWorkGroupCount[1]); ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1); - vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, false); + vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true); std::array elements = { wg_x * pipeline->wg_denoms[0], wg_y * pipeline->wg_denoms[1], 1 }; ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { dst_buf }, pc, elements); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp b/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp index b5cc33322078..bfae6a3d128c 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/fill.comp @@ -16,6 +16,6 @@ void main() { return; } - // p.param1 = fill value - data_d[i] = D_TYPE(p.param1); + // p.param1 = fill value, p.KY = element offset of dst in the bound buffer + data_d[p.KY + i] = D_TYPE(p.param1); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp index ad2ced78aa39..75c32a067595 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/gated_delta_net.comp @@ -16,6 +16,7 @@ layout(constant_id = 1) const uint KDA = 0; layout(constant_id = 2) const uint SUBGROUP_SIZE = 32; layout(constant_id = 3) const uint LANES_PER_COLUMN = 32; layout(constant_id = 4) const bool PACKED_ROWS = false; +layout(constant_id = 5) const uint REPLAY = 0; const uint COLS_PER_WG = SUBGROUP_SIZE / LANES_PER_COLUMN; const uint ROWS_PER_LANE = S_V / LANES_PER_COLUMN; @@ -42,6 +43,10 @@ layout(push_constant) uniform Parameters { uint neq1, rq3; float scale; uint K; + uint n_pend, keep; + uint spk1, spk2, spk3; + uint spv1, spv2, spv3; + uint spg1, spg2, spg3; }; layout(binding = 0) readonly buffer QBuf { FLOAT_TYPE data_q[]; }; @@ -52,6 +57,12 @@ layout(binding = 4) readonly buffer BetaBuf { FLOAT_TYPE data_beta[]; }; layout(binding = 5) readonly buffer StateBuf { FLOAT_TYPE data_state[]; }; layout(binding = 6) buffer DstBuf { FLOAT_TYPE data_dst[]; }; +// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext) +layout(binding = 7) readonly buffer PKBuf { FLOAT_TYPE data_pk[]; }; +layout(binding = 8) readonly buffer PVBuf { FLOAT_TYPE data_pv[]; }; +layout(binding = 9) readonly buffer PGBBuf { FLOAT_TYPE data_pgb[]; }; +layout(binding = 10) readonly buffer NRepBuf { int data_n_rep[]; }; + #if !USE_SUBGROUP_ADD && !USE_SUBGROUP_CLUSTERED shared FLOAT_TYPE temp[SUBGROUP_SIZE]; @@ -123,6 +134,55 @@ void main() { s_shard[r] = FLOAT_TYPE(data_state[state_in_base + col * S_V + row_index(r, lane)]); } + if (REPLAY != 0) { + const uint n_r = uint(clamp(data_n_rep[seq_id], 0, int(n_pend))); + + for (uint t = 0; t < n_r; t++) { + const uint k_off = seq_id * spk3 + t * spk2 + iq1 * spk1; + const uint v_off = seq_id * spv3 + t * spv2 + head_id * spv1; + const uint g_off = seq_id * spg3 + t * spg2 + head_id * spg1; + const FLOAT_TYPE beta_val = FLOAT_TYPE(data_pgb[g_off + n_pend * spg2]); + + FLOAT_TYPE k_reg[ROWS_PER_LANE]; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + k_reg[r] = FLOAT_TYPE(data_pk[k_off + row_index(r, lane)]); + } + + FLOAT_TYPE g_exp[ROWS_PER_LANE]; + if (KDA == 0) { + const FLOAT_TYPE g_val = exp(FLOAT_TYPE(data_pgb[g_off])); + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + g_exp[r] = g_val; + } + } else { + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + g_exp[r] = exp(FLOAT_TYPE(data_pgb[g_off + row_index(r, lane)])); + } + } + + const FLOAT_TYPE v_val = FLOAT_TYPE(data_pv[v_off + col]); + + // same update as below, without the attention output + FLOAT_TYPE kv_shard = 0.0; + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + kv_shard += g_exp[r] * s_shard[r] * k_reg[r]; + } + FLOAT_TYPE kv_col = reduce_partial(kv_shard); + + FLOAT_TYPE delta_col = (v_val - kv_col) * beta_val; + + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + s_shard[r] = g_exp[r] * s_shard[r] + k_reg[r] * delta_col; + } + } + + if (keep != 0) { + [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { + data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; + } + } + } + // snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back. // When n_tokens < K, only slots 0..n_tokens-1 are written; older slots are caller-owned. @@ -191,7 +251,8 @@ void main() { } } - if (K == 1u) { + // replay with keep: the state output is the state after the replay + if (K == 1u && !(REPLAY != 0 && keep != 0)) { [[unroll]] for (uint r = 0; r < ROWS_PER_LANE; r++) { data_dst[s_off + state_out_base + col * S_V + row_index(r, lane)] = s_shard[r]; } diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index 8896efb5af4a..6b618bb16370 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -450,9 +450,11 @@ struct ggml_webgpu_gated_delta_net_pipeline_key { int s_v; int kda; bool fused_cache; + bool replay; bool operator==(const ggml_webgpu_gated_delta_net_pipeline_key & other) const { - return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache; + return type == other.type && s_v == other.s_v && kda == other.kda && fused_cache == other.fused_cache && + replay == other.replay; } }; @@ -462,6 +464,7 @@ struct ggml_webgpu_gated_delta_net_pipeline_key_hash { ggml_webgpu_hash_combine(seed, key.type); ggml_webgpu_hash_combine(seed, key.s_v); ggml_webgpu_hash_combine(seed, key.kda); + ggml_webgpu_hash_combine(seed, key.replay); return seed; } }; @@ -2015,6 +2018,7 @@ class ggml_webgpu_shader_lib { key.s_v = (int) context.src2->ne[0]; key.kda = context.src3->ne[0] == context.src2->ne[0]; key.fused_cache = context.dst_fuse != nullptr; + key.replay = context.dst->src[6] != nullptr; auto it = gated_delta_net_pipelines.find(key); if (it != gated_delta_net_pipelines.end()) { @@ -2042,6 +2046,11 @@ class ggml_webgpu_shader_lib { variant += "_fused_cache"; } + if (key.replay) { + defines.push_back("REPLAY"); + variant += "_replay"; + } + defines.push_back("S_V=" + std::to_string(key.s_v) + "u"); defines.push_back("WG_SIZE=" + std::to_string(key.s_v) + "u"); diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 4bb43926daaa..daf83ee83ce4 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -1497,6 +1497,11 @@ static webgpu_encoded_op ggml_webgpu_ssm_scan(webgpu_context & ctx, return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +// storage buffers of the gated delta net shader: q, k, v, g, beta, state and dst, the fused cache, then the replay inputs +static uint32_t ggml_webgpu_gated_delta_net_n_storage_buffers(const ggml_tensor * op, bool fused_cache) { + return 7 + (fused_cache ? 1 : 0) + (op->src[6] != nullptr ? 4 : 0); +} + static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, ggml_tensor * src0, ggml_tensor * src1, @@ -1527,6 +1532,12 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, uint32_t scale_u32; memcpy(&scale_u32, &scale, sizeof(scale_u32)); + // replay of pending tokens, see ggml_gated_delta_net_ext + ggml_tensor * pend_k = dst->src[6]; + ggml_tensor * pend_v = dst->src[7]; + ggml_tensor * pend_gb = dst->src[8]; + ggml_tensor * n_rep = dst->src[9]; + std::vector params = { h, n_tokens, @@ -1551,6 +1562,21 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, scale_u32, dst_fuse ? (uint32_t) (dst_fuse->nb[2] / ggml_type_size(dst_fuse->type)) : 0, dst_fuse ? (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst_fuse) / ggml_type_size(dst_fuse->type)) : 0, + + pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 1) : 0, + pend_k ? (uint32_t) ggml_get_op_params_i32(dst, 2) : 0, + + pend_k ? (uint32_t) (pend_k->nb[1] / ggml_type_size(pend_k->type)) : 0, + pend_k ? (uint32_t) (pend_k->nb[2] / ggml_type_size(pend_k->type)) : 0, + pend_k ? (uint32_t) (pend_k->nb[3] / ggml_type_size(pend_k->type)) : 0, + + pend_v ? (uint32_t) (pend_v->nb[1] / ggml_type_size(pend_v->type)) : 0, + pend_v ? (uint32_t) (pend_v->nb[2] / ggml_type_size(pend_v->type)) : 0, + pend_v ? (uint32_t) (pend_v->nb[3] / ggml_type_size(pend_v->type)) : 0, + + pend_gb ? (uint32_t) (pend_gb->nb[1] / ggml_type_size(pend_gb->type)) : 0, + pend_gb ? (uint32_t) (pend_gb->nb[2] / ggml_type_size(pend_gb->type)) : 0, + pend_gb ? (uint32_t) (pend_gb->nb[3] / ggml_type_size(pend_gb->type)) : 0, }; std::vector entries = { @@ -1564,6 +1590,14 @@ static webgpu_encoded_op ggml_webgpu_gated_delta_net(webgpu_context & ctx, entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, 7, dst_fuse)); } + if (pend_k) { + const uint32_t binding = dst_fuse ? 8 : 7; + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 0, pend_k)); + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 1, pend_v)); + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 2, pend_gb)); + entries.push_back(ggml_webgpu_make_tensor_bind_group_entry(ctx, binding + 3, n_rep)); + } + return ggml_backend_webgpu_build(ctx, pipeline, params, entries, h, n_seqs); } @@ -3728,7 +3762,9 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, return ggml_webgpu_ssm_scan(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node->src[6], node); case GGML_OP_GATED_DELTA_NET: - if (ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) { + if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <= + ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage && + ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) { ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1]; return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5], node, dst_fuse); @@ -5270,7 +5306,9 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const src2->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F32 && op->src[4]->type == GGML_TYPE_F32 && op->src[5]->type == GGML_TYPE_F32 && s_v <= ctx->webgpu_global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup && - ggml_are_same_stride(src0, src1); + ggml_are_same_stride(src0, src1) && + ggml_webgpu_gated_delta_net_n_storage_buffers(op, false) <= + ctx->webgpu_global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage; } break; case GGML_OP_CLAMP: diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl index 6f4b5a31c16c..1a5b3208bec0 100644 --- a/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl +++ b/ggml/src/ggml-webgpu/wgsl-shaders/gated_delta_net.wgsl @@ -23,10 +23,31 @@ var dst: array; @group(0) @binding(7) var dst_fuse: array; #define DST_SNAP dst_fuse -#define PARAMS_BINDING 8 +#define NEXT_BINDING 8 #else #define DST_SNAP dst -#define PARAMS_BINDING 7 +#define NEXT_BINDING 7 +#endif + +#ifdef REPLAY +// pending tokens to run before the new ones (see ggml_gated_delta_net_ext) +@group(0) @binding(NEXT_BINDING) +var pend_k: array; + +@group(0) @binding(NEXT_BINDING + 1) +var pend_v: array; + +@group(0) @binding(NEXT_BINDING + 2) +var pend_gb: array; + +@group(0) @binding(NEXT_BINDING + 3) +var n_rep: array; + +var wg_n_rep: u32; + +#define PARAMS_BINDING (NEXT_BINDING + 4) +#else +#define PARAMS_BINDING NEXT_BINDING #endif struct Params { @@ -53,6 +74,21 @@ struct Params { scale: f32, dst_fuse_nb2: u32, dst_fuse_off: u32, + + n_pend: u32, + keep: u32, + + spk1: u32, + spk2: u32, + spk3: u32, + + spv1: u32, + spv2: u32, + spv3: u32, + + spg1: u32, + spg2: u32, + spg3: u32, }; @group(0) @binding(PARAMS_BINDING) @@ -92,6 +128,66 @@ fn main( state[i] = src_state[state_in_base + col * S_V + i]; } +#ifdef REPLAY + if (col == 0u) { + wg_n_rep = u32(n_rep[seq_id]); + } + let n_r = workgroupUniformLoad(&wg_n_rep); + + for (var t = 0u; t < n_r; t++) { + let k_off = seq_id * params.spk3 + t * params.spk2 + iq1 * params.spk1; + let v_off = seq_id * params.spv3 + t * params.spv2 + head_id * params.spv1; + let g_off = seq_id * params.spg3 + t * params.spg2 + head_id * params.spg1; + + sh_k[col] = pend_k[k_off + col]; + +#ifdef KDA + sh_g[col] = exp(pend_gb[g_off + col]); +#endif + + workgroupBarrier(); + + let v_val = pend_v[v_off + col]; + let beta_val = pend_gb[g_off + params.n_pend * params.spg2]; + + // same update as below, without the attention output + var kv_col = 0.0; + var delta_col = 0.0; + +#ifdef KDA + for (var i = 0u; i < S_V; i++) { + kv_col += (sh_g[i] * state[i]) * sh_k[i]; + } + + delta_col = (v_val - kv_col) * beta_val; + + for (var i = 0u; i < S_V; i++) { + state[i] = sh_g[i] * state[i] + sh_k[i] * delta_col; + } +#else + let g_val = exp(pend_gb[g_off]); + + for (var i = 0u; i < S_V; i++) { + kv_col += state[i] * sh_k[i]; + } + + delta_col = (v_val - g_val * kv_col) * beta_val; + + for (var i = 0u; i < S_V; i++) { + state[i] = g_val * state[i] + sh_k[i] * delta_col; + } +#endif + + workgroupBarrier(); + } + + if (params.keep != 0u) { + for (var i = 0u; i < S_V; i++) { + DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i]; + } + } +#endif + var attn_off = (seq_id * params.n_tokens * params.h + head_id) * S_V; for (var t = 0u; t < params.n_tokens; t++) { @@ -160,7 +256,14 @@ fn main( workgroupBarrier(); } - if (params.K == 1u) { +#ifdef REPLAY + // replay with keep: the state output is the state after the replay + let write_state = params.K == 1u && params.keep == 0u; +#else + let write_state = params.K == 1u; +#endif + + if (write_state) { for (var i = 0u; i < S_V; i++) { DST_SNAP[snap_off + state_out_base + col * S_V + i] = state[i]; } diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 947342125327..88ade6e8ae3a 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -6373,7 +6373,7 @@ struct ggml_tensor * ggml_solve_tri( // ggml_gated_delta_net -struct ggml_tensor * ggml_gated_delta_net( +static struct ggml_tensor * ggml_gated_delta_net_impl( struct ggml_context * ctx, struct ggml_tensor * q, struct ggml_tensor * k, @@ -6381,7 +6381,12 @@ struct ggml_tensor * ggml_gated_delta_net( struct ggml_tensor * g, struct ggml_tensor * beta, struct ggml_tensor * state, - int64_t K) { + struct ggml_tensor * pend_k, + struct ggml_tensor * pend_v, + struct ggml_tensor * pend_gb, + struct ggml_tensor * n_rep, + int64_t K, + bool keep) { GGML_ASSERT(ggml_is_contiguous_rows(q)); GGML_ASSERT(ggml_is_contiguous_rows(k)); GGML_ASSERT(ggml_is_contiguous_rows(v)); @@ -6425,9 +6430,61 @@ struct ggml_tensor * ggml_gated_delta_net( result->src[4] = beta; result->src[5] = state; + const bool replay = pend_k != NULL; + GGML_ASSERT((pend_v != NULL) == replay && (pend_gb != NULL) == replay && (n_rep != NULL) == replay); + GGML_ASSERT(replay || !keep); + if (replay) { + const int64_t n_pend = pend_k->ne[2]; + + GGML_ASSERT(K == 1); + GGML_ASSERT(pend_k->type == GGML_TYPE_F32 && pend_v->type == GGML_TYPE_F32 && pend_gb->type == GGML_TYPE_F32); + GGML_ASSERT(n_rep->type == GGML_TYPE_I32); + GGML_ASSERT(pend_k->nb[0] == sizeof(float) && pend_v->nb[0] == sizeof(float) && pend_gb->nb[0] == sizeof(float)); + GGML_ASSERT(pend_k->ne[0] == k->ne[0] && pend_k->ne[1] == k->ne[1] && pend_k->ne[3] == n_seqs); + GGML_ASSERT(pend_v->ne[0] == S_v && pend_v->ne[1] == H && pend_v->ne[2] == n_pend && pend_v->ne[3] == n_seqs); + GGML_ASSERT(pend_gb->ne[0] == g->ne[0] && pend_gb->ne[1] == H && pend_gb->ne[2] == 2*n_pend && pend_gb->ne[3] == n_seqs); + GGML_ASSERT(ggml_is_contiguous(n_rep) && ggml_nelements(n_rep) == n_seqs); + + ggml_set_op_params_i32(result, 1, (int32_t) n_pend); + ggml_set_op_params_i32(result, 2, keep ? 1 : 0); + + result->src[6] = pend_k; + result->src[7] = pend_v; + result->src[8] = pend_gb; + result->src[9] = n_rep; + } + return result; } +struct ggml_tensor * ggml_gated_delta_net_ext( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * g, + struct ggml_tensor * beta, + struct ggml_tensor * state, + struct ggml_tensor * pend_k, + struct ggml_tensor * pend_v, + struct ggml_tensor * pend_gb, + struct ggml_tensor * n_rep, + bool keep) { + return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, pend_k, pend_v, pend_gb, n_rep, 1, keep); +} + +struct ggml_tensor * ggml_gated_delta_net( + struct ggml_context * ctx, + struct ggml_tensor * q, + struct ggml_tensor * k, + struct ggml_tensor * v, + struct ggml_tensor * g, + struct ggml_tensor * beta, + struct ggml_tensor * state, + int64_t K) { + return ggml_gated_delta_net_impl(ctx, q, k, v, g, beta, state, NULL, NULL, NULL, NULL, K, false); +} + // ggml_lightning_indexer struct ggml_tensor * ggml_lightning_indexer( diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 07a0dbafc17e..4caca65f3674 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -190,6 +190,14 @@ llama_context::llama_context( cparams.n_rs_seq = 0; } + // delta-net rollback keeps one state and the inputs of the last ubatch; the gdn op replays the kept tokens before the new ones + cparams.rs_replay = cparams.n_rs_seq > 0 && ( + model.arch == LLM_ARCH_QWEN35 || model.arch == LLM_ARCH_QWEN35MOE || model.arch == LLM_ARCH_QWEN4EXP || + model.arch == LLM_ARCH_CLOVER_MOE || + // KDA + model.arch == LLM_ARCH_KIMI_K3 || model.arch == LLM_ARCH_KIMI_K31 || model.arch == LLM_ARCH_GLM5_NEXT || + model.arch == LLM_ARCH_BAILINGMOE3); + cparams.n_threads = params.n_threads; cparams.n_threads_batch = params.n_threads_batch; cparams.yarn_ext_factor = params.yarn_ext_factor >= 0.0f ? params.yarn_ext_factor : hparams.yarn_ext_factor; @@ -435,6 +443,7 @@ llama_context::llama_context( LLAMA_LOG_INFO("%s: freq_base = %.1f\n", __func__, cparams.rope_freq_base); LLAMA_LOG_INFO("%s: freq_scale = %g\n", __func__, cparams.rope_freq_scale); LLAMA_LOG_INFO("%s: n_rs_seq = %u\n", __func__, cparams.n_rs_seq); + LLAMA_LOG_INFO("%s: rs_replay = %s\n", __func__, cparams.rs_replay ? "true" : "false"); LLAMA_LOG_INFO("%s: n_outputs_max = %u\n", __func__, cparams.n_outputs_max); LLAMA_LOG_INFO("%s: n_outputs_max_per_seq = %u\n", __func__, cparams.n_outputs_max_per_seq); diff --git a/src/llama-cparams.h b/src/llama-cparams.h index c93494fafeb1..c71582a3cd2e 100644 --- a/src/llama-cparams.h +++ b/src/llama-cparams.h @@ -14,6 +14,7 @@ struct llama_cparams { uint32_t n_ubatch; uint32_t n_seq_max; uint32_t n_rs_seq; // number of recurrent-state snapshots per seq for rollback + bool rs_replay; // roll back by replaying kept tokens instead of keeping n_rs_seq snapshots uint32_t n_outputs_max; // max outputs supported by the context uint32_t n_outputs_max_per_seq; int32_t n_threads; // number of threads to use for generation diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 862476a5f60a..5fef4c42168a 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -527,8 +527,6 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) { } void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) { - GGML_UNUSED(ubatch); - const int64_t n_rs = mctx->get_n_rs(); if (s_copy) { @@ -540,6 +538,34 @@ void llm_graph_input_rs::set_input(const llama_ubatch * ubatch) { data[i] = mctx->s_copy(i); } } + + set_input_rep(mctx, ubatch); +} + +void llm_graph_input_rs::set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch) { + if (!has_rep) { + return; + } + + const int64_t n_seqs = ubatch->n_seqs; + + int32_t * reps = (int32_t *) rep_n->data; + int32_t * cols = (int32_t *) rep_cols->data; + + GGML_ASSERT(ggml_backend_buffer_is_host(rep_n->buffer)); + GGML_ASSERT(ggml_backend_buffer_is_host(rep_cols->buffer)); + + for (int64_t s = 0; s < n_seqs; ++s) { + const int64_t n_rep = mctx->get_rs_rep(s); + GGML_ASSERT(n_rep <= n_pend); + + reps[s] = n_rep; + + // the conv history is [window | pending]: the window after the kept tokens + for (int64_t c = 0; c < n_conv; ++c) { + cols[s*n_conv + c] = n_rep + c; + } + } } bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) { @@ -1261,6 +1287,8 @@ void llm_graph_input_mem_hybrid::set_input(const llama_ubatch * ubatch) { data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) { @@ -1307,6 +1335,8 @@ void llm_graph_input_mem_hybrid_k::set_input(const llama_ubatch * ubatch) { data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) { @@ -1364,6 +1394,8 @@ void llm_graph_input_mem_hybrid_iswa::set_input(const llama_ubatch * ubatch) { data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params) { @@ -1443,6 +1475,8 @@ void llm_graph_input_mem_hybrid_iswa_rel::set_input(const llama_ubatch * ubatch) data[i] = mctx->get_recr()->s_copy(i); } } + + inp_rs->set_input_rep(mctx->get_recr(), ubatch); } bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & params) { @@ -4136,6 +4170,8 @@ ggml_tensor * llm_graph_context::build_rs( static std::unique_ptr build_rs_inp_impl( ggml_context * ctx0, const llama_ubatch & ubatch, + const llama_hparams & hparams, + const llama_cparams & cparams, const llama_memory_recurrent_context * mctx_cur) { auto inp = std::make_unique(mctx_cur); @@ -4153,13 +4189,38 @@ static std::unique_ptr build_rs_inp_impl( inp->head = mctx_cur->get_head(); inp->rs_z = mctx_cur->get_rs_z(); + inp->has_rep = mctx_cur->get_rs_replay(); + if (inp->has_rep) { + // the widest conv window of the model: the delta-net conv, or the PLE n-gram conv (qwen4exp) + const int64_t n_conv_r = hparams.ssm_d_conv - 1; + const int64_t n_conv_p = hparams.ple_conv_state() > 0 ? (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size : 0; + + inp->n_conv = std::max(n_conv_r, n_conv_p); + inp->n_pend = cparams.n_rs_seq + 1; + + inp->rep_cols = ggml_new_tensor_2d(ctx0, GGML_TYPE_I32, inp->n_conv, n_seqs); + ggml_set_input(inp->rep_cols); + ggml_set_name(inp->rep_cols, "rs_rep_cols"); + + const auto win = [&](int64_t n) { + return n == inp->n_conv ? inp->rep_cols : ggml_view_2d(ctx0, inp->rep_cols, n, n_seqs, inp->rep_cols->nb[1], 0); + }; + + inp->rep_cols_r = win(n_conv_r); + inp->rep_cols_p = n_conv_p > 0 ? win(n_conv_p) : nullptr; + + inp->rep_n = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, n_seqs); + ggml_set_input(inp->rep_n); + ggml_set_name(inp->rep_n, "rs_rep_n"); + } + return inp; } llm_graph_input_rs * llm_graph_context::build_rs_inp() const { const auto * mctx_cur = static_cast(mctx); - auto inp = build_rs_inp_impl(ctx0, ubatch, mctx_cur); + auto inp = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur); return (llm_graph_input_rs *) res->add_input(std::move(inp)); } @@ -4286,7 +4347,7 @@ ggml_tensor * llm_graph_context::build_rwkv_token_shift_store( llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); auto inp_attn = build_attn_inp_kv_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); @@ -4297,7 +4358,7 @@ llm_graph_input_mem_hybrid * llm_graph_context::build_inp_mem_hybrid() const { llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl (ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl (ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); auto inp_attn = build_attn_inp_k_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_attn()); auto inp = std::make_unique(cparams, std::move(inp_attn), std::move(inp_rs), mctx_cur); @@ -4308,7 +4369,7 @@ llm_graph_input_mem_hybrid_k * llm_graph_context::build_inp_mem_hybrid_k() const llm_graph_input_mem_hybrid_iswa * llm_graph_context::build_inp_mem_hybrid_iswa() const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); // build iswa attention input const auto * attn_ctx = mctx_cur->get_attn(); @@ -4345,7 +4406,7 @@ llm_graph_input_mem_hybrid_iswa_rel * llm_graph_context::build_inp_mem_hybrid_is uint32_t extent_swa) const { const auto * mctx_cur = static_cast(mctx); - auto inp_rs = build_rs_inp_impl(ctx0, ubatch, mctx_cur->get_recr()); + auto inp_rs = build_rs_inp_impl(ctx0, ubatch, hparams, cparams, mctx_cur->get_recr()); const auto * attn_ctx = mctx_cur->get_attn(); diff --git a/src/llama-graph.h b/src/llama-graph.h index 116b7132a53e..ff155f14d2f6 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -323,6 +323,19 @@ class llm_graph_input_rs : public llm_graph_input_i { ggml_tensor * s_copy_main; // I32 [n_seqs] ggml_tensor * s_copy_tail; // I32 [n_rs - 1] + // rs_replay: the ubatch first replays the kept pending tokens of the last ubatch (none is a no-op) + bool has_rep = false; + int64_t n_conv = 0; // conv window columns, the widest conv of the model + int64_t n_pend = 0; // pending slots per seq + ggml_tensor * rep_n = nullptr; // I32 [n_seqs], kept pending tokens + ggml_tensor * rep_cols = nullptr; // I32 [n_conv, n_seqs], conv history columns of the window after the kept tokens + + // views of rep_cols for the delta-net conv and the PLE conv windows, computed once per graph and shared across layers + ggml_tensor * rep_cols_r = nullptr; + ggml_tensor * rep_cols_p = nullptr; + + void set_input_rep(const llama_memory_recurrent_context * mctx, const llama_ubatch * ubatch); + const llama_memory_recurrent_context * mctx; // used in view offsets, need to match for valid graph reuse diff --git a/src/llama-memory-hybrid-idx.cpp b/src/llama-memory-hybrid-idx.cpp index 0199c734e341..3866d5980f37 100644 --- a/src/llama-memory-hybrid-idx.cpp +++ b/src/llama-memory-hybrid-idx.cpp @@ -33,6 +33,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx( /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ @@ -44,7 +45,7 @@ llama_memory_hybrid_idx::llama_memory_hybrid_idx( no_alloc, type_k, type_v, v_trans, kv_size, n_swa, swa_type, type_r, type_s, rs_size, - n_seq_max, n_rs_seq, offload, unified, + n_seq_max, n_rs_seq, rs_replay, offload, unified, filter_attn, filter_recr), hparams_idx(model.hparams), mem_idx(filter_idx == nullptr ? nullptr : [&] { diff --git a/src/llama-memory-hybrid-idx.h b/src/llama-memory-hybrid-idx.h index 85a2a91ec28b..ebd082ab5685 100644 --- a/src/llama-memory-hybrid-idx.h +++ b/src/llama-memory-hybrid-idx.h @@ -33,6 +33,7 @@ class llama_memory_hybrid_idx : public llama_memory_hybrid { /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ diff --git a/src/llama-memory-hybrid-iswa.cpp b/src/llama-memory-hybrid-iswa.cpp index 6d843c76ee86..569a09ee2192 100644 --- a/src/llama-memory-hybrid-iswa.cpp +++ b/src/llama-memory-hybrid-iswa.cpp @@ -59,6 +59,7 @@ llama_memory_hybrid_iswa::llama_memory_hybrid_iswa( rs_size, n_seq_max, n_rs_seq, + false, filter_recr == nullptr ? [&](int32_t il) { return hparams.is_recr(il); } : filter_recr diff --git a/src/llama-memory-hybrid.cpp b/src/llama-memory-hybrid.cpp index 7d3b279088e6..a93e256b05a7 100644 --- a/src/llama-memory-hybrid.cpp +++ b/src/llama-memory-hybrid.cpp @@ -25,6 +25,7 @@ llama_memory_hybrid::llama_memory_hybrid( /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ @@ -60,6 +61,7 @@ llama_memory_hybrid::llama_memory_hybrid( rs_size, n_seq_max, n_rs_seq, + rs_replay, filter_recr == nullptr ? [&](int32_t il) { return hparams.is_recr(il); } : filter_recr diff --git a/src/llama-memory-hybrid.h b/src/llama-memory-hybrid.h index 2b4d1269c3c2..b4df21f15155 100644 --- a/src/llama-memory-hybrid.h +++ b/src/llama-memory-hybrid.h @@ -35,6 +35,7 @@ class llama_memory_hybrid : public llama_memory_i { /* common */ uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, bool offload, bool unified, /* layer filters */ diff --git a/src/llama-memory-recurrent.cpp b/src/llama-memory-recurrent.cpp index 0d5739695186..bab6276f65d2 100644 --- a/src/llama-memory-recurrent.cpp +++ b/src/llama-memory-recurrent.cpp @@ -26,6 +26,7 @@ llama_memory_recurrent::llama_memory_recurrent( uint32_t mem_size, uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, const layer_filter_cb & filter) : hparams(model.hparams), n_seq_max(n_seq_max), ctxs_bufs(no_alloc) { const int32_t n_layer = hparams.n_layer(); @@ -33,7 +34,8 @@ llama_memory_recurrent::llama_memory_recurrent( size = mem_size; used = 0; - this->n_rs_seq = n_rs_seq; + this->n_rs_seq = n_rs_seq; + this->rs_replay = rs_replay && n_rs_seq > 0; rs_idx.assign(n_seq_max, 0); cells.clear(); @@ -53,7 +55,7 @@ llama_memory_recurrent::llama_memory_recurrent( if (it == ctx_map.end()) { ggml_init_params params = { // r and s per layer, plus the separate PLE conv row where the model has one - /*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 3u : 2u)*n_layer*ggml_tensor_overhead()), + /*.mem_size =*/ size_t((hparams.ple_conv_state() > 0 ? 6u : 5u)*n_layer*ggml_tensor_overhead()), /*.mem_buffer =*/ NULL, /*.no_alloc =*/ true, }; @@ -74,6 +76,9 @@ llama_memory_recurrent::llama_memory_recurrent( r_l.resize(n_layer); s_l.resize(n_layer); p_l.resize(n_layer); + spk_l.resize(n_layer); + spv_l.resize(n_layer); + spgb_l.resize(n_layer); for (int i = 0; i < n_layer; i++) { if (filter && !filter(i)) { @@ -99,17 +104,45 @@ llama_memory_recurrent::llama_memory_recurrent( throw std::runtime_error("failed to create ggml context for rs cache"); } - const uint32_t n_rows = mem_size * (1 + n_rs_seq); - ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, hparams.n_embd_r(), n_rows); + // rs_replay: r is the conv history [channels, d_conv - 1 + n_pend], the window then the pending columns, + // and spk, spv, spgb hold the gdn k, v, gate and beta of up to n_pend pending tokens + const int64_t n_pend = n_rs_seq + 1; + const int64_t n_ch = hparams.n_embd_r() / std::max(1, hparams.ssm_d_conv - 1); + const int64_t n_embd_r = this->rs_replay ? n_ch*(hparams.ssm_d_conv - 1 + n_pend) : hparams.n_embd_r(); + + const uint32_t n_rows = mem_size * (this->rs_replay ? 1 : 1 + n_rs_seq); + ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, n_embd_r, n_rows); ggml_tensor * s = ggml_new_tensor_2d(ctx, type_s, hparams.n_embd_s(), n_rows); ggml_format_name(r, "cache_r_l%d", i); ggml_format_name(s, "cache_s_l%d", i); r_l[i] = r; s_l[i] = s; + if (this->rs_replay) { + // k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend]: separate rows, so that a split by heads + // is one axis of each (-sm tensor). The gate is a scalar per head (g0 = 1), or per key dim for KDA (g0 = S_v) + const bool kda = hparams.n_embd_head_kda != 0; + const int64_t n_k = kda ? (int64_t) hparams.n_embd_head_kda*hparams.n_head() : (int64_t) hparams.ssm_d_state*hparams.ssm_n_group; + const int64_t n_v = kda ? n_k : (int64_t) hparams.ssm_d_inner; + const int64_t n_gb = kda ? n_k : (int64_t) hparams.ssm_dt_rank; + ggml_tensor * spk = ggml_new_tensor_2d(ctx, type_s, n_k*n_pend, mem_size); + ggml_tensor * spv = ggml_new_tensor_2d(ctx, type_s, n_v*n_pend, mem_size); + ggml_tensor * spgb = ggml_new_tensor_2d(ctx, type_s, n_gb*2*n_pend, mem_size); + ggml_format_name(spk, "cache_spk_l%d", i); + ggml_format_name(spv, "cache_spv_l%d", i); + ggml_format_name(spgb, "cache_spgb_l%d", i); + spk_l[i] = spk; + spv_l[i] = spv; + spgb_l[i] = spgb; + } + // the PLE history needs its own row: Meta must mirror it while the delta-net conv state next door stays split if (hparams.ple_conv_state() > 0 && hparams.is_ple(i)) { - ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, hparams.ple_conv_state(), n_rows); + // rs_replay: [channels, window + n_pend], like r + const int64_t n_win_p = (int64_t) (hparams.ple_conv_kernel - 1)*hparams.ple_ngram_size; + const int64_t n_embd_p = this->rs_replay ? hparams.ple_conv_state()/n_win_p*(n_win_p + n_pend) : hparams.ple_conv_state(); + + ggml_tensor * p = ggml_new_tensor_2d(ctx, type_r, n_embd_p, n_rows); ggml_format_name(p, "cache_ple_r_l%d", i); p_l[i] = p; } @@ -124,7 +157,8 @@ llama_memory_recurrent::llama_memory_recurrent( if (is_empty()) { if (n_rs_seq > 0) { - n_rs_seq = 0; + n_rs_seq = 0; + rs_replay = false; LLAMA_LOG_INFO("%s: disabling rollback snapshots because the memory module is empty\n", __func__); } } @@ -134,8 +168,8 @@ llama_memory_recurrent::llama_memory_recurrent( const size_t memory_size_s = size_s_bytes(); const size_t memory_size_p = size_p_bytes(); - LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__, - (float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq, + LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq%s), R (%s): %7.2f MiB, S (%s): %7.2f MiB, P (%s): %7.2f MiB\n", __func__, + (float)(memory_size_r + memory_size_s + memory_size_p) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq, rs_replay ? " replay" : "", ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f), ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f), ggml_type_name(type_r), (float)memory_size_p / (1024.0f * 1024.0f)); @@ -149,6 +183,8 @@ void llama_memory_recurrent::clear(bool data) { cells[i].src = -1; cells[i].tail = -1; cells[i].rs_max = 0; + cells[i].rs_pend = 0; + cells[i].rs_rep = 0; } head = 0; @@ -210,7 +246,13 @@ bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos // pending rollback is single-use const bool pending = rs_idx[seq_id] != 0; if (!pending && rollback >= 1 && rollback <= (llama_pos) cell.rs_max) { - set_rs_idx(seq_id, (uint32_t) rollback); + if (rs_replay) { + // the next ubatch replays only the kept pending tokens + cell.rs_pend -= rollback; + cell.rs_max = 0; + } else { + set_rs_idx(seq_id, (uint32_t) rollback); + } cell.pos = p0 - 1; return true; } @@ -615,6 +657,7 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { auto & orig_cell = cells[seq_meta.tail]; empty_cell.pos = orig_cell.pos; empty_cell.src = orig_cell.src; + empty_cell.rs_pend = orig_cell.rs_pend; orig_cell.seq_id.erase(seq_id); empty_cell.seq_id.insert(seq_id); // will be overwritten GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id @@ -645,7 +688,13 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { std::swap(dst_cell.pos, src_cell.pos); std::swap(dst_cell.src, src_cell.src); + std::swap(dst_cell.rs_max, src_cell.rs_max); + std::swap(dst_cell.rs_pend, src_cell.rs_pend); std::swap(dst_cell.seq_id, src_cell.seq_id); + // the cell moved out only gets its final state copied, its rollback snapshots stay behind + if (!rs_replay) { + src_cell.rs_max = 0; + } // swap tails for (uint32_t j = 0; j < size; ++j) { @@ -674,6 +723,11 @@ bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) { } cell.pos = last_pos; cell.rs_max = n_seq_tokens <= n_rs_seq + 1 ? n_seq_tokens - 1 : 0; + if (rs_replay) { + // replay what the last ubatch left pending, then keep this ubatch pending if it can be rolled back + cell.rs_rep = cell.src >= 0 ? cell.rs_pend : 0; + cell.rs_pend = cell.rs_max > 0 ? n_seq_tokens : 0; + } cell.seq_id.clear(); for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) { const llama_seq_id seq_id = ubatch.seq_id[i][j]; @@ -753,6 +807,7 @@ size_t llama_memory_recurrent::size_r_bytes() const { } } + return size_r_bytes; } @@ -765,6 +820,14 @@ size_t llama_memory_recurrent::size_s_bytes() const { } } + for (const auto * sp : { &spk_l, &spv_l, &spgb_l }) { + for (const auto & s : *sp) { + if (s != nullptr) { + size_s_bytes += ggml_nbytes(s); + } + } + } + return size_s_bytes; } @@ -907,6 +970,10 @@ void llama_memory_recurrent::state_write_meta(llama_io_write_i & io, const std:: io.write(&seq_id, sizeof(seq_id)); } } + + if (rs_replay) { + io.write(&cell.rs_pend, sizeof(cell.rs_pend)); + } } } } @@ -929,7 +996,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std:: io.write(&r_type_i, sizeof(r_type_i)); // Write row size of R tensor - const uint64_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); + const uint64_t r_size_row = r_l[il]->nb[1]; io.write(&r_size_row, sizeof(r_size_row)); // Write each logical cell row range. With pending recurrent rollback, @@ -942,7 +1009,7 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std:: // the PLE conv history is a second recurrent row, so it has to travel with the first if (p_l[il] != nullptr) { - const uint64_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); + const uint64_t p_size_row = p_l[il]->nb[1]; io.write(&p_size_row, sizeof(p_size_row)); for (const auto & range : cell_ranges) { @@ -1004,6 +1071,22 @@ void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std:: } } } + + // rs_replay pending inputs travel with their cells + if (rs_replay) { + for (uint32_t il = 0; il < n_layer; ++il) { + for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) { + if (t == nullptr) continue; + + const uint64_t size_row = t->nb[1]; + io.write(&size_row, sizeof(size_row)); + + for (const auto & range : cell_ranges) { + io.write_tensor(t, range.first * size_row, (range.second - range.first) * size_row); + } + } + } + } } bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) { @@ -1024,6 +1107,8 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1); + std::vector rs_pend(cell_count, 0); + for (uint32_t i = 0; i < cell_count; ++i) { llama_pos pos; uint32_t n_seq_id; @@ -1036,6 +1121,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell return false; } + if (rs_replay) { + io.read(&rs_pend[i], sizeof(rs_pend[i])); + } + ubatch.pos[i] = pos; } ubatch.n_seq_id[0] = 1; @@ -1053,6 +1142,11 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]); GGML_ASSERT(cells[head].has_seq_id(dest_seq_id)); GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id)); + + for (uint32_t i = 0; i < cell_count; ++i) { + cells[head + i].rs_pend = rs_pend[i]; + cells[head + i].rs_max = 0; + } } else { // whole KV cache restore @@ -1092,6 +1186,10 @@ bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell } tail = i; } + + if (rs_replay) { + io.read(&cell.rs_pend, sizeof(cell.rs_pend)); + } } head = 0; @@ -1143,7 +1241,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell // Read row size of key uint64_t r_size_row_ref; io.read(&r_size_row_ref, sizeof(r_size_row_ref)); - const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); + const size_t r_size_row = r_l[il]->nb[1]; if (r_size_row != r_size_row_ref) { LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il); return false; @@ -1157,7 +1255,7 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell if (p_l[il] != nullptr) { uint64_t p_size_row_ref; io.read(&p_size_row_ref, sizeof(p_size_row_ref)); - const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); + const size_t p_size_row = p_l[il]->nb[1]; if (p_size_row != p_size_row_ref) { LLAMA_LOG_ERROR("%s: mismatched ple row size (%zu != %zu, layer %d)\n", __func__, p_size_row, (size_t) p_size_row_ref, il); return false; @@ -1242,6 +1340,25 @@ bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell } } + if (rs_replay) { + for (uint32_t il = 0; il < n_layer; ++il) { + for (ggml_tensor * t : { spk_l[il], spv_l[il], spgb_l[il] }) { + if (t == nullptr) continue; + + uint64_t size_row_ref; + io.read(&size_row_ref, sizeof(size_row_ref)); + if (size_row_ref != t->nb[1]) { + LLAMA_LOG_ERROR("%s: mismatched pending row size (%zu != %zu, layer %d)\n", __func__, t->nb[1], (size_t) size_row_ref, il); + return false; + } + + if (cell_count) { + io.read_tensor(t, head * t->nb[1], cell_count * t->nb[1]); + } + } + } + } + return true; } @@ -1264,7 +1381,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head for (uint32_t il = 0; il < n_layer; ++il) { if (r_l[il] != nullptr) { - const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r()); + const size_t r_size_row = r_l[il]->nb[1]; ggml_backend_tensor_memset(r_l[il], 0, cell_head * r_size_row, cell_count * r_size_row); } @@ -1274,7 +1391,7 @@ void llama_memory_recurrent::state_clear(llama_seq_id seq_id, uint32_t cell_head } if (p_l[il] != nullptr) { - const size_t p_size_row = ggml_row_size(p_l[il]->type, hparams.ple_conv_state()); + const size_t p_size_row = p_l[il]->nb[1]; ggml_backend_tensor_memset(p_l[il], 0, cell_head * p_size_row, cell_count * p_size_row); } } @@ -1360,6 +1477,26 @@ ggml_tensor * llama_memory_recurrent_context::get_p_l(int32_t il) const { return mem->p_l[il]; } +ggml_tensor * llama_memory_recurrent_context::get_spk_l(int32_t il) const { + return mem->spk_l[il]; +} + +ggml_tensor * llama_memory_recurrent_context::get_spv_l(int32_t il) const { + return mem->spv_l[il]; +} + +ggml_tensor * llama_memory_recurrent_context::get_spgb_l(int32_t il) const { + return mem->spgb_l[il]; +} + +bool llama_memory_recurrent_context::get_rs_replay() const { + return mem->rs_replay; +} + +uint32_t llama_memory_recurrent_context::get_rs_rep(int i) const { + return is_full ? 0 : mem->cells[i + mem->head].rs_rep; +} + int32_t llama_memory_recurrent_context::s_copy(int i) const { const uint32_t cell_idx = i + mem->head; const int32_t src0 = mem->cells[cell_idx].src0; diff --git a/src/llama-memory-recurrent.h b/src/llama-memory-recurrent.h index 6442fc1c15d7..5efe9c3b49ce 100644 --- a/src/llama-memory-recurrent.h +++ b/src/llama-memory-recurrent.h @@ -25,6 +25,7 @@ class llama_memory_recurrent : public llama_memory_i { uint32_t mem_size, uint32_t n_seq_max, uint32_t n_rs_seq, + bool rs_replay, const layer_filter_cb & filter); ~llama_memory_recurrent() = default; @@ -77,6 +78,9 @@ class llama_memory_recurrent : public llama_memory_i { // per-seq rollback index std::vector rs_idx; + // deferred commit: keep one state plane plus the inputs of the last ubatch, replay the accepted part in the next ubatch + bool rs_replay = false; + void set_rs_idx(llama_seq_id seq_id, uint32_t idx); // computed before each graph build @@ -93,9 +97,13 @@ class llama_memory_recurrent : public llama_memory_i { int32_t tail = -1; // largest rollback whose snapshot the last ubatch guarantees: a ubatch of n <= n_rs_seq + 1 tokens - // writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_gated_delta_net) + // writes snapshots 0..n-1, a longer one only guarantees the final state (ggml_ssm_scan) uint32_t rs_max = 0; + // rs_replay: valid tokens in the pending rows, and the pending tokens the current ubatch replays + uint32_t rs_pend = 0; + uint32_t rs_rep = 0; + std::set seq_id; bool has_seq_id(const llama_seq_id & id) const { @@ -118,6 +126,10 @@ class llama_memory_recurrent : public llama_memory_i { std::vector s_l; // a second conv history that must stay replicated across devices, so it cannot share the r row std::vector p_l; + // rs_replay pending gdn inputs: k, v, and the gates then the betas + std::vector spk_l; + std::vector spv_l; + std::vector spgb_l; private: //const llama_model & model; @@ -184,9 +196,15 @@ class llama_memory_recurrent_context : public llama_memory_context_i { ggml_tensor * get_r_l(int32_t il) const; ggml_tensor * get_s_l(int32_t il) const; ggml_tensor * get_p_l(int32_t il) const; + ggml_tensor * get_spk_l (int32_t il) const; + ggml_tensor * get_spv_l (int32_t il) const; + ggml_tensor * get_spgb_l(int32_t il) const; int32_t s_copy(int i) const; + bool get_rs_replay() const; + uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i + private: const llama_memory_status status; diff --git a/src/llama-model.cpp b/src/llama-model.cpp index fa20378aa6d2..b20459646ece 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -468,6 +468,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str static const std::regex pattern_r_cache ("cache_r_l\\d*"); static const std::regex pattern_ple_r_cache ("cache_ple_r_l\\d*"); static const std::regex pattern_s_cache ("cache_s_l\\d*"); + static const std::regex pattern_spk_cache ("cache_spk_l\\d*"); + static const std::regex pattern_spv_cache ("cache_spv_l\\d*"); + static const std::regex pattern_spgb_cache ("cache_spgb_l\\d*"); static const std::regex pattern_ssm_conv1d ("blk\\.\\d*\\.ssm_conv1d.weight"); static const std::regex pattern_ssm_out_weight ("blk\\.\\d*\\.ssm_out.weight"); static const std::regex pattern_kda_conv1d ("blk\\.\\d*\\.ssm_conv1d_(q|k|v)\\.weight"); @@ -577,7 +580,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_2, "attn_output.weight"); } if (std::regex_match(tensor_name, pattern_ssm_dt) || std::regex_match(tensor_name, pattern_ssm_a) || - std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) { + std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) || + std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache)) { return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_0, "attn_output.weight"); } } @@ -642,7 +647,9 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str std::regex_match(tensor_name, pattern_ssm_beta_alpha) || std::regex_match(tensor_name, pattern_ssm_beta_alpha_cat)) { return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_1, "ssm_out.weight"); } - if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache)) { + if (std::regex_match(tensor_name, pattern_r_cache) || std::regex_match(tensor_name, pattern_s_cache) || + std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache)) { if (ud->model->arch == LLM_ARCH_LFM2 || ud->model->arch == LLM_ARCH_LFM2MOE || ud->model->arch == LLM_ARCH_LFM3) { // the LFM2 shortconv block runs fully mirrored, so its conv state must be mirrored too return get_tensor_config_impl(GGML_BACKEND_SPLIT_AXIS_MIRRORED, ""); @@ -697,10 +704,22 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str auto get_split_segments = [&](int axis, uint32_t il) -> std::vector> { if (is_glm5_next && std::regex_match(tensor_name, pattern_r_cache)) { // the conv state holds the q, k and v windows one after the other - const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * hparams.n_embd_head_kda; - GGML_ASSERT(tensor->ne[axis] == 3*conv_state_size); + const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda; + const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * d_inner; + if (tensor->ne[axis] != 3*conv_state_size) { + // replay: q, k and v histories [d_inner, window + pending], every column is a block of heads + GGML_ASSERT(tensor->ne[axis] % (3*d_inner) == 0); + return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}}; + } return {{conv_state_size, 3}}; } + if (is_glm5_next && (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache))) { + // replay pending inputs, per token: k [S_k, H], v [S_v, H], then the gates [S_v, H] and the betas (in element 0) + const int64_t d_inner = hparams.n_head(il) * hparams.n_embd_head_kda; + GGML_ASSERT(tensor->ne[axis] % d_inner == 0); + return {{d_inner, uint32_t(tensor->ne[axis] / d_inner)}}; + } // TODO: deduplicate condition [TAG_SPLIT_QGATE_QWEN] // zonos3 has the qwen35 GDN layout, its attention layers have no fused qkv if (ud->model->arch == LLM_ARCH_QWEN3NEXT || ud->model->arch == LLM_ARCH_QWEN35 || ud->model->arch == LLM_ARCH_QWEN35MOE || ud->model->arch == LLM_ARCH_CLEF || ud->model->arch == LLM_ARCH_CLOVER_MOE || @@ -731,6 +750,8 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return {{key_dim, 2}, {value_dim, 1}}; } if (std::regex_match(tensor_name, pattern_r_cache)) { + // the replay layouts need the Qwen 3.5 pattern, llama_context keeps Qwen 3 Next on snapshots + GGML_ASSERT(tensor->ne[axis] == (2*key_dim + value_dim) * (hparams.ssm_d_conv - 1)); return {{key_dim * (hparams.ssm_d_conv - 1), 2}, {value_dim * (hparams.ssm_d_conv - 1), 1}}; } } else { @@ -755,11 +776,26 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return {{n_k_heads, head_ratio}}; } if (std::regex_match(tensor_name, pattern_r_cache)) { + const int64_t n_conv_ch = 2*key_dim + value_dim; + if (tensor->ne[axis] != n_conv_ch * (hparams.ssm_d_conv - 1)) { + // replay: [channels, window + pending] per cell, every column is a q, k, v block + GGML_ASSERT(tensor->ne[axis] % n_conv_ch == 0); + return {{key_dim, uint32_t((2 + head_ratio) * (tensor->ne[axis] / n_conv_ch))}}; + } return {{key_dim * (hparams.ssm_d_conv - 1), 2 + head_ratio}}; } if (std::regex_match(tensor_name, pattern_s_cache)) { return {{n_k_heads * head_v_dim * head_v_dim, head_ratio}}; } + // replay pending inputs, per token: k [S_k, H_k], v [S_v, H_v], then the gates and betas [H_v] + if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) { + GGML_ASSERT(tensor->ne[axis] % key_dim == 0); + return {{key_dim, uint32_t(tensor->ne[axis] / key_dim)}}; + } + if (std::regex_match(tensor_name, pattern_spgb_cache)) { + GGML_ASSERT(tensor->ne[axis] % n_k_heads == 0); + return {{n_k_heads, uint32_t(tensor->ne[axis] / n_k_heads)}}; + } } // the FFN is the same for Qwen 3 Next and Qwen 3.5: @@ -815,7 +851,14 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return {granularity_qkv / head_dim}; } if (std::regex_match(tensor_name, pattern_r_cache)) { - return std::vector(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1)); + // replay: channels first, each segment is a single conv column + const int64_t conv_state_size = (hparams.ssm_d_conv - 1) * hparams.n_head(il) * head_dim; + const bool replay = tensor->ne[0] != 3*conv_state_size; + return std::vector(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1)); + } + if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache) || + std::regex_match(tensor_name, pattern_spgb_cache)) { + return std::vector(segments.size(), granularity_qkv); } if (std::regex_match(tensor_name, pattern_s_cache)) { return {granularity_qkv * head_dim}; @@ -852,11 +895,20 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str return std::vector(segments.size(), 2 * (granularity_qkv / head_dim)); } if (std::regex_match(tensor_name, pattern_r_cache)) { - return std::vector(segments.size(), granularity_qkv * (hparams.ssm_d_conv - 1)); + // replay: [channels, window + pending], each segment is a single conv column + const int64_t n_conv_ch = 2*hparams.ssm_n_group*hparams.ssm_d_state + hparams.ssm_d_inner; + const bool replay = tensor->ne[0] != n_conv_ch * (hparams.ssm_d_conv - 1); + return std::vector(segments.size(), granularity_qkv * (replay ? 1 : hparams.ssm_d_conv - 1)); } if (std::regex_match(tensor_name, pattern_s_cache)) { return std::vector(segments.size(), granularity_qkv * head_dim); } + if (std::regex_match(tensor_name, pattern_spk_cache) || std::regex_match(tensor_name, pattern_spv_cache)) { + return std::vector(segments.size(), granularity_qkv); + } + if (std::regex_match(tensor_name, pattern_spgb_cache)) { + return std::vector(segments.size(), granularity_qkv / head_dim); + } } else { // regular attention const uint32_t n_gqa = hparams.n_gqa(il); @@ -3220,6 +3272,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* recurrent_rs_size */ std::max((uint32_t) 1, cparams.n_seq_max), /* n_seq_max */ cparams.n_seq_max, /* n_rs_seq */ cparams.n_rs_seq, + /* rs_replay */ cparams.rs_replay, /* offload */ cparams.offload_kqv, /* unified */ cparams.kv_unified, /* filter_attn */ std::move(filter_attn), @@ -3433,6 +3486,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, std::max((uint32_t) 1, cparams.n_seq_max), cparams.n_seq_max, cparams.n_rs_seq, + false, nullptr); } else if (llm_arch_is_hybrid(arch) && !mtp_on_hybrid_qwen && !mtp_on_hybrid_nemotron) { // The main difference between hybrid architectures is the @@ -3527,6 +3581,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max), /* n_seq_max */ cparams.n_seq_max, /* n_rs_seq */ cparams.n_rs_seq, + /* rs_replay */ cparams.rs_replay, /* offload */ cparams.offload_kqv, /* unified */ cparams.kv_unified, /* filter_attn */ std::move(filter_attn), @@ -3547,6 +3602,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, /* recurrent_kv_size */ std::max((uint32_t) 1, cparams.n_seq_max), /* n_seq_max */ cparams.n_seq_max, /* n_rs_seq */ cparams.n_rs_seq, + /* rs_replay */ cparams.rs_replay, /* offload */ cparams.offload_kqv, /* unified */ cparams.kv_unified, /* filter_attn */ std::move(filter_attn), diff --git a/src/models/bailingmoe3.cpp b/src/models/bailingmoe3.cpp index ad1f0ee27b1f..20d940ca32e4 100644 --- a/src/models/bailingmoe3.cpp +++ b/src/models/bailingmoe3.cpp @@ -163,22 +163,29 @@ std::unique_ptr llama_model_bailingmoe3::build_arch_graph(con ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t total_state_size = 3 * conv_state_size; - ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - total_state_size * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); x_proj = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_proj, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + total_state_size * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state, ggml_transpose(ctx0, x_proj), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * out = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -227,17 +234,17 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) : if (hparams.is_recr(il)) { const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); ggml_tensor * q = build_causal_conv1d( inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, - d_conv, head_dim, n_head, n_seq_tokens, n_seqs); + d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); ggml_tensor * k = build_causal_conv1d( inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, - d_conv, head_dim, n_head, n_seq_tokens, n_seqs); + d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); ggml_tensor * v = build_causal_conv1d( inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, - d_conv, head_dim, n_head, n_seq_tokens, n_seqs); + d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il); ggml_tensor * gate = ggml_mul_mat(ctx0, layer.ssm_f_a, cur); gate = ggml_add(ctx0, gate, layer.ssm_dt_b); diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp index 45b2de4bbc9d..f05bd8c0a2ba 100644 --- a/src/models/delta-net-base.cpp +++ b/src/models/delta-net-base.cpp @@ -32,8 +32,8 @@ std::pair llm_build_delta_net_base::build_delta_ne GGML_ASSERT(b->ne[0] == 1 && b->ne[1] == H_v && b->ne[2] == n_tokens && b->ne[3] == n_seqs); GGML_ASSERT(s->ne[0] == S_v && s->ne[1] == S_v && s->ne[2] == H_v && s->ne[3] == n_seqs); - // K=1: output carries the final state only. state s is 4D [S_v, S_v, H_v, n_seqs]. - ggml_tensor * result = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, /*K=*/1); + // output carries the final state. state s is 4D [S_v, S_v, H_v, n_seqs]. + ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, nullptr, nullptr, nullptr, nullptr, false); ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_tokens, n_seqs, ggml_row_size(result->type, S_v), @@ -59,6 +59,10 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( int il) { const int64_t n_seqs = ubatch.n_seqs; + if (cparams.rs_replay) { + return build_conv_state_replay(inp, conv_states_all, qkv_mixed, conv_kernel_size - 1, conv_channels, il); + } + ggml_tensor * conv_states = build_rs(inp, conv_states_all, hparams.n_embd_r(), n_seqs); cb(conv_states, "conv_states", il); @@ -76,7 +80,80 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( return conv_input; } -ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( +// [TAG_RECURRENT_REPLAY] +// rs_replay keeps one committed state per seq plus the inputs of the last ubatch when it is short enough to be rolled +// back (2 <= n_seq_tokens <= n_rs_seq + 1). The next ubatch first replays the pending tokens that seq_rm kept, commits +// the result and then runs its own tokens. Must match the rule in llama_memory_recurrent::find_slot. +// Every ubatch builds the same nodes, with or without pending tokens, so the allocation planned at reserve time +// stays valid and the scheduler never re-plans. +static bool rs_replay_keep(const llama_cparams & cparams, int64_t n_seq_tokens) { + return n_seq_tokens >= 2 && n_seq_tokens <= (int64_t) cparams.n_rs_seq + 1; +} + +ggml_tensor * llm_build_delta_net_base::build_conv_state_replay( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * x, + int64_t n_conv, + int64_t channels, + int il, + ggml_tensor * hist_rows, + int64_t blk) { + const auto * mctx_cur = inp->mctx; + + const auto kv_head = mctx_cur->get_head(); + + const int64_t n_hist = n_conv + cparams.n_rs_seq + 1; + const int64_t n_seqs = ubatch.n_seqs; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + + GGML_ASSERT(conv_states_all->ne[0] % (channels*n_hist) == 0); + const int64_t n_blk = conv_states_all->ne[0] / (channels*n_hist); + + GGML_ASSERT(blk >= 0 && blk < n_blk); + GGML_ASSERT(x->ne[0] == channels && x->ne[1] == n_seq_tokens && x->ne[2] == n_seqs); + GGML_ASSERT(n_conv <= inp->n_conv); + + if (hist_rows == nullptr) { + hist_rows = build_rs(inp, conv_states_all, conv_states_all->ne[0], n_seqs); + } + GGML_ASSERT(hist_rows->ne[0] == conv_states_all->ne[0] && hist_rows->ne[1] == n_seqs); + + // channels first: [window | pending], the histories of a row one after the other + ggml_tensor * hist = nullptr; + if (n_blk == 1) { + hist = ggml_reshape_3d(ctx0, hist_rows, channels, n_hist, n_seqs); + } else { + hist = ggml_reshape_4d(ctx0, hist_rows, channels, n_hist, n_blk, n_seqs); + hist = ggml_view_3d(ctx0, hist, channels, n_hist, n_seqs, hist->nb[1], hist->nb[3], blk*hist->nb[2]); + } + cb(hist, "conv_hist", il); + + ggml_tensor * win_cols = n_conv == inp->rep_cols_r->ne[0] ? inp->rep_cols_r : inp->rep_cols_p; + GGML_ASSERT(win_cols && win_cols->ne[0] == n_conv); + + // [channels, n_conv + n_seq_tokens]: the window after the kept pending tokens, then the new tokens + // (built channels first, a transposed concat is much slower than a concat and a transpose) + ggml_tensor * cols = ggml_concat(ctx0, ggml_get_rows(ctx0, hist, win_cols), x, 1); + + ggml_tensor * conv_input = ggml_cont(ctx0, ggml_transpose(ctx0, cols)); + cb(conv_input, "conv_input", il); + + // keep: the new tokens stay pending behind the committed window, else commit the last n_conv columns + const int64_t n_dst = rs_replay_keep(cparams, n_seq_tokens) ? n_conv + n_seq_tokens : n_conv; + + ggml_tensor * tail = ggml_view_3d(ctx0, cols, channels, n_dst, n_seqs, cols->nb[1], cols->nb[2], + (n_conv + n_seq_tokens - n_dst)*cols->nb[1]); + // the rows as [channels, n_blk*n_hist, cells], so that the view of the ubatch cells keeps their strides (-sm tensor) + ggml_tensor * hist_all = ggml_reshape_3d(ctx0, conv_states_all, channels, n_blk*n_hist, conv_states_all->ne[1]); + ggml_tensor * hist_dst = ggml_view_3d(ctx0, hist_all, channels, n_dst, n_seqs, hist_all->nb[1], hist_all->nb[2], + kv_head*hist_all->nb[2] + blk*n_hist*hist_all->nb[1]); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, tail, hist_dst)); + + return conv_input; +} + +ggml_tensor * llm_build_delta_net_base::build_recurrent_attn_replay( llm_graph_input_rs * inp, ggml_tensor * ssm_states_all, ggml_tensor * q, @@ -86,67 +163,112 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( ggml_tensor * b, ggml_tensor * s, int il) { - const auto * mctx_cur = inp->mctx; - const auto kv_head = mctx_cur->get_head(); - const uint32_t mem_size = mctx_cur->get_size(); - - const int64_t S_v = s->ne[0]; - const int64_t H_v = s->ne[2]; - const int64_t n_seqs = s->ne[3]; - const int64_t n_seq_tokens = q->ne[2]; - - const bool keep = cparams.n_rs_seq > 0; - - if (!keep) { - auto attn_out = build_delta_net(q, k, v, g, b, s); - ggml_tensor * output = attn_out.first; - ggml_tensor * new_state = attn_out.second; - cb(output, "attn_output", il); - cb(new_state, "new_state", il); - - ggml_build_forward_expand(gf, - ggml_cpy(ctx0, new_state, - ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], - kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all)))); - - return output; - } + const auto * mctx_cur = inp->mctx; + + const auto kv_head = mctx_cur->get_head(); - const int64_t D = S_v * S_v * H_v; - const int64_t K = cparams.n_rs_seq + 1; + const int64_t n_pend = cparams.n_rs_seq + 1; + const int64_t n_seqs = ubatch.n_seqs; + const int64_t n_seq_tokens = ubatch.n_seq_tokens; + + const int64_t S_k = k->ne[0]; + const int64_t H_k = k->ne[1]; + const int64_t S_v = v->ne[0]; + const int64_t H_v = v->ne[1]; + const int64_t g0 = g->ne[0]; - // state s is 4D [S_v, S_v, H_v, n_seqs]; K snapshot slots are written into the output. - ggml_tensor * gdn_out = ggml_gated_delta_net(ctx0, q, k, v, g, b, s, K); - const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs; - const int64_t state_size_per_snap = S_v * S_v * H_v * n_seqs; + const size_t row_size = ggml_row_size(ssm_states_all->type, hparams.n_embd_s()); - ggml_tensor * output = ggml_view_4d(ctx0, gdn_out, - S_v, H_v, n_seq_tokens, n_seqs, - ggml_row_size(gdn_out->type, S_v), - ggml_row_size(gdn_out->type, S_v * H_v), - ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens), - 0); + // the pending inputs of the cells: k [S_k, H_k, n_pend], v [S_v, H_v, n_pend], gb [g0, H_v, 2*n_pend] (the gates, + // then the betas). The views of the ubatch cells keep the strides of these 4D views, so that -sm tensor can split + // them by heads + ggml_tensor * spk = mctx_cur->get_spk_l(il); + ggml_tensor * spv = mctx_cur->get_spv_l(il); + ggml_tensor * spgb = mctx_cur->get_spgb_l(il); + + ggml_tensor * ck = ggml_reshape_4d(ctx0, spk, S_k, H_k, n_pend, spk->ne[1]); + ggml_tensor * cv = ggml_reshape_4d(ctx0, spv, S_v, H_v, n_pend, spv->ne[1]); + ggml_tensor * cgb = ggml_reshape_4d(ctx0, spgb, g0, H_v, 2*n_pend, spgb->ne[1]); + + const auto gather = [&](ggml_tensor * rows, ggml_tensor * c) { + return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs), c->ne[0], c->ne[1], c->ne[2], n_seqs); + }; + + ggml_tensor * pk = gather(spk, ck); + ggml_tensor * pv = gather(spv, cv); + ggml_tensor * pgb = gather(spgb, cgb); + + const bool keep = rs_replay_keep(cparams, n_seq_tokens); + + ggml_tensor * state_dst = ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], kv_head*row_size); + + // store the inputs of the new tokens as pending; only used when keep, a longer ubatch stores its first n_pend tokens + const auto store_inputs = [&]() { + const int64_t n_st = std::min(n_seq_tokens, n_pend); + + const auto store = [&](ggml_tensor * x, ggml_tensor * c, int64_t t0) { + ggml_tensor * x_st = ggml_view_4d(ctx0, x, x->ne[0], x->ne[1], n_st, n_seqs, x->nb[1], x->nb[2], x->nb[3], 0); + ggml_tensor * dst = ggml_view_4d(ctx0, c, x->ne[0], x->ne[1], n_st, n_seqs, c->nb[1], c->nb[2], c->nb[3], + kv_head*c->nb[3] + t0*c->nb[2]); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, x_st, dst)); + }; + + store(k, ck, 0); + store(v, cv, 0); + store(g, cgb, 0); + store(b, cgb, n_pend); + }; + + // the gdn op replays the kept pending tokens, then runs the new tokens + ggml_tensor * result = ggml_gated_delta_net_ext(ctx0, q, k, v, g, b, s, pk, pv, pgb, inp->rep_n, keep); + + ggml_tensor * output = ggml_view_4d(ctx0, result, S_v, H_v, n_seq_tokens, n_seqs, + ggml_row_size(result->type, S_v), + ggml_row_size(result->type, S_v*H_v), + ggml_row_size(result->type, S_v*H_v*n_seq_tokens), 0); cb(output, "attn_output", il); - const size_t row_size = hparams.n_embd_s() * ggml_element_size(ssm_states_all); + // keep: the state after the replay, else the final state + ggml_tensor * new_state = ggml_view_2d(ctx0, result, hparams.n_embd_s(), n_seqs, + ggml_row_size(result->type, hparams.n_embd_s()), + ggml_row_size(result->type, S_v*H_v*n_seq_tokens*n_seqs)); + ggml_build_forward_expand(gf, ggml_cpy(ctx0, new_state, state_dst)); + + store_inputs(); + + return output; +} + +ggml_tensor * llm_build_delta_net_base::build_recurrent_attn( + llm_graph_input_rs * inp, + ggml_tensor * ssm_states_all, + ggml_tensor * q, + ggml_tensor * k, + ggml_tensor * v, + ggml_tensor * g, + ggml_tensor * b, + ggml_tensor * s, + int il) { + if (cparams.rs_replay) { + return build_recurrent_attn_replay(inp, ssm_states_all, q, k, v, g, b, s, il); + } - // op writes the last min(n_seq_tokens, K) snapshots; trailing slots are left unwritten - const int64_t n_written = std::min(n_seq_tokens, K); + // a rollback replays the kept tokens, the gdn op does not write state snapshots + GGML_ASSERT(cparams.n_rs_seq == 0); - // write the produced snapshots into the recurrent cache (snapshot slot i -> rollback group i) - ggml_tensor * src = ggml_view_3d(ctx0, gdn_out, - D, n_seqs, n_written, - ggml_row_size(gdn_out->type, D), - ggml_row_size(gdn_out->type, state_size_per_snap), - ggml_row_size(gdn_out->type, attn_score_elems)); + const auto kv_head = inp->mctx->get_head(); + const int64_t n_seqs = s->ne[3]; - ggml_tensor * dst = ggml_view_3d(ctx0, ssm_states_all, - D, n_seqs, n_written, - ssm_states_all->nb[1], - (size_t) mem_size * row_size, - (size_t) kv_head * row_size); + auto attn_out = build_delta_net(q, k, v, g, b, s); + ggml_tensor * output = attn_out.first; + ggml_tensor * new_state = attn_out.second; + cb(output, "attn_output", il); + cb(new_state, "new_state", il); - ggml_build_forward_expand(gf, ggml_cpy(ctx0, src, dst)); + ggml_build_forward_expand(gf, + ggml_cpy(ctx0, new_state, + ggml_view_2d(ctx0, ssm_states_all, hparams.n_embd_s(), n_seqs, ssm_states_all->nb[1], + kv_head * hparams.n_embd_s() * ggml_element_size(ssm_states_all)))); return output; } diff --git a/src/models/glm5-next.cpp b/src/models/glm5-next.cpp index 51a26df3deaf..5d3944af28a7 100644 --- a/src/models/glm5-next.cpp +++ b/src/models/glm5-next.cpp @@ -194,22 +194,29 @@ std::unique_ptr llama_model_glm5_next::build_arch_graph(const ggml_tensor * llama_model_glm5_next::graph::build_kda_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head_kda; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t n_embd_r_total = 3 * conv_state_size; - ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - n_embd_r_total * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + n_embd_r_total * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -796,11 +803,11 @@ ggml_tensor * llama_model_glm5_next::graph::build_kda_layer( const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); - ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); cb(Qcur, "kda_q_conv", il); cb(Kcur, "kda_k_conv", il); cb(Vcur, "kda_v_conv", il); diff --git a/src/models/kimi-k3.cpp b/src/models/kimi-k3.cpp index 2e91c5243a64..e0ef7b6cd40a 100644 --- a/src/models/kimi-k3.cpp +++ b/src/models/kimi-k3.cpp @@ -355,22 +355,29 @@ llama_model_kimi_k3::graph::graph(const llm_graph_params & params) : ggml_tensor * llama_model_kimi_k3::graph::build_kda_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head_kda; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t n_embd_r_total = 3 * conv_state_size; - ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - n_embd_r_total * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + n_embd_r_total * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -388,11 +395,11 @@ ggml_tensor * llama_model_kimi_k3::graph::build_kda_layer( const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); - ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); cb(Qcur, "kda_q_conv", il); cb(Kcur, "kda_k_conv", il); cb(Vcur, "kda_v_conv", il); diff --git a/src/models/kimi-k31.cpp b/src/models/kimi-k31.cpp index 3f99eca4a183..049f667dea40 100644 --- a/src/models/kimi-k31.cpp +++ b/src/models/kimi-k31.cpp @@ -391,22 +391,29 @@ llama_model_kimi_k31::graph::graph(const llm_graph_params & params) : ggml_tensor * llama_model_kimi_k31::graph::build_kda_conv1d( llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs) { + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il) { const int64_t d_inner = head_dim * n_head_kda; const int64_t conv_state_size = (d_conv - 1) * d_inner; const int64_t n_embd_r_total = 3 * conv_state_size; - ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, - (d_conv - 1) * ggml_element_size(conv_state_all), - n_embd_r_total * ggml_element_size(conv_state_all), - qkv * conv_state_size * ggml_element_size(conv_state_all)); - ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x); ggml_tensor * x_3d = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs); - ggml_tensor * conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); - build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, - ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + ggml_tensor * conv_x = nullptr; + if (cparams.rs_replay) { + // the row holds the q, k and v conv histories one after the other + conv_x = build_conv_state_replay(inp_rs, conv_states_all, x_3d, d_conv - 1, d_inner, il, conv_state_all, qkv); + } else { + ggml_tensor * conv_state_x = ggml_view_3d(ctx0, conv_state_all, d_conv - 1, d_inner, n_seqs, + (d_conv - 1) * ggml_element_size(conv_state_all), + n_embd_r_total * ggml_element_size(conv_state_all), + qkv * conv_state_size * ggml_element_size(conv_state_all)); + + conv_x = ggml_concat(ctx0, conv_state_x, ggml_transpose(ctx0, x_3d), 0); + + build_conv_state_store(inp_rs, conv_states_all, conv_x, d_conv - 1, + ggml_row_size(conv_states_all->type, qkv * conv_state_size)); + } ggml_tensor * conv_weight = ggml_reshape_2d(ctx0, conv_w, d_conv, d_inner); ggml_tensor * Xcur = ggml_ssm_conv(ctx0, conv_x, conv_weight); @@ -424,11 +431,11 @@ ggml_tensor * llama_model_kimi_k31::graph::build_kda_layer( const auto * mctx_cur = inp_rs->mctx; ggml_tensor * conv_states_all = mctx_cur->get_r_l(il); - ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, hparams.n_embd_r(), n_seqs); + ggml_tensor * conv_state_all = build_rs(inp_rs, conv_states_all, conv_states_all->ne[0], n_seqs); - ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); - ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs); + ggml_tensor * Qcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 0, cur, layer.wq, layer.ssm_q_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Kcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 1, cur, layer.wk, layer.ssm_k_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); + ggml_tensor * Vcur = build_kda_conv1d(inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv, d_conv, head_dim, n_head_kda, n_seq_tokens, n_seqs, il); cb(Qcur, "kda_q_conv", il); cb(Kcur, "kda_k_conv", il); cb(Vcur, "kda_v_conv", il); diff --git a/src/models/models.h b/src/models/models.h index b12642fb9a70..3b4f04c19454 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -67,6 +67,31 @@ struct llm_build_delta_net_base : public llm_graph_context { ggml_tensor * b, ggml_tensor * s, int il); + + // rs_replay variants: replay the kept pending tokens, then keep or commit the new ones [TAG_RECURRENT_REPLAY] + // x: [channels, n_seq_tokens, n_seqs] new conv inputs; returns [n_conv + n_seq_tokens, channels, n_seqs] + // a row of conv_states_all can hold several histories [channels, n_conv + n_pend] one after the other (KDA: q, k, v): + // blk picks one, and hist_rows are the rows of the ubatch cells (build_rs) shared by the blocks, nullptr gathers them + ggml_tensor * build_conv_state_replay( + llm_graph_input_rs * inp, + ggml_tensor * conv_states_all, + ggml_tensor * x, + int64_t n_conv, + int64_t channels, + int il, + ggml_tensor * hist_rows = nullptr, + int64_t blk = 0); + + ggml_tensor * build_recurrent_attn_replay( + llm_graph_input_rs * inp, + ggml_tensor * ssm_states_all, + ggml_tensor * q, + ggml_tensor * k, + ggml_tensor * v, + ggml_tensor * g, + ggml_tensor * b, + ggml_tensor * s, + int il); }; struct llm_build_lfm_base : public llm_graph_context { @@ -2209,7 +2234,7 @@ struct llama_model_bailingmoe3 : public llama_model_base { // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used ggml_tensor * build_causal_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs); + int64_t d_conv, int64_t head_dim, int64_t n_head, int64_t n_seq_tokens, int64_t n_seqs, int il); }; struct graph_mtp : public llm_graph_context { @@ -3170,7 +3195,7 @@ struct llama_model_kimi_k3 : public llama_model_base { // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs); + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il); ggml_tensor * build_mla_layer(ggml_tensor * cur, const llama_layer & layer, llm_graph_input_attn_k * inp_attn_k, @@ -3207,7 +3232,7 @@ struct llama_model_kimi_k31 : public llama_model_base { ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, int64_t d_conv, int64_t head_dim, int64_t n_head_kda, - int64_t n_seq_tokens, int64_t n_seqs); + int64_t n_seq_tokens, int64_t n_seqs, int il); ggml_tensor * build_kda_layer(ggml_tensor * cur, const llama_layer & layer, llm_graph_input_rs * inp_rs, @@ -3294,7 +3319,7 @@ struct llama_model_glm5_next : public llama_model_base { // causal conv1d over one of Q/K/V, qkv selects which third of the conv state row is used ggml_tensor * build_kda_conv1d(llm_graph_input_rs * inp_rs, ggml_tensor * conv_states_all, ggml_tensor * conv_state_all, int64_t qkv, ggml_tensor * x, ggml_tensor * proj_w, ggml_tensor * conv_w, - int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs); + int64_t d_conv, int64_t head_dim, int64_t n_head_kda, int64_t n_seq_tokens, int64_t n_seqs, int il); ggml_tensor * build_kpool_select(ggml_tensor * cur, ggml_tensor * qr, const llama_layer & layer, const llama_memory_hybrid_idx_context * mctx_hyb, llm_graph_input_kpool * inp_kpool, int il); diff --git a/src/models/qwen4exp.cpp b/src/models/qwen4exp.cpp index 106530490fd7..f77e6f5090f8 100644 --- a/src/models/qwen4exp.cpp +++ b/src/models/qwen4exp.cpp @@ -1373,6 +1373,10 @@ ggml_tensor * llama_model_qwen4exp::graph::build_conv_state_at( int64_t state_cols, int64_t channels, int il) { + if (cparams.rs_replay) { + return build_conv_state_replay(inp, conv_states_all, x, state_cols, channels, il); + } + const int64_t n_seqs = ubatch.n_seqs; const int64_t row_total = conv_states_all->ne[0]; diff --git a/tests/llama-context/cases-rs.cpp b/tests/llama-context/cases-rs.cpp index a26322b30b27..ba4b71c7ec97 100644 --- a/tests/llama-context/cases-rs.cpp +++ b/tests/llama-context/cases-rs.cpp @@ -357,7 +357,7 @@ struct case_rollback_bound : ctx_test { const llm_arch arch = llama_arch_from_string(arch_name); // the DSV4 cache rebuilds snapshot d from the state before the ubatch, so d <= n is exact; - // the recurrent memory gets snapshots 0..n-1 from ggml_gated_delta_net, only for n <= n_rs_seq + 1 + // the recurrent memory gets snapshots 0..n-1 from ggml_ssm_scan, only for n <= n_rs_seq + 1 const bool from_ubatch_start = arch == LLM_ARCH_DEEPSEEK4 || arch == LLM_ARCH_DEEPSEEK41; const auto make_ctx = [&]() { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index a0268b638a5e..5947cc1b0d17 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -5358,7 +5358,6 @@ struct test_gated_delta_net : public test_case { const int v_repeat; const bool permuted; const bool kda; - const int64_t K; // snapshot slot count: 1 = final-only, >1 = last K states const bool correlated; const bool padded_v; const bool padded_q; @@ -5366,16 +5365,8 @@ struct test_gated_delta_net : public test_case { // lower bound of the log-gate; a mild gate keeps the state alive over the whole sequence const float g_min; - std::string op_desc(ggml_tensor * t) override { - GGML_UNUSED(t); - return "GATED_DELTA_NET"; - } - - // compare only the view returned by build_graph, not the full op output - bool run_whole_graph() override { return K > 1 && n_seq_tokens > K; } - std::string vars() override { - std::string s = VARS_TO_STR13(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, K, correlated, padded_v, padded_q, permuted_k); + std::string s = VARS_TO_STR12(type, head_count, head_size, n_seq_tokens, n_seqs, v_repeat, permuted, kda, correlated, padded_v, padded_q, permuted_k); if (g_min != -20.0f) { s += "," + VAR_TO_STR(g_min); } @@ -5384,9 +5375,9 @@ struct test_gated_delta_net : public test_case { test_gated_delta_net(ggml_type type = GGML_TYPE_F32, int64_t head_count = 4, int64_t head_size = 16, int64_t n_seq_tokens = 1, int64_t n_seqs = 1, - int v_repeat = 1, bool permuted = false, bool kda = false, int64_t K = 1, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f) + int v_repeat = 1, bool permuted = false, bool kda = false, bool correlated = false, bool padded_v = false, bool padded_q = false, bool permuted_k = false, float g_min = -20.0f) : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), - v_repeat(v_repeat), permuted(permuted), kda(kda), K(K), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {} + v_repeat(v_repeat), permuted(permuted), kda(kda), correlated(correlated), padded_v(padded_v), padded_q(padded_q), permuted_k(permuted_k), g_min(g_min) {} ggml_tensor * build_graph(ggml_context * ctx) override { ggml_tensor * q; @@ -5430,11 +5421,7 @@ struct test_gated_delta_net : public test_case { k_permuted = ggml_permute(ctx, k_permuted, 0, 2, 1, 3); k = ggml_cpy(ctx, k, k_permuted); } - ggml_tensor * out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); - if (K > 1 && n_seq_tokens > K) { - // n_tokens > K: only slot 0 is guaranteed, so keep the scores and slot 0 - out = ggml_view_2d(ctx, out, out->ne[0], out->ne[1] - (K - 1) * head_size * n_seqs, out->nb[1], 0); - } + ggml_tensor * out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false); return out; } @@ -5462,6 +5449,115 @@ struct test_gated_delta_net : public test_case { } }; +// GGML_OP_GATED_DELTA_NET with a replay of pending tokens (ggml_gated_delta_net_replay) +struct test_gated_delta_net_replay : public test_case { + const int64_t head_count; // k heads + const int64_t head_size; + const int64_t n_seq_tokens; + const int64_t n_seqs; + const int v_repeat; + const bool kda; + const int64_t n_pend; + const bool keep; + + std::string vars() override { + return VARS_TO_STR8(head_count, head_size, n_seq_tokens, n_seqs, v_repeat, kda, n_pend, keep); + } + + test_gated_delta_net_replay(int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 4, int64_t n_seqs = 1, + int v_repeat = 1, bool kda = false, int64_t n_pend = 4, bool keep = true) + : head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), + v_repeat(v_repeat), kda(kda), n_pend(n_pend), keep(keep) {} + + ggml_tensor * build_graph(ggml_context * ctx) override { + const int64_t S = head_size; + const int64_t H_k = head_count; + const int64_t H = head_count * v_repeat; + const int64_t g0 = kda ? S : 1; + + ggml_tensor * q = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs); + ggml_tensor * k = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_seq_tokens, n_seqs); + ggml_tensor * v = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_seq_tokens, n_seqs); + ggml_tensor * g = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, n_seq_tokens, n_seqs); + ggml_tensor * beta = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, 1, H, n_seq_tokens, n_seqs); + ggml_tensor * state = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, S, H, n_seqs); + // one spare token per seq in pend_k, so that its seq stride is not the dense one + ggml_tensor * pk = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H_k, n_pend + 1, n_seqs); + ggml_tensor * pv = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, S, H, n_pend, n_seqs); + ggml_tensor * pgb = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, g0, H, 2*n_pend, n_seqs); + ggml_tensor * n_rep = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs); + ggml_set_name(g, "g"); + ggml_set_name(beta, "beta"); + ggml_set_name(v, "v"); + ggml_set_name(pk, "pend_k"); + ggml_set_name(pv, "pend_v"); + ggml_set_name(pgb, "pend_gb"); + ggml_set_name(n_rep, "n_rep"); + + q = ggml_l2_norm(ctx, q, 1e-6f); + k = ggml_l2_norm(ctx, k, 1e-6f); + + ggml_tensor * pk_tok = ggml_view_4d(ctx, pk, S, H_k, n_pend, n_seqs, pk->nb[1], pk->nb[2], pk->nb[3], 0); + + return ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, pk_tok, pv, pgb, n_rep, keep); + } + + void initialize_tensors(ggml_context * ctx) override { + std::mt19937 rng(0x6d4e); + const int64_t S = head_size; + const int64_t H = head_count * v_repeat; + const int64_t g0 = kda ? S : 1; + + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != nullptr; t = ggml_get_next_tensor(ctx, t)) { + if (ggml_is_view_op(t->op)) { continue; } + if (strcmp(t->name, "g") == 0) { + init_tensor_uniform(t, -20.0f, -1e-4f); + } else if (strcmp(t->name, "beta") == 0) { + init_tensor_uniform(t, 0.0f, 1.0f); + } else if (strcmp(t->name, "v") == 0) { + init_tensor_uniform(t, -0.3f, 5.0f); + } else if (strcmp(t->name, "n_rep") == 0) { + std::vector data(n_seqs); + for (auto & x : data) { + x = std::uniform_int_distribution(0, n_pend)(rng); + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(int32_t)); + } else if (strcmp(t->name, "pend_k") == 0) { + // unit rows, as the l2 norm leaves them + std::vector data(ggml_nelements(t)); + std::uniform_real_distribution u(-1.0f, 1.0f); + for (int64_t i = 0; i < ggml_nelements(t)/S; ++i) { + float n2 = 0.0f; + for (int64_t j = 0; j < S; ++j) { data[i*S + j] = u(rng); n2 += data[i*S + j]*data[i*S + j]; } + for (int64_t j = 0; j < S; ++j) { data[i*S + j] /= sqrtf(n2); } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float)); + } else if (strcmp(t->name, "pend_v") == 0) { + init_tensor_uniform(t, -2.0f, 2.0f); + } else if (strcmp(t->name, "pend_gb") == 0) { + // the gates < 0, then the betas in [0, 1] (element 0 of each gate group) + std::vector data(ggml_nelements(t), 0.0f); + std::uniform_real_distribution u(0.0f, 1.0f); + for (int64_t s = 0; s < n_seqs; ++s) { + for (int64_t r = 0; r < 2*n_pend; ++r) { + float * row = data.data() + (s*2*n_pend + r)*g0*H; + for (int64_t h = 0; h < H; ++h) { + if (r < n_pend) { + for (int64_t j = 0; j < g0; ++j) { row[h*g0 + j] = -20.0f*u(rng) - 1e-4f; } + } else { + row[h*g0] = u(rng); + } + } + } + } + ggml_backend_tensor_set(t, data.data(), 0, data.size()*sizeof(float)); + } else { + init_tensor_uniform(t); + } + } + } +}; + // GGML_OP_GATED_DELTA_NET + GGML_OP_CPY (recurrent cache fusion) struct test_gated_delta_net_cache_fusion : public test_case { const ggml_type type; @@ -5470,25 +5566,22 @@ struct test_gated_delta_net_cache_fusion : public test_case { const int64_t head_size; const int64_t n_seq_tokens; const int64_t n_seqs; - const int64_t K; // snapshot slot count (>1) ggml_tensor * cpy_node = nullptr; std::string vars() override { - return VARS_TO_STR6(type, head_count, head_size, n_seq_tokens, n_seqs, K); + return VARS_TO_STR5(type, head_count, head_size, n_seq_tokens, n_seqs); } test_gated_delta_net_cache_fusion(ggml_type type = GGML_TYPE_F32, - int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1, - int64_t K = 2) - : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), K(K) {} + int64_t head_count = 4, int64_t head_size = 32, int64_t n_seq_tokens = 2, int64_t n_seqs = 1) + : type(type), head_count(head_count), head_size(head_size), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs) {} ggml_tensor * build_graph(ggml_context * ctx) override { const int64_t S_v = head_size; const int64_t H_v = head_count; const int64_t H_k = head_count; const int64_t D = S_v * S_v * H_v; - const int64_t n_written = std::min(n_seq_tokens, K); ggml_tensor * q = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs); ggml_tensor * k = ggml_new_tensor_4d(ctx, type, head_size, H_k, n_seq_tokens, n_seqs); @@ -5506,7 +5599,7 @@ struct test_gated_delta_net_cache_fusion : public test_case { q = ggml_l2_norm(ctx, q, 1e-6f); k = ggml_l2_norm(ctx, k, 1e-6f); - ggml_tensor * gdn_out = ggml_gated_delta_net(ctx, q, k, v, g, beta, state, K); + ggml_tensor * gdn_out = ggml_gated_delta_net_ext(ctx, q, k, v, g, beta, state, nullptr, nullptr, nullptr, nullptr, false); ggml_set_name(gdn_out, "gdn_out"); // attn scores view (first part of the gdn output) @@ -5517,21 +5610,19 @@ struct test_gated_delta_net_cache_fusion : public test_case { ggml_row_size(gdn_out->type, S_v * H_v * n_seq_tokens), 0); ggml_set_name(attn, "attn"); - // snapshot tail view [D, n_seqs, n_written] + // state tail view [D, n_seqs] const int64_t attn_score_elems = S_v * H_v * n_seq_tokens * n_seqs; - ggml_tensor * src = ggml_view_3d(ctx, gdn_out, - D, n_seqs, n_written, + ggml_tensor * src = ggml_view_2d(ctx, gdn_out, + D, n_seqs, ggml_row_size(gdn_out->type, D), - ggml_row_size(gdn_out->type, D * n_seqs), ggml_row_size(gdn_out->type, attn_score_elems)); - // recurrent cache view [D, n_seqs, n_written] - ggml_tensor * cache = ggml_new_tensor_3d(ctx, type, D, n_seqs, n_written); + // recurrent cache view [D, n_seqs] + ggml_tensor * cache = ggml_new_tensor_2d(ctx, type, D, n_seqs); ggml_set_name(cache, "cache"); - ggml_tensor * dst = ggml_view_3d(ctx, cache, - D, n_seqs, n_written, - ggml_row_size(cache->type, D), - ggml_row_size(cache->type, D * n_seqs), 0); + ggml_tensor * dst = ggml_view_2d(ctx, cache, + D, n_seqs, + ggml_row_size(cache->type, D), 0); ggml_tensor * cpy = ggml_cpy(ctx, src, dst); ggml_set_name(cpy, "gdn_cache_cpy"); @@ -10004,14 +10095,34 @@ struct test_fill : public test_case { const ggml_type type; const std::array ne; float c; + const int64_t offset; // > 0: fill in place a view that starts offset elements into its buffer - std::string vars() override { return VARS_TO_STR3(type, ne, c); } + std::string vars() override { + std::string s = VARS_TO_STR3(type, ne, c); + if (offset != 0) { + s += "," + VAR_TO_STR(offset); + } + return s; + } test_fill(float c, ggml_type type = GGML_TYPE_F32, - std::array ne = { 10, 10, 4, 3 }) - : type(type), ne(ne), c(c) {} + std::array ne = { 10, 10, 4, 3 }, int64_t offset = 0) + : type(type), ne(ne), c(c), offset(offset) {} ggml_tensor * build_graph(ggml_context * ctx) override { + if (offset != 0) { + ggml_tensor * a = ggml_new_tensor_1d(ctx, type, offset + ne[0]*ne[1]*ne[2]*ne[3]); + ggml_set_name(a, "a"); + + ggml_tensor * v = ggml_view_4d(ctx, a, ne[0], ne[1], ne[2], ne[3], + ne[0]*ggml_type_size(type), ne[0]*ne[1]*ggml_type_size(type), ne[0]*ne[1]*ne[2]*ggml_type_size(type), + offset*ggml_type_size(type)); + + ggml_tensor * out = ggml_fill_inplace(ctx, v, c); + ggml_set_name(out, "out"); + return out; + } + ggml_tensor * a = ggml_new_tensor_4d(ctx, type, ne[0], ne[1], ne[2], ne[3]); ggml_set_param(a); ggml_set_name(a, "a"); @@ -13469,6 +13580,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 207, 11, 3 })); test_cases.emplace_back(new test_fill(-152.0f, GGML_TYPE_F16, { 800, 600, 4, 4 })); test_cases.emplace_back(new test_fill(3.5f, GGML_TYPE_F16, { 2048, 512, 2, 2 })); + test_cases.emplace_back(new test_fill(0.0f, GGML_TYPE_F32, { 303, 7, 1, 1 }, 1)); + test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F32, { 96, 4, 1, 1 }, 37)); + test_cases.emplace_back(new test_fill(2.0f, GGML_TYPE_F16, { 303, 7, 1, 1 }, 3)); test_cases.emplace_back(new test_sleep(0)); test_cases.emplace_back(new test_sleep(10, GGML_TYPE_F16, { 128, 4, 2, 2 })); @@ -14006,6 +14120,19 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_moe_reduce(2048, 16, 32, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 128, 1, 1)); + for (bool keep : { true, false }) { + test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 4, 1, 1, false, 4, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 2, 3, 3, false, 4, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 4, 1, 3, false, 4, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 8, 2, 3, false, 8, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(4, 32, 1, 2, 2, false, 3, keep)); + test_cases.emplace_back(new test_gated_delta_net_replay(4, 64, 3, 2, 1, true, 4, keep)); + } + // prefill sized: the replay runs before the chunked kernels (CUDA from 64 tokens, HIP from 2048) + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 65, 1, 1, false, 4, false)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 257, 1, 3, false, 4, false)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 513, 2, 2, false, 8, false)); + test_cases.emplace_back(new test_gated_delta_net_replay(16, 128, 2048, 1, 3, false, 4, false)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, true, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 32, 16, 1, 1, 1, false, true)); @@ -14041,9 +14168,8 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 64, 1, 1, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 2, 2, true, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, false, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, 1, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, 1, true, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4, 2, 2, false, true, 4)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 65, 1, 1, false, true, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 1, 1, true, true, true, true)); // MMA-eligible GDN shapes: whole heads, value slices, tails, and the HIP prefill threshold. test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 65, 1, 1)); @@ -14064,53 +14190,43 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 512, 2, 2)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 257, 2, 2, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 129, 1, 1, false, false, false, true)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 4095, 1, 2)); // Correlated keys, high beta, and weak decay stress the chunked triangular solve. for (int64_t n_tokens : {64, 65, 257}) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, 1, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, n_tokens, 1, 1, false, false, true)); } // Odd V strides require element loads instead of aligned matrix loads. - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, 1, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 3, 128, 65, 1, 1, false, false, false, true)); // Q and K can have different strides in both scalar and chunked paths. for (int64_t n_tokens : {4, 65}) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, true)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, 1, false, false, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, true)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 2, 128, n_tokens, 2, 2, false, false, false, false, false, true)); } - // mild decay keeps the state alive across the sequence; qwen35 prefill layout with K=5 snapshots + // mild decay keeps the state alive across the sequence; qwen35 prefill layout for (int64_t n : { 5, 300, 2048 }) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, n, 1, 3, false, false, false, false, false, false, /*g_min=*/-0.05f)); } - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, /*K=*/5, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 300, 2, 2, true, false, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 200, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f)); // a backend may pick its kernel by head count: few and many heads, per head size, plain and KDA for (int64_t s : { 16, 32, 64, 128 }) { for (int64_t h : { 4 * 128 / s, 64 * 128 / s }) { - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, /*K=*/4, false, false, false, false, /*g_min=*/-0.05f)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, /*K=*/1, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, false, false, false, false, false, /*g_min=*/-0.05f)); + test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, h, s, 37, 1, 1, false, true, false, false, false, false, /*g_min=*/-0.05f)); } } - // K > 1: output keeps the last min(n_tokens, K) per-token snapshots, ordered most-recent-first - // (slot 0 = final state, slot s = state s tokens back). - // exact-match cases (K == n_seq_tokens): - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 16, 2, 1, 1, false, false, /*K=*/2)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 32, 4, 1, 1, false, false, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, false, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 128, 4, 1, 1, false, false, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 64, 4, 2, 1, false, true, /*K=*/4)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 8, 32, 4, 2, 2, false, true, /*K=*/4)); - - // gdn + cache cpy fusion (K > 1) - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1, 2)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1, 2)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1, 4)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2, 4)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1, 4)); - test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1, 4)); + // gdn + cache cpy fusion + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 2, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 64, 4, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 4, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 8, 32, 4, 2)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 128, 64, 4, 1)); + test_cases.emplace_back(new test_gated_delta_net_cache_fusion(GGML_TYPE_F32, 4, 32, 8, 1)); #if 0 // these tests are disabled to save execution time, sbut they can be handy for debugging @@ -14795,7 +14911,6 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 4, 128, 8192, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 1536, 1)); test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 20, 128, 2048, 1)); - test_cases.emplace_back(new test_gated_delta_net(GGML_TYPE_F32, 16, 128, 2048, 1, 3, false, false, 5)); // qwen35 PP-2048, K=5 // lightning_indexer for (int kv : { 256, 4096, 65536 }) { From 38b9cad71d14fa69b20393f42ebcd22ced77934e Mon Sep 17 00:00:00 2001 From: Aldehir Rojas Date: Mon, 23 Nov 2026 17:41:33 -0600 Subject: [PATCH 082/401] quantize : make local const static for MSVC (#32902) --- src/llama-quant.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index c66f060f621e..fd85c0f4031e 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -884,7 +884,7 @@ static std::unordered_map target_bpw_type( }; // Quantization types - constexpr ggml_type quant_types[] = { + static constexpr ggml_type quant_types[] = { GGML_TYPE_IQ1_S, GGML_TYPE_IQ1_M, GGML_TYPE_IQ2_XXS, @@ -908,16 +908,16 @@ static std::unordered_map target_bpw_type( GGML_TYPE_BF16, }; - constexpr double EPSILON = 1e-12; - constexpr double INFINITE = std::numeric_limits::infinity(); - constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2" - constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d; - constexpr float ffn_down_boost = 6.0f; - constexpr float output_boost = 3.0f; - constexpr float tied_embd_boost = 2.5f; - constexpr float attn_v_boost = 1.25f; - constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw - constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted + static constexpr double EPSILON = 1e-12; + static constexpr double INFINITE = std::numeric_limits::infinity(); + static constexpr uint64_t STATE_MAGIC = 0x4250572d5632; // "BPW-V2" + static constexpr uint64_t HASH_MAGIC = 0xeabada55cafed00d; + static constexpr float ffn_down_boost = 6.0f; + static constexpr float output_boost = 3.0f; + static constexpr float tied_embd_boost = 2.5f; + static constexpr float attn_v_boost = 1.25f; + static constexpr float boost_taper = 2.2f; // boost starves other tensors below 2.2 bpw + static constexpr double downward_threshold = 0.08; // potential gains smaller than 8% are not trusted const char * func = __func__; // --target-exclude must leave at least one quant type in the pool From c74c71a6f7a0b06df30f979520e5d9a86a4d60ad Mon Sep 17 00:00:00 2001 From: Max Krasnyansky Date: Mon, 23 Nov 2026 15:47:20 -0800 Subject: [PATCH 083/401] fix editor config in master (#32914) --- ggml/src/ggml.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c index 88ade6e8ae3a..c616fa39bf96 100644 --- a/ggml/src/ggml.c +++ b/ggml/src/ggml.c @@ -5545,7 +5545,7 @@ void ggml_flash_attn_ext_add_sinks( a->src[4] = sinks; } -bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { +bool ggml_flash_attn_ext_has_indexed_bias(const struct ggml_tensor * a) { return a->op == GGML_OP_FLASH_ATTN_EXT && ggml_get_op_params_i32(a, 5) != 0; } From af5c58347fdbc2cd19e65b278e81c8f528f8a175 Mon Sep 17 00:00:00 2001 From: lhez Date: Mon, 23 Nov 2026 17:12:33 -0800 Subject: [PATCH 084/401] opencl: add c8 q6_k coopk GEMM for up to n=8 spec verify (#32909) Assisted-by: Codex Co-authored-by: Hongqiang Wang --- ggml/src/ggml-opencl/CMakeLists.txt | 1 + ggml/src/ggml-opencl/ggml-opencl.cpp | 143 +++++++++++- .../gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl | 214 ++++++++++++++++++ 3 files changed, 357 insertions(+), 1 deletion(-) create mode 100644 ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index 1520f8d40e3a..6d55f5d3de5f 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -300,6 +300,7 @@ set(GGML_OPENCL_KERNELS gemm_coopk_q4_k_q8_1_dp4a gemm_coopk_q4_k_q8_1_dp4a_bin_c8 gemm_coopk_q6_k_q8_1_dp4a + gemm_coopk_q6_k_q8_1_dp4a_bin_c8 pack_b_f16_coopmat gemm_noshuffle_q4_0_f32_coopmat gemm_noshuffle_q5_0_f32_coopmat diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 54038a503ad5..ba18fde3635d 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1529,13 +1529,18 @@ struct ggml_backend_opencl_context { cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr; int nsg_coopk_dp4a_q6_k = 8; int rows_coopk_dp4a_q6_k = 4; + cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = nullptr; + cl_kernel kernel_quant_a_q8_1_k4h = nullptr; + int nsg_coopk_dp4a_q6_k_bin_c8 = 4; #endif // GGML_OPENCL_USE_ADRENO_KERNELS ~ggml_backend_opencl_context() { #ifdef GGML_OPENCL_USE_ADRENO_KERNELS for (cl_kernel kernel : { kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8, - kernel_quant_a_q8_1_k4 + kernel_quant_a_q8_1_k4, + kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8, + kernel_quant_a_q8_1_k4h } ) { if (kernel != nullptr) { @@ -1949,6 +1954,46 @@ static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backe backend_ctx->kernel_quant_a_q8_1_k4 = quant; } +static void load_cl_kernel_coopk_q6_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl"); +#endif + cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), + "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, + backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8, false); + if (program == nullptr) { + return; + } + + cl_int err; + + cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", &err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + return; + } + + cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4h", &err); + CL_CHECK(clReleaseProgram(program)); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseKernel(gemm)); + return; + } + + if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { + CL_CHECK(clReleaseKernel(gemm)); + CL_CHECK(clReleaseKernel(quant)); + return; + } + + backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = gemm; + backend_ctx->kernel_quant_a_q8_1_k4h = quant; +} + static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx, const std::string & kernel_src, const char * kernel_name, int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) { @@ -2065,6 +2110,15 @@ static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx backend_ctx->rows_coopk_dp4a_q6_k, backend_ctx->nsg_coopk_dp4a_q6_k, backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4, backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c2); + + static const bool use_coopk_bin = [] { + const char * env = getenv("GGML_OPENCL_COOPK_Q6_K_BIN"); + return !env || !*env || atoi(env) != 0; + }(); + + if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { + load_cl_kernel_coopk_q6_k_bin_c8(backend_ctx); + } GGML_LOG_CONT("."); } } @@ -29446,6 +29500,93 @@ static void ggml_cl_mul_mat_q6_K_f32_adreno_ila(ggml_backend_t backend, const gg const int N = ne1; const int K = ne00; + if (backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 != nullptr && + N >= 2 && N <= 8 && M > 0 && K > 0 && M % 4 == 0 && K % 256 == 0 && + src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && + K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && + src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && + src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && + ggml_is_contiguous(src1) && ggml_is_contiguous(dst) + ) { + const int kb = K / 32; + const size_t qa_bytes = (size_t)8 * K; + const size_t ds_bytes = (size_t)24 * kb * sizeof(cl_half); + + backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); + backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); + + if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, + backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && + ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, + backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) + ) { + const int n_blocks = N * kb; + + cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4h; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); + CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); + + size_t quant_local[] = {64}; + size_t quant_global[] = {(size_t)8 * kb}; + backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); + + int ksplit = ggml_cl_coopk_ksplit(backend_ctx, CEIL_DIV(M / 4, 64), kb); + if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) { + ksplit = 1; + } + + cl_mem out = extrad->data_device; + cl_ulong out_offset = offsetd; + + if (ksplit > 1) { + backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float)); + out = backend_ctx->prealloc_splitk_partial.buffer; + out_offset = 0; + } + + const cl_uchar mask_c0 = 0xC0; + + const size_t nsg = backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8; + cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8; + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_c0)); + CL_CHECK(clSetKernelArg(gemm, 12, sizeof(int), &ksplit)); + + size_t local[] = {64, nsg, 1}; + size_t global[] = {(size_t)CEIL_DIV(M / 4, 64) * 64, nsg * ksplit, 1}; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + + if (ksplit > 1) { + const int rows = M * N; + cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); + CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); + size_t reduce_local[] = {64}; + size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64}; + backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); + } + return; + } + } + if (ne1 == 1) { cl_mem b_sub_buf = nullptr; cl_mem b_img = nullptr; diff --git a/ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl b/ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl new file mode 100644 index 000000000000..b561c577a961 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl @@ -0,0 +1,214 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable +#ifdef cl_khr_integer_dot_product +#pragma OPENCL EXTENSION cl_khr_integer_dot_product : enable +#endif + +#ifndef COOPK_NSG +#define COOPK_NSG 4 +#endif +#define COK_SG 64 +#define COK_ROWS 4 + +#define COK_PACK4(a, b, c, e) \ + ( ((uint)(a) & 0xFFu) | (((uint)(b) & 0xFFu) << 8) \ + | (((uint)(c) & 0xFFu) << 16) | (((uint)(e) & 0xFFu) << 24) ) + +// Pack (0, 2, 1, 3) K bytes and store scales plus both 16-value sums at width eight. +kernel void kernel_quant_a_q8_1_k4h( + global const float * src, + global uint * qa, + global half * ds, + ulong offset_src, + int total_blocks, + int k_b +) { + const int blk = get_global_id(0); + if (blk >= 8 * k_b) { + return; + } + const int col = blk / k_b; + const int b = blk % k_b; + if (blk >= total_blocks) { + vstore8((uint8)(0), 0, qa + blk * 8); + ds[(3 * b) * 8 + col] = (half)0; + ds[(3 * b + 1) * 8 + col] = (half)0; + ds[(3 * b + 2) * 8 + col] = (half)0; + return; + } + src = (global const float *)((global const char *)src + offset_src); + const int base = blk * 32; + + float v[32]; + float amax = 0.0f; + #pragma unroll + for (int i = 0; i < 32; ++i) { + v[i] = src[base + i]; + amax = fmax(amax, fabs(v[i])); + } + + const float d = amax / 127.0f; + const float id = (amax > 0.0f) ? (127.0f / amax) : 0.0f; + + int q[32]; + int sum_lo = 0, sum_hi = 0; + #pragma unroll + for (int i = 0; i < 16; ++i) { + q[i] = (int)rint(v[i] * id); + sum_lo += q[i]; + } + #pragma unroll + for (int i = 16; i < 32; ++i) { + q[i] = (int)rint(v[i] * id); + sum_hi += q[i]; + } + + uint8 out; + out.s0 = COK_PACK4(q[ 0], q[ 2], q[ 1], q[ 3]); + out.s1 = COK_PACK4(q[ 4], q[ 6], q[ 5], q[ 7]); + out.s2 = COK_PACK4(q[ 8], q[10], q[ 9], q[11]); + out.s3 = COK_PACK4(q[12], q[14], q[13], q[15]); + out.s4 = COK_PACK4(q[16], q[18], q[17], q[19]); + out.s5 = COK_PACK4(q[20], q[22], q[21], q[23]); + out.s6 = COK_PACK4(q[24], q[26], q[25], q[27]); + out.s7 = COK_PACK4(q[28], q[30], q[29], q[31]); + vstore8(out, 0, qa + blk * 8); + + ds[(3 * b) * 8 + col] = (half)d; + ds[(3 * b + 1) * 8 + col] = (half)(d * (float)sum_lo); + ds[(3 * b + 2) * 8 + col] = (half)(d * (float)sum_hi); +} + +// Cast before shifting to keep all four K values on Adreno compilers. +#define COK_LO(u) (((uint)(u) | ((uint)(ushort)((u) >> 4) << 16)) & 0x0F0F0F0Fu) +#define COK_HI(h) ((((((uint)(h)) & 0x33u) * 0x110u) & 0x3030u) | (((((uint)(h)) & 0xCCu) * 0x440000u) & 0x30300000u)) + +#define COK_UNPACK(r) \ + const uint w0_##r = COK_LO(bl0.s##r) | COK_HI(bh0.s##r); \ + const uint w1_##r = COK_LO(bl1.s##r) | COK_HI(bh1.s##r); \ + const uint w2_##r = COK_LO(bl2.s##r) | COK_HI(bh2.s##r); \ + const uint w3_##r = COK_LO(bl3.s##r) | COK_HI(bh3.s##r); + +#define COK_DOT_RC(r, c) \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w0_##r, A.s0, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w1_##r, A.s1, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w2_##r, A.s2, d##r.s##c); \ + d##r.s##c = dot_acc_sat_4x8packed_ss_int(w3_##r, A.s3, d##r.s##c); + +#define COK_DOT_COL(c, t) \ + { const uint4 A = read_imageui(src1_qa, (c) * k_t + (t)); \ + COK_DOT_RC(0, c) COK_DOT_RC(1, c) COK_DOT_RC(2, c) COK_DOT_RC(3, c) } + +kernel void kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8( + global const uint * src0_ql, + global const uint * src0_qh, + global const ushort * src0_s, + global const half * src0_d, + read_only image1d_buffer_t src1_qa, + read_only image1d_buffer_t src1_ds, + global float * dst, + ulong offsetd, + int m, + int k, + int n_no_padding, + uchar mask_c0, + int ksplit +) { + dst = (global float *)((global char *)dst + offsetd); + + const int gx = get_global_id(0); + const int sg = get_local_id(1); + const int lane = get_local_id(0); + const int ks = get_group_id(1); + + const bool live = gx * COK_ROWS < m; + const int row0 = live ? gx * COK_ROWS : m - COK_ROWS; + const int num_32blk = k / 32; + const int k_t = k >> 4; + const int fence = (int)(mask_c0 >> 6) - 3; + + const int nslice = ksplit * COOPK_NSG; + const int b_beg = ks * COOPK_NSG + sg; + + float8 acc0 = (float8)(0.0f), acc1 = (float8)(0.0f); + float8 acc2 = (float8)(0.0f), acc3 = (float8)(0.0f); + + for (int bg = b_beg; bg * 8 < num_32blk; bg += nslice) { + ushort8 sr0 = vload8(0, src0_s + (row0 + 0) * num_32blk + bg * 8); + ushort8 sr1 = vload8(0, src0_s + (row0 + 1) * num_32blk + bg * 8); + ushort8 sr2 = vload8(0, src0_s + (row0 + 2) * num_32blk + bg * 8); + ushort8 sr3 = vload8(0, src0_s + (row0 + 3) * num_32blk + bg * 8); + for (int jb = 0; jb < 8; ++jb) { + const int blk = bg * 8 + jb; + const ushort4 spk = (ushort4)(sr0.s0, sr1.s0, sr2.s0, sr3.s0); + sr0 = sr0.s12345670; sr1 = sr1.s12345670; sr2 = sr2.s12345670; sr3 = sr3.s12345670; + const half4 scd = vload4(0, src0_d + row0 + (blk >> 3) * m); + const float8 da = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk))); + + for (int h = 0; h < 2; ++h) { + const int g0 = (blk << 3) + (h << 2); + const int at = (blk << 1) + h; + + const uint4 l01 = vload4(0, src0_ql + row0 + ((g0 >> 1) ) * m); + const uint4 l23 = vload4(0, src0_ql + row0 + ((g0 >> 1) + 1) * m); + const uint4 hq = vload4(0, src0_qh + row0 + (g0 >> 2) * m); + + const ushort4 bl0 = (ushort4)((ushort)l01.s0, (ushort)l01.s1, (ushort)l01.s2, (ushort)l01.s3); + const ushort4 bl1 = (ushort4)((ushort)(l01.s0 >> 16), (ushort)(l01.s1 >> 16), (ushort)(l01.s2 >> 16), (ushort)(l01.s3 >> 16)); + const ushort4 bl2 = (ushort4)((ushort)l23.s0, (ushort)l23.s1, (ushort)l23.s2, (ushort)l23.s3); + const ushort4 bl3 = (ushort4)((ushort)(l23.s0 >> 16), (ushort)(l23.s1 >> 16), (ushort)(l23.s2 >> 16), (ushort)(l23.s3 >> 16)); + const uchar4 bh0 = (uchar4)((uchar)hq.s0, (uchar)hq.s1, (uchar)hq.s2, (uchar)hq.s3); + const uchar4 bh1 = (uchar4)((uchar)(hq.s0 >> 8), (uchar)(hq.s1 >> 8), (uchar)(hq.s2 >> 8), (uchar)(hq.s3 >> 8)); + const uchar4 bh2 = (uchar4)((uchar)(hq.s0 >> 16), (uchar)(hq.s1 >> 16), (uchar)(hq.s2 >> 16), (uchar)(hq.s3 >> 16)); + const uchar4 bh3 = (uchar4)((uchar)(hq.s0 >> 24), (uchar)(hq.s1 >> 24), (uchar)(hq.s2 >> 24), (uchar)(hq.s3 >> 24)); + + COK_UNPACK(0) COK_UNPACK(1) COK_UNPACK(2) COK_UNPACK(3) + + int8 d0 = (int8)(0), d1 = (int8)(0), d2 = (int8)(0), d3 = (int8)(0); + COK_DOT_COL(0, at) COK_DOT_COL(1, at) COK_DOT_COL(2, at) COK_DOT_COL(3, at) + const int at4 = at + (d0.s0 & fence); + COK_DOT_COL(4, at4) COK_DOT_COL(5, at4) COK_DOT_COL(6, at4) COK_DOT_COL(7, at4) + + const float8 sa = convert_float8(as_half8(read_imageui(src1_ds, 3 * blk + 1 + h))); + // Apply the signed-code offset with the sum for this 16-value half. + const float8 sm = sa * -32.0f; + const float s0f = (float)(h ? as_char2(spk.s0).s1 : as_char2(spk.s0).s0) * (float)scd.s0; + const float s1f = (float)(h ? as_char2(spk.s1).s1 : as_char2(spk.s1).s0) * (float)scd.s1; + const float s2f = (float)(h ? as_char2(spk.s2).s1 : as_char2(spk.s2).s0) * (float)scd.s2; + const float s3f = (float)(h ? as_char2(spk.s3).s1 : as_char2(spk.s3).s0) * (float)scd.s3; + acc0 = mad(mad(da, convert_float8(d0), sm), s0f, acc0); + acc1 = mad(mad(da, convert_float8(d1), sm), s1f, acc1); + acc2 = mad(mad(da, convert_float8(d2), sm), s2f, acc2); + acc3 = mad(mad(da, convert_float8(d3), sm), s3f, acc3); + } + } + } + + local float8 reduceLM[COK_SG * (COOPK_NSG - 1)]; + float8 out0 = (float8)(0.0f), out1 = (float8)(0.0f); + float8 out2 = (float8)(0.0f), out3 = (float8)(0.0f); +#define COK_REDUCE(accv, outv) \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg > 0) { reduceLM[(sg - 1) * COK_SG + lane] = (accv); } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + if (sg == 0) { \ + float8 sum = (accv); \ + for (int s = 0; s < COOPK_NSG - 1; s++) { sum += reduceLM[s * COK_SG + lane]; } \ + (outv) = sum; \ + } + COK_REDUCE(acc0, out0) + COK_REDUCE(acc1, out1) + COK_REDUCE(acc2, out2) + COK_REDUCE(acc3, out3) +#undef COK_REDUCE + +#define COK_STORE_COL(c) \ + if ((c) < n_no_padding) { \ + vstore4((float4)(out0.s##c, out1.s##c, out2.s##c, out3.s##c), 0, dst + (c) * m + row0); \ + } + if (sg == 0 && live) { + dst += (size_t)ks * (size_t)m * (size_t)n_no_padding; + COK_STORE_COL(0) COK_STORE_COL(1) COK_STORE_COL(2) COK_STORE_COL(3) + COK_STORE_COL(4) COK_STORE_COL(5) COK_STORE_COL(6) COK_STORE_COL(7) + } +#undef COK_STORE_COL +} From 12d47ba2f462439240329b4e34a5e173e3267d66 Mon Sep 17 00:00:00 2001 From: lhez Date: Mon, 23 Nov 2026 21:14:37 -0800 Subject: [PATCH 085/401] opencl: fix GDN QK offsets (#32747) Assisted-by: Codex --- ggml/src/ggml-opencl/ggml-opencl.cpp | 6 ++++++ ggml/src/ggml-opencl/kernels/gated_delta_net.cl | 4 +++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index ba18fde3635d..700d214c3c8a 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -40664,6 +40664,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { const cl_uint sq1 = (cl_uint)(src_q->nb[1] / sizeof(float)); const cl_uint sq2 = (cl_uint)(src_q->nb[2] / sizeof(float)); const cl_uint sq3 = (cl_uint)(src_q->nb[3] / sizeof(float)); + const cl_uint sk1 = (cl_uint)(src_k->nb[1] / sizeof(float)); + const cl_uint sk2 = (cl_uint)(src_k->nb[2] / sizeof(float)); + const cl_uint sk3 = (cl_uint)(src_k->nb[3] / sizeof(float)); const cl_uint sv1 = (cl_uint)(src_v->nb[1] / sizeof(float)); const cl_uint sv2 = (cl_uint)(src_v->nb[2] / sizeof(float)); const cl_uint sv3 = (cl_uint)(src_v->nb[3] / sizeof(float)); @@ -40714,6 +40717,9 @@ static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq1)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq2)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk3)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv1)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv2)); CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv3)); diff --git a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl index 78b807cfdbba..b254703e481f 100644 --- a/ggml/src/ggml-opencl/kernels/gated_delta_net.cl +++ b/ggml/src/ggml-opencl/kernels/gated_delta_net.cl @@ -95,6 +95,7 @@ kernel void kernel_gated_delta_net( uint n_seqs, uint s_off, uint sq1, uint sq2, uint sq3, + uint sk1, uint sk2, uint sk3, uint sv1, uint sv2, uint sv3, uint sb1, uint sb2, uint sb3, uint H_k, @@ -136,6 +137,7 @@ kernel void kernel_gated_delta_net( // input state holds s0 only [S_v, S_v, H, n_seqs]: per-seq stride is H*D. const uint state_base = (seq_id * H_v + head_id) * state_size; const uint q_off_base = iq3 * sq3 + iq1 * sq1; + const uint k_off_base = iq3 * sk3 + iq1 * sk1; const uint v_off_base = seq_id * sv3 + head_id * sv1; const uint gb_off_base = seq_id * sb3 + head_id * sb1; const uint state_out_base = (seq_id * H_v + head_id) * state_size; @@ -231,7 +233,7 @@ kernel void kernel_gated_delta_net( for (uint t = 0; t < n_tokens; t++) { const uint q_off = q_off_base + t * sq2; - const uint k_off = q_off; + const uint k_off = k_off_base + t * sk2; const uint v_off = v_off_base + t * sv2; const uint gb_off = gb_off_base + t * sb2; const float beta_val = data_beta[gb_off]; From d141011c25781519123be51019441cd710260cb2 Mon Sep 17 00:00:00 2001 From: losewayy Date: Tue, 24 Nov 2026 15:25:31 +0800 Subject: [PATCH 086/401] vulkan: support state size 96 in ssm_scan (#32162) * vulkan: support state size 96 in ssm_scan Assisted-by: Claude Code * vulkan: specialize ssm_scan state size Assisted-by: Codex * vulkan: clarify ssm_scan constant names Assisted-by: Codex --- ggml/src/ggml-vulkan/ggml-vulkan-types.h | 1 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 21 ++++++++++------ .../ggml-vulkan/vulkan-shaders/ssm_scan.comp | 25 ++++++++++++------- tests/test-backend-ops.cpp | 2 ++ 4 files changed, 32 insertions(+), 17 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index f200b43d30f5..a121436e6b08 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -1018,6 +1018,7 @@ struct vk_device_struct { vk_pipeline pipeline_gated_delta_net_cm; vk_pipeline pipeline_gated_delta_net_cm_v32; vk_pipeline pipeline_gated_delta_net_cm_v128; + vk_pipeline pipeline_ssm_scan_f32_d96; vk_pipeline pipeline_ssm_scan_f32_d128; vk_pipeline pipeline_ssm_scan_f32_d256; vk_pipeline pipeline_ssm_conv_f32; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 88e595f4a8e9..74486b8500ba 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4273,12 +4273,15 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { GGML_UNUSED(gdn_shmem); } + // Pad 96 states to a 128-thread workgroup for 32- and 64-lane subgroups. if (device->subgroup_arithmetic && device->subgroup_require_full_support) { - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size}, 1, true, true); - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_subgroup_f32_len, ssm_scan_subgroup_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true); } else { - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 16}, 1, true, true); - ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 16}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d96, "ssm_scan_96_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 96}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d128, "ssm_scan_128_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {128, device->subgroup_size, 128}, 1, true, true); + ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true); } ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1); @@ -10253,7 +10256,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const case GGML_OP_SSM_SCAN: if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { const uint32_t d_state = src0->ne[0]; - if (d_state == 128) { + if (d_state == 96) { + return ctx->device->pipeline_ssm_scan_f32_d96; + } else if (d_state == 128) { return ctx->device->pipeline_ssm_scan_f32_d128; } else if (d_state == 256) { return ctx->device->pipeline_ssm_scan_f32_d256; @@ -11523,7 +11528,7 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te std::array elements; const uint32_t d_state = src0->ne[0]; - uint32_t num_subgroups = d_state / ctx->device->subgroup_size; + uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size; const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups); const uint32_t num_workgroups_y = n_seq; elements = { num_workgroups_x, num_workgroups_y, 1 }; @@ -17273,11 +17278,11 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm return false; } - if ((d_state != 128 && d_state != 256) || head_dim % 16 != 0) { + if ((d_state != 96 && d_state != 128 && d_state != 256) || head_dim % 16 != 0) { return false; } - size_t shmem_size = d_state * sizeof(float); + size_t shmem_size = (d_state == 96 ? 128 : d_state) * sizeof(float); if (shmem_size > device->properties.limits.maxComputeSharedMemorySize) { return false; diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp index 4fecb3aa5ace..ec9b9e60abf0 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp @@ -8,10 +8,11 @@ #include "types.glsl" -layout(constant_id = 0) const uint D_STATE = 128; +layout(constant_id = 0) const uint BLOCK_SIZE = 128; layout(constant_id = 1) const uint SUBGROUP_SIZE = 32; +layout(constant_id = 2) const uint D_STATE = 128; -const uint32_t c_factor = D_STATE / SUBGROUP_SIZE; +const uint32_t c_factor = (D_STATE + SUBGROUP_SIZE - 1) / SUBGROUP_SIZE; layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in; @@ -46,14 +47,14 @@ float softplus(float x) { } #if !USE_SUBGROUP_ADD -shared float temp[D_STATE]; +shared float temp[BLOCK_SIZE]; #endif void main() { const uint subgroup = gl_SubgroupID; const uint lane = gl_SubgroupInvocationID; const uint tid = gl_SubgroupID * SUBGROUP_SIZE + lane; - const uint subgroup_idx = gl_WorkGroupID.x * c_factor + subgroup; + const uint subgroup_idx = gl_WorkGroupID.x * (BLOCK_SIZE / SUBGROUP_SIZE) + subgroup; const uint head_idx = subgroup_idx / d_head; const uint head_off = (subgroup_idx % d_head) * 4; @@ -78,7 +79,8 @@ void main() { float state[c_factor]; [[unroll]] for (uint j = 0; j < c_factor; j++) { - state[j] = s0[s0_base_idx + SUBGROUP_SIZE * j + lane]; + const uint state_idx = SUBGROUP_SIZE * j + lane; + state[j] = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? s0[s0_base_idx + state_idx] : 0.0f; } float a = A[A_base_idx]; @@ -91,8 +93,9 @@ void main() { const float dA = exp(dt_soft_plus * a); const float x_dt = x[x_base_idx + i * stride_x] * dt_soft_plus; [[unroll]] for (uint j = 0; j < c_factor; j++) { - float B_val = B[B_base_idx + i * stride_B + SUBGROUP_SIZE * j + lane]; - float C_val = C[C_base_idx + i * stride_C + SUBGROUP_SIZE * j + lane]; + const uint state_idx = SUBGROUP_SIZE * j + lane; + float B_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? B[B_base_idx + i * stride_B + state_idx] : 0.0f; + float C_val = D_STATE % SUBGROUP_SIZE == 0 || state_idx < D_STATE ? C[C_base_idx + i * stride_C + state_idx] : 0.0f; state[j] = (state[j] * dA) + (B_val * x_dt); state_sum += state[j] * C_val; } @@ -121,7 +124,9 @@ void main() { if (slot > 0u && slot < K) { const uint snapshot_base_idx = s_base_idx + slot * n_seq * (nb03 / 4u); [[unroll]] for (uint j = 0; j < c_factor; j++) { - d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) { + d[snapshot_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + } } } } @@ -129,6 +134,8 @@ void main() { // write back the state [[unroll]] for (int j = 0; j < c_factor; j++) { - d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + if (D_STATE % SUBGROUP_SIZE == 0 || SUBGROUP_SIZE * j + lane < D_STATE) { + d[s_base_idx + SUBGROUP_SIZE * j + lane] = state[j]; + } } } diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 5947cc1b0d17..dc9e4a1ae69d 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -14854,6 +14854,8 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_ssm_conv(GGML_TYPE_F32, {4, 3328, 1, 1}, {4, 3328, 1, 1})); // generate test_cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, {515, 3328, 1, 1}, {4, 3328, 1, 1}, true)); // prefill test_cases.emplace_back(new test_ssm_conv_bias_silu(GGML_TYPE_F32, {4, 3328, 1, 1}, {4, 3328, 1, 1}, true)); // generate + test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 128, 8, 512, 1)); // Nemotron-3-Puzzle prefill + test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 128, 8, 1, 1)); // Nemotron-3-Puzzle generate test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 48, 1, 512, 1)); // prefill test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 48, 1, 1, 1)); // generate test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 512, 1)); // Nemotron-9B prefill From b12f22d2f27412db16f8746280cf65f33bc1a0dd Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Tue, 24 Nov 2026 09:30:43 +0200 Subject: [PATCH 087/401] ggml : use a range-reduced log1p for softplus (#32655) * metal : use a range-reduced log1p for softplus Use the atanh series for x in [-0.5, 1] and precise::log(1 + x) otherwise. This avoids the cancellation in log(1 + exp(x)) for negative inputs and does not rely on fast-math folding of (1 + e) - 1. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * tests : add a softplus test for negative inputs Use inputs in [-16.6, -16.0], where log(1 + exp(x)) has up to ~2x relative error. This catches both the old form and the fast-math-folded compensated form. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * ggml : use log1pf in ggml_compute_softplus_f32 Use log1pf(expf(input)) so the host helper keeps the true value for x < -16.64. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) Co-authored-by: IsNot-10 <209144869@qq.com> * vulkan : use a range-reduced log1p for softplus Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) Co-authored-by: IsNot-10 <209144869@qq.com> * opencl : use a range-reduced log1p for softplus Use the atanh series for x in [-0.5, 1] and log(1 + x) otherwise. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) Co-authored-by: IsNot-10 <209144869@qq.com> * vulkan : move log1p to utils.glsl Move the range-reduced log1p out of unary.comp into utils.glsl so that other ops such as topk_moe and ssm_scan can include it. The body is unchanged; only the call site in op_softplus is renamed. Co-authored-by: IsNot-10 <209144869@qq.com> Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (MacBook, M5 Max, 128GB) --------- Co-authored-by: IsNot-10 <209144869@qq.com> --- ggml/src/ggml-impl.h | 2 +- ggml/src/ggml-metal/kernels/unary.metal | 21 +++++++- ggml/src/ggml-opencl/kernels/softplus.cl | 52 ++++++++++++++++--- .../src/ggml-vulkan/vulkan-shaders/unary.comp | 3 +- .../src/ggml-vulkan/vulkan-shaders/utils.glsl | 20 +++++++ tests/test-backend-ops.cpp | 16 +++++- 6 files changed, 104 insertions(+), 10 deletions(-) diff --git a/ggml/src/ggml-impl.h b/ggml/src/ggml-impl.h index 7df7e1efd589..095ff643328c 100644 --- a/ggml/src/ggml-impl.h +++ b/ggml/src/ggml-impl.h @@ -105,7 +105,7 @@ static inline bool ggml_impl_is_view(const struct ggml_tensor * t) { } static inline float ggml_compute_softplus_f32(float input) { - return (input > 20.0f) ? input : logf(1 + expf(input)); + return (input > 20.0f) ? input : log1pf(expf(input)); } // compute correction dims for YaRN RoPE scaling diff --git a/ggml/src/ggml-metal/kernels/unary.metal b/ggml/src/ggml-metal/kernels/unary.metal index b361da996ffa..c8a441609848 100644 --- a/ggml/src/ggml-metal/kernels/unary.metal +++ b/ggml/src/ggml-metal/kernels/unary.metal @@ -21,6 +21,25 @@ inline bfloat4 ggml_metal_unary_cast(float x) { } #endif +template +inline T ggml_metal_log1p(T x) { + const T y = x / (T(2.0f) + x); + const T y2 = y * y; + T p = T(1.0f / 13.0f); + p = p * y2 + T(1.0f / 11.0f); + p = p * y2 + T(1.0f / 9.0f); + p = p * y2 + T(1.0f / 7.0f); + p = p * y2 + T(1.0f / 5.0f); + p = p * y2 + T(1.0f / 3.0f); + p = p * y2 + T(1.0f); + const T s = T(2.0f) * y * p; + const T l = precise::log(T(1.0f) + x); + const auto in_series = (x >= T(-0.5f)) & (x <= T(1.0f)); + const auto tiny = fabs(x) < T(2.5e-38f); + const T r = select(l, s, in_series); + return select(r, x, tiny); +} + template kernel void kernel_unary_impl( constant ggml_metal_kargs_unary & args, @@ -166,7 +185,7 @@ kernel void kernel_unary_impl( } if (FC_OP == OP_UNARY_NUM_SOFTPLUS) { - dst_ptr[i0] = ggml_metal_unary_cast(select(log(1 + exp(x)), x, x > 20)); + dst_ptr[i0] = ggml_metal_unary_cast(select(ggml_metal_log1p(precise::exp(x)), x, x > TC(20.0f))); } if (FC_OP == OP_UNARY_NUM_EXPM1) { diff --git a/ggml/src/ggml-opencl/kernels/softplus.cl b/ggml/src/ggml-opencl/kernels/softplus.cl index 6f8b7474165f..8c59c0ae48a7 100644 --- a/ggml/src/ggml-opencl/kernels/softplus.cl +++ b/ggml/src/ggml-opencl/kernels/softplus.cl @@ -4,6 +4,46 @@ // softplus //------------------------------------------------------------------------------ +inline float op_log1p(float x) { + const float y = x / (2.0f + x); + const float y2 = y * y; + float p = 1.0f / 13.0f; + p = p * y2 + 1.0f / 11.0f; + p = p * y2 + 1.0f / 9.0f; + p = p * y2 + 1.0f / 7.0f; + p = p * y2 + 1.0f / 5.0f; + p = p * y2 + 1.0f / 3.0f; + p = p * y2 + 1.0f; + const float s = 2.0f * y * p; + const float l = log(1.0f + x); + const float r = select(l, s, (x >= -0.5f) & (x <= 1.0f)); + return select(r, x, fabs(x) < 2.5e-38f); +} + +inline float4 op_log1p4(float4 x) { + const float4 y = x / ((float4)(2.0f) + x); + const float4 y2 = y * y; + float4 p = (float4)(1.0f / 13.0f); + p = p * y2 + (float4)(1.0f / 11.0f); + p = p * y2 + (float4)(1.0f / 9.0f); + p = p * y2 + (float4)(1.0f / 7.0f); + p = p * y2 + (float4)(1.0f / 5.0f); + p = p * y2 + (float4)(1.0f / 3.0f); + p = p * y2 + (float4)(1.0f); + const float4 s = (float4)(2.0f) * y * p; + const float4 l = log((float4)(1.0f) + x); + const float4 r = select(l, s, (x >= (float4)(-0.5f)) & (x <= (float4)(1.0f))); + return select(r, x, fabs(x) < (float4)(2.5e-38f)); +} + +inline float softplus_f32(float x) { + return select(op_log1p(exp(x)), x, x > 20.0f); +} + +inline float4 softplus_f32_4(float4 x) { + return select(op_log1p4(exp(x)), x, x > (float4)(20.0f)); +} + kernel void kernel_softplus_f32( global const float * src0, ulong offset0, @@ -13,7 +53,7 @@ kernel void kernel_softplus_f32( src0 = (global float*)((global char*)src0 + offset0); dst = (global float*)((global char*)dst + offsetd); - dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)])); + dst[get_global_id(0)] = softplus_f32(src0[get_global_id(0)]); } kernel void kernel_softplus_f32_4( @@ -25,7 +65,7 @@ kernel void kernel_softplus_f32_4( src0 = (global float4*)((global char*)src0 + offset0); dst = (global float4*)((global char*)dst + offsetd); - dst[get_global_id(0)] = (src0[get_global_id(0)] > 20.0f) ? src0[get_global_id(0)] : log(1.0f + exp(src0[get_global_id(0)])); + dst[get_global_id(0)] = softplus_f32_4(src0[get_global_id(0)]); } kernel void kernel_softplus_f16( @@ -38,7 +78,7 @@ kernel void kernel_softplus_f16( dst = (global half*)((global char*)dst + offsetd); const float x = convert_float(src0[get_global_id(0)]); - dst[get_global_id(0)] = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x))); + dst[get_global_id(0)] = convert_half_rte(softplus_f32(x)); } kernel void kernel_softplus_f16_4( @@ -51,7 +91,7 @@ kernel void kernel_softplus_f16_4( dst = (global half4*)((global char*)dst + offsetd); const float4 x = convert_float4(src0[get_global_id(0)]); - dst[get_global_id(0)] = convert_half4_rte((x > 20.0f) ? x : log(1.0f + exp(x))); + dst[get_global_id(0)] = convert_half4_rte(softplus_f32_4(x)); } kernel void kernel_softplus_f32_nc( @@ -80,7 +120,7 @@ kernel void kernel_softplus_f32_nc( global const float * x = (global const float *)(src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); global float * y = (global float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); - *y = (*x > 20.0f) ? *x : log(1.0f + exp(*x)); + *y = softplus_f32(*x); } } @@ -111,6 +151,6 @@ kernel void kernel_softplus_f16_nc( global half * hy = (global half *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); const float x = convert_float(*hx); - *hy = convert_half_rte((x > 20.0f) ? x : log(1.0f + exp(x))); + *hy = convert_half_rte(softplus_f32(x)); } } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp b/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp index 04a3756bd7d1..756c70b1d1e4 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/unary.comp @@ -1,6 +1,7 @@ #version 450 #include "types.glsl" +#include "utils.glsl" #if defined(UNARY_MUL_FUSION) #include "generic_binary_head.glsl" #else @@ -116,7 +117,7 @@ float op_expm1(float x) { } float op_softplus(float x) { - return (x > 20.0f) ? x : log(1.0f + exp(x)); + return (x > 20.0f) ? x : log1p(exp(x)); } float op_gelu_erf(float a) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl index 8aac64d75932..1f3b74783e63 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/utils.glsl @@ -25,6 +25,26 @@ uint fastdiv_small(uint a, uint b) { return (a < b) ? 0 : (a / b); } +// log(1 + x); the atanh series 2*y*(1 + y^2/3 + ... + y^12/13), y = x/(2+x), +// keeps the precision that log(1 + x) loses for x in [-0.5, 1]. +float log1p(float x) { + float y = x / (2.0f + x); + float y2 = y * y; + float p = 1.0f / 13.0f; + p = p * y2 + 1.0f / 11.0f; + p = p * y2 + 1.0f / 9.0f; + p = p * y2 + 1.0f / 7.0f; + p = p * y2 + 1.0f / 5.0f; + p = p * y2 + 1.0f / 3.0f; + p = p * y2 + 1.0f; + float s = 2.0f * y * p; + float l = log(1.0f + x); + bool in_series = (x >= -0.5f) && (x <= 1.0f); + bool tiny = abs(x) < 2.5e-38f; + float r = in_series ? s : l; + return tiny ? x : r; +} + void get_indices(uint idx, out uint i00, out uint i01, out uint i02, out uint i03, uint ne00, uint ne01, uint ne02, uint ne03) { i03 = fastdiv_small(idx, (ne02*ne01*ne00)); const uint i03_offset = i03 * ne02*ne01*ne00; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index dc9e4a1ae69d..2d50c607cab3 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -2258,6 +2258,20 @@ struct test_unary : public test_case { }; +struct test_unary_softplus_neg : public test_unary { + test_unary_softplus_neg() : test_unary(GGML_UNARY_OP_SOFTPLUS) {} + + std::string vars() override { + return test_unary::vars() + ",neg"; + } + + void initialize_tensors(ggml_context * ctx) override { + for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) { + init_tensor_uniform(t, -16.6f, -16.0f); + } + } +}; + // GGML_OP_GLU struct test_glu : public test_case { const ggml_glu_op op; @@ -11130,7 +11144,7 @@ static std::vector> make_test_cases_eval() { std::default_random_engine rng(0); // unary ops - // TODO: add GGML_UNARY_OP_SOFTPLUS test that is sensitive to using `log1p(exp(x))` vs `log(exp(x) + 1)` + test_cases.emplace_back(new test_unary_softplus_neg()); for (ggml_type type : {GGML_TYPE_F16, GGML_TYPE_F32, GGML_TYPE_BF16}) { for (int v : {0, 1}) { for (int op = 0; op < GGML_UNARY_OP_COUNT; op++) { From 4af4bb6d8ad83ec0b3ef84a3bc477ccfe179b4ff Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 15:43:50 +0800 Subject: [PATCH 088/401] rpc : reuse one context for request tensors on the server (#32896) --- ggml/src/ggml-rpc/ggml-rpc.cpp | 133 +++++++++------------------------ 1 file changed, 35 insertions(+), 98 deletions(-) diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index 6197f01c285e..1814002ce4c6 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -1561,6 +1561,13 @@ class rpc_server { : backends(std::move(all_backends)), cache_dir(cache_dir) { stored_graphs.resize(backends.size()); comm_states.resize(backends.size()); + ggml_init_params params { + /*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC), + /*.mem_buffer =*/ NULL, + /*.no_alloc =*/ true, + }; + req_ctx.reset(ggml_init(params)); + GGML_ASSERT(req_ctx != nullptr); } ~rpc_server(); @@ -1593,6 +1600,16 @@ class rpc_server { }; private: + // empty context for the tensors of one request, valid until the next call + ggml_context * request_ctx() { + ggml_reset(req_ctx.get()); + return req_ctx.get(); + } + // nullptr if the buffer was not allocated by this server + ggml_backend_buffer_t find_buffer(uint64_t remote_ptr) const { + ggml_backend_buffer_t buffer = reinterpret_cast(remote_ptr); + return buffers.find(buffer) != buffers.end() ? buffer : nullptr; + } void sync_all_backends(); void comm_free_device(uint32_t dev_id); static bool comm_allreduce_pairwise(void * comm_ctx_v, ggml_tensor ** tensors); @@ -1631,6 +1648,7 @@ class rpc_server { std::vector comm_states; // SET_TENSOR data is received in chunks through this buffer std::vector set_tensor_buf; + ggml_context_ptr req_ctx; }; void rpc_server::hello(rpc_msg_hello_rsp & response) { @@ -1647,15 +1665,7 @@ bool rpc_server::get_alloc_size(const rpc_msg_get_alloc_size_req & request, rpc_ return false; } ggml_backend_buffer_type_t buft; - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead()*(1 + GGML_MAX_SRC), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); + ggml_context * ctx = request_ctx(); ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); if (tensor == nullptr) { @@ -1733,8 +1743,8 @@ bool rpc_server::get_max_size(const rpc_msg_get_max_size_req & request, rpc_msg_ bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rpc_msg_buffer_get_base_rsp & response) { LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr); - ggml_backend_buffer_t buffer = reinterpret_cast(request.remote_ptr); - if (buffers.find(buffer) == buffers.end()) { + ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr); + if (buffer == nullptr) { LOG_ERROR("[%s] buffer not found\n", __func__); return false; } @@ -1746,8 +1756,8 @@ bool rpc_server::buffer_get_base(const rpc_msg_buffer_get_base_req & request, rp bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) { sync_all_backends(); LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 "\n", __func__, request.remote_ptr); - ggml_backend_buffer_t buffer = reinterpret_cast(request.remote_ptr); - if (buffers.find(buffer) == buffers.end()) { + ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr); + if (buffer == nullptr) { LOG_ERROR("[%s] buffer not found\n", __func__); return false; } @@ -1767,8 +1777,8 @@ bool rpc_server::free_buffer(const rpc_msg_free_buffer_req & request) { bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) { sync_all_backends(); LOG_DBG2("[%s] remote_ptr: 0x%" PRIx64 ", value: %u\n", __func__, request.remote_ptr, request.value); - ggml_backend_buffer_t buffer = reinterpret_cast(request.remote_ptr); - if (buffers.find(buffer) == buffers.end()) { + ggml_backend_buffer_t buffer = find_buffer(request.remote_ptr); + if (buffer == nullptr) { LOG_ERROR("[%s] buffer not found\n", __func__); return false; } @@ -1778,15 +1788,7 @@ bool rpc_server::buffer_clear(const rpc_msg_buffer_clear_req & request) { bool rpc_server::memset_tensor(const rpc_msg_memset_tensor_req & request) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } @@ -1830,10 +1832,7 @@ ggml_tensor * rpc_server::deserialize_tensor(struct ggml_context * ctx, const rp return nullptr; } - ggml_backend_buffer_t buffer = reinterpret_cast(tensor->buffer); - if (buffer && buffers.find(buffer) == buffers.end()) { - buffer = nullptr; - } + ggml_backend_buffer_t buffer = find_buffer(tensor->buffer); if (buffer && nbytes > 0 && !rpc_in_buffer(buffer, tensor->data, nbytes)) { LOG_ERROR("[%s] tensor '%.*s' (op %s, type %s) data 0x%" PRIx64 " with size %" PRIu64 " out of buffer bounds " "(base %p, size %zu)\n", __func__, (int) sizeof(tensor->name), tensor->name, ggml_op_name((ggml_op) tensor->op), @@ -1868,15 +1867,7 @@ bool rpc_server::set_tensor(socket_ptr sock, uint64_t input_size) { const uint64_t offset = request.offset; const size_t size = input_size - sizeof(request); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, offset, size)) { return false; } @@ -1927,15 +1918,7 @@ bool rpc_server::set_tensor_2d(const std::vector & input) { return false; } - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } @@ -1975,15 +1958,7 @@ bool rpc_server::get_cached_file(uint64_t hash, std::vector & data) { bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rpc_msg_set_tensor_hash_rsp & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, 0)) { return false; } @@ -2010,15 +1985,7 @@ bool rpc_server::set_tensor_hash(const rpc_msg_set_tensor_hash_req & request, rp bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (tensor == nullptr) { LOG_ERROR("Null tensor pointer passed to server init_tensor function.\n"); return false; @@ -2047,15 +2014,7 @@ bool rpc_server::init_tensor(const rpc_msg_init_tensor_req & request) { bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size)) { return false; } @@ -2070,15 +2029,7 @@ bool rpc_server::get_tensor(const rpc_msg_get_tensor_req & request, std::vector< bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vector & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); - ggml_tensor * tensor = deserialize_tensor(ctx, &request.tensor); + ggml_tensor * tensor = deserialize_tensor(request_ctx(), &request.tensor); if (!rpc_check_region(__func__, tensor, request.offset, request.size, request.n_copies, request.stride)) { return false; } @@ -2093,14 +2044,7 @@ bool rpc_server::get_tensor_2d(const rpc_msg_tensor_2d_req & request, std::vecto bool rpc_server::copy_tensor(const rpc_msg_copy_tensor_req & request, rpc_msg_copy_tensor_rsp & response) { sync_all_backends(); - struct ggml_init_params params { - /*.mem_size =*/ 2*ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_context * ctx = ctx_ptr.get(); + ggml_context * ctx = request_ctx(); ggml_tensor * src = deserialize_tensor(ctx, &request.src); ggml_tensor * dst = deserialize_tensor(ctx, &request.dst); @@ -2559,14 +2503,7 @@ bool rpc_server::comm_allreduce(const rpc_msg_comm_allreduce_req & request) { return false; } - struct ggml_init_params params = { - /*.mem_size =*/ ggml_tensor_overhead(), - /*.mem_buffer =*/ NULL, - /*.no_alloc =*/ true, - }; - ggml_context_ptr ctx_ptr { ggml_init(params) }; - GGML_ASSERT(ctx_ptr != nullptr); - ggml_tensor * t_dst = deserialize_tensor(ctx_ptr.get(), &request.tensor); + ggml_tensor * t_dst = deserialize_tensor(request_ctx(), &request.tensor); if (t_dst == nullptr || t_dst->buffer == nullptr) { LOG_ERROR("[%s] error deserializing tensor\n", __func__); return false; From 3fccd98e9dba9f19b2f5bf3818e06c3262adcf3e Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 09:25:04 +0100 Subject: [PATCH 089/401] ui: let the chat form's model selection decide the submit state (#32920) When the last assistant message came from a model that is no longer available, the submit button stayed red and disabled even after an available model was picked in the form, since availability checked the conversation's model first. The form's selection now decides it; the conversation's model only counts when nothing is selected. Assisted-by: Claude (Opus 5.5 Medium) --- .../lib/hooks/use-chat-form-model.svelte.ts | 26 +++--- ui/apps/chat/src/lib/utils/model-selection.ts | 43 ++++++++++ ...hat-form-model-availability.svelte.test.ts | 84 +++++++++++++++++++ .../tests/unit/chat-form-model-state.test.ts | 70 ++++++++++++++++ 4 files changed, 208 insertions(+), 15 deletions(-) create mode 100644 ui/apps/chat/src/lib/utils/model-selection.ts create mode 100644 ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts create mode 100644 ui/apps/chat/tests/unit/chat-form-model-state.test.ts diff --git a/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts b/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts index d9f81b6adef3..a2b559ac7c0a 100644 --- a/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts +++ b/ui/apps/chat/src/lib/hooks/use-chat-form-model.svelte.ts @@ -11,6 +11,7 @@ import { conversationsStore, modelsStore, serverStore } from '#lib/stores/index.ts'; import type { DatabaseMessage } from '#lib/types/database.js'; import { getConversationModel } from '#lib/utils/index.ts'; +import { getChatFormModelState } from '#lib/utils/model-selection.ts'; export function useChatFormModel() { const isRouter = $derived(serverStore.isRouterMode); @@ -82,22 +83,17 @@ export function useChatFormModel() { return activeModelId ? modelsStore.props.modelSupportsVision(activeModelId) : false; }); - const hasModelSelected = $derived( - !isRouter || !!conversationModel || !!modelsStore.selectedModelId + // the form's selection decides the state; the conversation's model only counts when nothing is selected + const modelState = $derived( + getChatFormModelState({ + conversationModel, + isRouter, + models: modelsStore.models, + selectedModelId: modelsStore.selectedModelId + }) ); - const isSelectedModelInCache = $derived.by(() => { - if (!isRouter) return true; - - if (conversationModel) { - return modelsStore.models.some((option) => option.model === conversationModel); - } - - const currentModelId = modelsStore.selectedModelId; - - if (!currentModelId) return false; - - return modelsStore.models.some((option) => option.id === currentModelId); - }); + const hasModelSelected = $derived(modelState.hasModelSelected); + const isSelectedModelInCache = $derived(modelState.isSelectedModelAvailable); return { get conversationModel() { diff --git a/ui/apps/chat/src/lib/utils/model-selection.ts b/ui/apps/chat/src/lib/utils/model-selection.ts new file mode 100644 index 000000000000..948c7efef713 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/model-selection.ts @@ -0,0 +1,43 @@ +import type { ModelOption } from '#lib/types/models.js'; + +export interface ChatFormModelStateInput { + conversationModel: string | null; + isRouter: boolean; + models: readonly Pick[]; + selectedModelId: string | null; +} + +export interface ChatFormModelState { + hasModelSelected: boolean; + isSelectedModelAvailable: boolean; +} + +/** + * Whether the chat form has a model to send with and whether that model is available. + * The form's own selection always wins; the conversation's last model only counts + * when nothing is selected in the form. + */ +export function getChatFormModelState({ + conversationModel, + isRouter, + models, + selectedModelId +}: ChatFormModelStateInput): ChatFormModelState { + if (!isRouter) return { hasModelSelected: true, isSelectedModelAvailable: true }; + + if (selectedModelId) { + return { + hasModelSelected: true, + isSelectedModelAvailable: models.some((option) => option.id === selectedModelId) + }; + } + + if (conversationModel) { + return { + hasModelSelected: true, + isSelectedModelAvailable: models.some((option) => option.model === conversationModel) + }; + } + + return { hasModelSelected: false, isSelectedModelAvailable: false }; +} diff --git a/ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts b/ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts new file mode 100644 index 000000000000..2ea96c70495d --- /dev/null +++ b/ui/apps/chat/tests/client/chat-form-model-availability.svelte.test.ts @@ -0,0 +1,84 @@ +// Regression: when the conversation's last assistant message names a model that is no +// longer available, picking an available model in the chat form must clear the submit +// button's error state. The form's selection always decides it. + +import ChatFormTestWrapper from './components/ChatFormTestWrapper.svelte'; +import { MessageRole, ServerRole } from '#lib/enums/index.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import { serverStore } from '#lib/stores/llama-server.svelte.ts'; +import { modelsStore } from '#lib/stores/models/index.svelte.ts'; +import type { DatabaseMessage, ModelOption } from '#lib/types/index.ts'; +import { tick } from 'svelte'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { render } from 'vitest-browser-svelte'; + +const AVAILABLE: ModelOption = { + capabilities: [], + id: 'org/available:Q4_K_M', + model: 'org/available:Q4_K_M', + name: 'org/available:Q4_K_M' +}; +const GONE = 'org/gone:Q4_K_M'; + +function assistantMessage(model: string): DatabaseMessage { + return { + children: [], + content: 'Hello', + convId: 'c1', + id: 'm1', + model, + parent: null, + role: MessageRole.ASSISTANT, + timestamp: 0, + type: 'text' + } as DatabaseMessage; +} + +function sendButton(container: HTMLElement) { + const button = container.querySelector('button[type="submit"]'); + + if (!button) throw new Error('send button not rendered'); + + return button; +} + +const isErrorState = (button: HTMLButtonElement) => button.classList.contains('bg-surface-danger'); + +beforeEach(() => { + serverStore.role = ServerRole.ROUTER; + modelsStore.models = [AVAILABLE]; + modelsStore.clearSelection(); + conversationsStore.activeMessages = [assistantMessage(GONE)]; +}); + +afterEach(() => { + conversationsStore.activeMessages = []; + modelsStore.clearSelection(); + modelsStore.models = []; +}); + +describe('ChatForm model availability', () => { + it('shows the error state while the only model is the conversation one that is gone', async () => { + const { container } = render(ChatFormTestWrapper, { initialValue: 'Hi' }); + + await tick(); + + const button = sendButton(container); + + expect(isErrorState(button)).toBe(true); + expect(button.disabled).toBe(true); + }); + + it('clears the error state once an available model is selected in the form', async () => { + const { container } = render(ChatFormTestWrapper, { initialValue: 'Hi' }); + + await tick(); + await modelsStore.selectModelById(AVAILABLE.id); + await tick(); + + const button = sendButton(container); + + expect(isErrorState(button)).toBe(false); + expect(button.disabled).toBe(false); + }); +}); diff --git a/ui/apps/chat/tests/unit/chat-form-model-state.test.ts b/ui/apps/chat/tests/unit/chat-form-model-state.test.ts new file mode 100644 index 000000000000..ab8281206c66 --- /dev/null +++ b/ui/apps/chat/tests/unit/chat-form-model-state.test.ts @@ -0,0 +1,70 @@ +// Guards which model decides the chat form's submit state: the form's own selection +// always wins over the model of the conversation's last assistant message. + +import { getChatFormModelState } from '#lib/utils/model-selection.ts'; +import { describe, expect, it } from 'vitest'; + +const AVAILABLE = { id: 'org/available:Q4_K_M', model: 'org/available:Q4_K_M' }; +const GONE = 'org/gone:Q4_K_M'; + +describe('getChatFormModelState', () => { + it('reports an available model when the form selects one, even if the conversation used a gone model', () => { + expect( + getChatFormModelState({ + conversationModel: GONE, + isRouter: true, + models: [AVAILABLE], + selectedModelId: AVAILABLE.id + }) + ).toEqual({ hasModelSelected: true, isSelectedModelAvailable: true }); + }); + + it('reports an unavailable model when the form selects one that left the list', () => { + expect( + getChatFormModelState({ + conversationModel: AVAILABLE.model, + isRouter: true, + models: [AVAILABLE], + selectedModelId: GONE + }) + ).toEqual({ hasModelSelected: true, isSelectedModelAvailable: false }); + }); + + it('falls back to the conversation model when nothing is selected in the form', () => { + const state = (conversationModel: string) => + getChatFormModelState({ + conversationModel, + isRouter: true, + models: [AVAILABLE], + selectedModelId: null + }); + + expect(state(GONE)).toEqual({ hasModelSelected: true, isSelectedModelAvailable: false }); + expect(state(AVAILABLE.model)).toEqual({ + hasModelSelected: true, + isSelectedModelAvailable: true + }); + }); + + it('has no model selected on a router with neither a selection nor a conversation model', () => { + expect( + getChatFormModelState({ + conversationModel: null, + isRouter: true, + models: [AVAILABLE], + selectedModelId: null + }) + ).toEqual({ hasModelSelected: false, isSelectedModelAvailable: false }); + }); + + it('always has an available model outside router mode', () => { + expect( + getChatFormModelState({ + conversationModel: GONE, + isRouter: false, + models: [], + selectedModelId: null + }) + ).toEqual({ hasModelSelected: true, isSelectedModelAvailable: true }); + }); +}); From a6ac41c757c066941766164439f6876f2deaab04 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 09:25:18 +0100 Subject: [PATCH 090/401] ui: match tool call timer font size to its title (#32922) Assisted-by: Claude (Opus 5.5 Medium) --- .../ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte index b83c74933036..9174148ac615 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallElapsed.svelte @@ -29,7 +29,7 @@ {label} From 82dd9704742e8514088914b61d61fbcd35d599ee Mon Sep 17 00:00:00 2001 From: Aircg <64237451+cgair@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:54:31 +0800 Subject: [PATCH 091/401] server : fix skipped prompt cache lookups (#28992) * server : fix skipped prompt cache lookups Assisted-by: Claude Opus 5 * server : let the slot scheduler ask the prompt cache Move the prompt cache lookup into server_slot_sched::select() so the plan alone decides whether the cache is updated, and the caller only applies it. find_better() and has_better() are now const, and find_better() also returns the common prefix, so load() no longer recomputes it. --------- Co-authored-by: Pascal --- tools/server/server-context.cpp | 2 +- tools/server/server-slot-sched.cpp | 49 ++++++++++++---- tools/server/server-slot-sched.h | 10 +++- tools/server/tests/unit/test_completion.py | 65 ++++++++++++++++++++++ 4 files changed, 113 insertions(+), 13 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 89f884e6548c..932d08bc71dd 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -2973,7 +2973,7 @@ struct server_context_impl { const int id_task = task.id; - const auto plan = slot_sched.select(get_slot_infos(), task, get_task_lora(task)); + const auto plan = slot_sched.select(get_slot_infos(), task, get_task_lora(task), prompt_cache.get()); server_slot * slot = plan.id_slot == -1 ? nullptr : get_slot_by_id(plan.id_slot); diff --git a/tools/server/server-slot-sched.cpp b/tools/server/server-slot-sched.cpp index fccfb709a6db..526a144c31a4 100644 --- a/tools/server/server-slot-sched.cpp +++ b/tools/server/server-slot-sched.cpp @@ -164,21 +164,21 @@ server_prompt_cache_state * server_prompt_cache::alloc(const server_prompt & pro return &states.back(); } -bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { +std::list::const_iterator server_prompt_cache::find_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, int & lcp) const { // a prompt made with another lora config is cleared before the new one starts, so it counts as empty const bool is_empty = prompt.tokens.empty() || lora_should_clear_cache(prompt.lora, lora_new); - int lcp_best = is_empty ? 0 : prompt.tokens.get_common_prefix(tokens_new); + lcp = is_empty ? 0 : prompt.tokens.get_common_prefix(tokens_new); - float f_keep_best = is_empty ? -1.0f : float(lcp_best) / prompt.tokens.size(); // empty slot: any cache entry wins - float f_sim_best = float(lcp_best) / tokens_new.size(); + float f_keep_best = is_empty ? -1.0f : float(lcp) / prompt.tokens.size(); // empty slot: any cache entry wins + float f_sim_best = float(lcp) / tokens_new.size(); SRV_TRC(" - looking for better prompt, base f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); - auto it_best = states.end(); + auto it_best = states.cend(); // find the most similar cached prompt, that would also preserve the most context - for (auto it = states.begin(); it != states.end(); ++it) { + for (auto it = states.cbegin(); it != states.cend(); ++it) { if (lora_should_clear_cache(it->prompt.lora, lora_new)) { SRV_TRC(" - prompt with length %7zu, skipping, other lora config\n", it->prompt.tokens.size()); continue; @@ -199,15 +199,34 @@ bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tok if (f_keep_best < f_keep_cur && f_sim_best < f_sim_cur) { f_keep_best = f_keep_cur; f_sim_best = f_sim_cur; - lcp_best = lcp_cur; + lcp = lcp_cur; it_best = it; } } - if (it_best != states.end()) { + if (it_best != states.cend()) { SRV_TRC(" - found better prompt with f_keep = %.3f, f_sim = %.3f\n", f_keep_best, f_sim_best); + } + + return it_best; +} + +bool server_prompt_cache::has_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new) const { + int lcp = 0; + + return find_better(prompt, tokens_new, lora_new, lcp) != states.cend(); +} + +bool server_prompt_cache::load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot) { + int lcp_best = 0; + + const auto it_found = find_better(prompt, tokens_new, lora_new, lcp_best); + // an empty erase gives a mutable iterator to the same entry, its prompt is moved out below + const auto it_best = states.erase(it_found, it_found); + + if (it_best != states.end()) { const int64_t t_start = ggml_time_us(); { @@ -321,7 +340,7 @@ std::vector server_slot_sched::get_free_slots(const std::vector & slots, const server_task & task, const std::vector & lora) const { +server_slot_plan server_slot_sched::select(const std::vector & slots, const server_task & task, const std::vector & lora, const server_prompt_cache * prompt_cache) const { const server_slot_info * ret = nullptr; bool update_cache = false; @@ -392,7 +411,9 @@ server_slot_plan server_slot_sched::select(const std::vector & } if (ret != nullptr) { - const float f_keep = (f_sim_best*task.tokens.size()) / ret->prompt->tokens.size(); + // empty slot: nothing to keep, avoid 0/0 + const float f_keep = ret->prompt->tokens.size() > 0 ? + (f_sim_best*task.tokens.size()) / ret->prompt->tokens.size() : 0.0f; if (task.id_slot == -1) { SLT_INF(*ret, "selected slot by LCP similarity, f_sim_best = %.3f (> %.3f thold), f_keep = %.3f\n", @@ -424,7 +445,13 @@ server_slot_plan server_slot_sched::select(const std::vector & } // cache prompts only for the tasks that reuse them - update_cache = update_cache && !task.is_stateless(); + if (prompt_cache == nullptr || task.is_stateless()) { + return { ret->id, false }; + } + + // the checks above only tell if the outgoing state is worth saving + // the cache can still hold a better start for this task, so ask it + update_cache = update_cache || prompt_cache->has_better(*ret->prompt, task.tokens, lora); return { ret->id, update_cache }; } diff --git a/tools/server/server-slot-sched.h b/tools/server/server-slot-sched.h index fc0099dc04fa..f1be0fe2f54b 100644 --- a/tools/server/server-slot-sched.h +++ b/tools/server/server-slot-sched.h @@ -97,7 +97,14 @@ struct server_prompt_cache { server_prompt_cache_state * alloc(const server_prompt & prompt, size_t state_size_main, size_t state_size_drft); + // the cached state that is a better starting point than `prompt` for `tokens_new`, states.end() if none + // lcp: the common prefix of that state with `tokens_new` // lora_new: the lora config of the new prompt, the states made with another config are skipped + std::list::const_iterator find_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, int & lcp) const; + + bool has_better(const server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new) const; + + // restore the result of find_better into the slot `id_slot` bool load(server_prompt & prompt, const server_tokens & tokens_new, const std::vector & lora_new, llama_context * ctx_tgt, llama_context * ctx_dft, int32_t id_slot); void update(); @@ -130,5 +137,6 @@ struct server_slot_sched { std::vector get_free_slots(const std::vector & slots, size_t n_slots_needed, int exclude_id_slot) const; // lora: the lora config of the task - server_slot_plan select(const std::vector & slots, const server_task & task, const std::vector & lora) const; + // prompt_cache: nullptr if disabled + server_slot_plan select(const std::vector & slots, const server_task & task, const std::vector & lora, const server_prompt_cache * prompt_cache) const; }; diff --git a/tools/server/tests/unit/test_completion.py b/tools/server/tests/unit/test_completion.py index aa29454b1e49..1d58f9e2b21c 100644 --- a/tools/server/tests/unit/test_completion.py +++ b/tools/server/tests/unit/test_completion.py @@ -865,3 +865,68 @@ def assert_same_output(actual, expected): assert actual["timings"]["cache_n"] == len(prefix) + len(first["tokens"]) - 1 assert actual["timings"]["prompt_n"] == len(suffix) + 1 assert_same_output(actual, expected) + + +# the prompt cache has to be consulted even when the selected slot already holds a usable prefix, and even when the slot was picked by id +# ref: https://github.com/ggml-org/llama.cpp/issues/28139 +# ref: https://github.com/ggml-org/llama.cpp/issues/28276 +PROMPT_HEAD = "The capital of France is Paris. " * 2 +PROMPT_TAIL = "The river Seine runs slowly through the middle of the old stone city. " + +# PROMPT_SHORT is a strict prefix of PROMPT_LONG and covers more of it than the default --slot-prompt-similarity, so the slot is selected by the LCP loop +PROMPT_SHORT = PROMPT_HEAD + PROMPT_TAIL*6 +PROMPT_LONG = PROMPT_SHORT + PROMPT_TAIL*18 +PROMPT_OTHER = "Whiskers the cat climbed the tall oak tree behind the red barn. " * 12 + + +def prompt_cache_server(): + global server + server.n_slots = 2 + server.n_ctx = 2048 + server.n_batch = 512 + server.cache_ram = 512 + server.start() + + +def completion_cached(prompt: str, id_slot: int | None = None): + data = {"prompt": prompt, "cache_prompt": True, "n_predict": 0, "temperature": 0.0} + if id_slot is not None: + data["id_slot"] = id_slot + res = server.make_request("POST", "/completion", data=data) + assert res.status_code == 200 + return res.body["timings"]["prompt_n"], res.body["timings"]["cache_n"] + + +def test_prompt_cache_used_when_slot_pinned_by_id_is_empty(): + global server + prompt_cache_server() + + n_cold, _ = completion_cached(PROMPT_LONG, id_slot=0) + assert n_cold > 100 + + # push the state of slot 0 into the prompt cache + completion_cached(PROMPT_OTHER, id_slot=0) + + # slot 1 is empty, so f_keep has no meaning here - the cache still holds the exact state for this prompt and has to be used + n_pinned, n_cached = completion_cached(PROMPT_LONG, id_slot=1) + assert n_cached == n_cold - n_pinned + assert n_pinned < n_cold + + +def test_prompt_cache_used_when_slot_holds_a_shorter_prefix(): + global server + prompt_cache_server() + + # warm slot 1 before the long state reaches the cache, otherwise this request would consume the cached entry itself + n_short, _ = completion_cached(PROMPT_SHORT, id_slot=1) + + n_cold, _ = completion_cached(PROMPT_LONG, id_slot=0) + assert n_cold > n_short + + # push the long state of slot 0 into the prompt cache + completion_cached(PROMPT_OTHER, id_slot=0) + + # slot 1 holds a prefix of PROMPT_LONG and would be reused as is, but the cache holds the whole state and is the better start + n_reuse, n_cached = completion_cached(PROMPT_LONG, id_slot=1) + assert n_cached == n_cold - n_reuse + assert n_reuse < n_cold - n_short From 5fe49068594967a70b32deb3f9f401d7e4b7fedd Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Tue, 24 Nov 2026 12:11:19 +0200 Subject: [PATCH 092/401] ci : disable test-llama-context on ubuntu-llvmpipe (#32932) The dummy-model context sweep no longer fits within the job timeout on the llvmpipe runner. Exclude it from the ctest run there, keeping the coverage in the other jobs. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) --- .github/workflows/build-vulkan.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-vulkan.yml b/.github/workflows/build-vulkan.yml index b699f2a1723c..3ad308583017 100644 --- a/.github/workflows/build-vulkan.yml +++ b/.github/workflows/build-vulkan.yml @@ -167,7 +167,8 @@ jobs: export GGML_VK_VISIBLE_DEVICES=0 export GGML_VK_DISABLE_F16=1 export GGML_VK_DISABLE_COOPMAT=1 - ctest -L main --verbose --timeout 900 + # TODO: too slow on llvmpipe + ctest -L main -E "test-llama-context" --verbose --timeout 900 windows: name: windows / ${{ matrix.arch }} From ae6a7ad2c5754dd8db93d04c84fda70435864f6e Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 11:12:47 +0100 Subject: [PATCH 093/401] ui: move the agentic loop and trace phrasing into @ggml-org/llama-harness (#32927) * ui: add @ggml-org/llama-harness, the agentic loop as a package, in ui/lib/harness Llama Harness is the agentic loop as headless TypeScript with no UI, no DOM and no dependencies. It streams a turn, runs the tools the model called, gives it the results, and repeats until the model answers without a tool call. An app gives it an inference client and tools, and reads the run as a stream of events: run(messages, tools, signal). It ships a client for any OpenAI-compatible endpoint, so it also runs on its own in Node. The UI workflow type-checks, tests and packs it. Assisted-by: Claude (Fable 5.2) * ui: run Llama Chat's agentic loop through @ggml-org/llama-harness The loop leaves the agentic store, which now gives the harness what the app owns: ChatService as its inference client, the enabled tools behind the permission gate, and the callbacks that store each turn. Its API and the flow's callbacks are unchanged. A unit test runs the flow end to end with the server and the tools mocked. Chat compiles the harness from source through an alias, so the builds that copy or isolate ui/apps/chat now bring ui/lib/harness along: CMake and Nix through LLAMA_HARNESS_DIR, the Dockerfiles with a COPY. Assisted-by: Claude (Fable 5.2) * ui: bring the architecture docs in line with the ui/ folder The layout card no longer calls the move planned, the harness is in the pages, and they say that Llama Chat does not import @ggml-org/llama-ui yet. Assisted-by: Claude (Opus 5.5 Medium) * ui: phrase agent traces in @ggml-org/llama-harness The plain-language lines of an agent trace move out of Llama Chat into the harness, as a headless trace module any app on it can use: what one tool call did ("Read app.ts"), what it is doing now ("Running npm test", "Thinking"), what a run of calls did ("Ran 3 commands, read 2 files"), and how calls fold into one row with the reasoning around them. createTracePhraser knows llama-server's built-in tools. An app adds its own with resolvers and a phrasing table; any other tool reads as "Used " with its main argument, and a call with a description shows the model's own words. The lenient parse of streamed arguments and the targeted read of a path in a whole-file argument move with it. Llama Chat keeps its Svelte components and phrases only its own tools: the browser tools, web search and tool_search. Its functions keep their names and signatures, so nothing that renders a trace changes. Assisted-by: Claude (Opus 5.5 Medium) --- .devops/cann.Dockerfile | 3 +- .devops/cpu.Dockerfile | 3 +- .devops/cuda.Dockerfile | 3 +- .devops/intel.Dockerfile | 3 +- .devops/musa.Dockerfile | 3 +- .devops/nix/package.nix | 2 +- .devops/openvino.Dockerfile | 3 +- .devops/rocm.Dockerfile | 3 +- .devops/vulkan.Dockerfile | 3 +- .devops/zendnn.Dockerfile | 3 +- .github/workflows/ui-self-hosted.yml | 2 + .github/workflows/ui.yml | 31 + scripts/ui-assets.cmake | 13 +- ui/README.md | 21 +- ui/apps/chat/AGENTS.md | 2 +- ui/apps/chat/README.md | 21 +- ui/apps/chat/sources.cmake | 3 +- .../ChatMessageToolCallBlockDefault.svelte | 2 +- .../ChatMessageToolCall/ToolCallBlock.svelte | 13 +- .../ChatMessageToolCall/parsers/_shared.ts | 57 +- .../ChatMessageToolCall/parsers/edit-file.ts | 8 +- .../parsers/tool-call-phrasing.ts | 428 +----- .../ChatMessageToolCall/parsers/write-file.ts | 8 +- .../ChatMessages/ChatMessageAgentTrace.svelte | 9 +- .../src/lib/constants/settings.constants.ts | 2 +- .../lib/constants/tool-call-args.constants.ts | 8 - .../constants/tool-call-phrasing.constants.ts | 107 +- ui/apps/chat/src/lib/enums/agentic.enums.ts | 32 + ui/apps/chat/src/lib/enums/index.ts | 3 +- ui/apps/chat/src/lib/enums/tools.enums.ts | 13 - .../src/lib/stores/agentic/index.svelte.ts | 931 ++++++------ ui/apps/chat/src/lib/types/index.ts | 2 - ui/apps/chat/src/lib/types/tools.d.ts | 31 +- ui/apps/chat/src/lib/utils/async-queue.ts | 50 + ui/apps/chat/src/lib/utils/index.ts | 1 - .../src/lib/utils/parse-partial-json-args.ts | 124 -- ui/apps/chat/tests/unit/agentic-flow.test.ts | 373 +++++ .../chat/tests/unit/agentic-hotpath.bench.ts | 2 +- ui/apps/chat/tests/unit/async-queue.test.ts | 42 + .../tests/unit/tool-call-phrasing.test.ts | 8 +- ui/apps/chat/tsconfig.json | 3 +- ui/apps/chat/vite.config.ts | 6 +- ui/lib/harness/.gitignore | 6 + ui/lib/harness/.npmrc | 1 + ui/lib/harness/LICENSE | 21 + ui/lib/harness/README.md | 83 ++ ui/lib/harness/package-lock.json | 1255 +++++++++++++++++ ui/lib/harness/package.json | 39 + ui/lib/harness/src/abort.ts | 17 + ui/lib/harness/src/harness.ts | 375 +++++ ui/lib/harness/src/index.ts | 5 + ui/lib/harness/src/openai-client.ts | 143 ++ ui/lib/harness/src/trace/args.ts | 158 +++ ui/lib/harness/src/trace/index.ts | 33 + ui/lib/harness/src/trace/phrasing.ts | 497 +++++++ ui/lib/harness/src/trace/types.ts | 94 ++ ui/lib/harness/src/types.ts | 209 +++ ui/lib/harness/tests/harness.test.ts | 316 +++++ ui/lib/harness/tests/openai-client.test.ts | 130 ++ ui/lib/harness/tests/trace.test.ts | 123 ++ ui/lib/harness/tsconfig.build.json | 10 + ui/lib/harness/tsconfig.json | 13 + 62 files changed, 4584 insertions(+), 1329 deletions(-) create mode 100644 ui/apps/chat/src/lib/utils/async-queue.ts delete mode 100644 ui/apps/chat/src/lib/utils/parse-partial-json-args.ts create mode 100644 ui/apps/chat/tests/unit/agentic-flow.test.ts create mode 100644 ui/apps/chat/tests/unit/async-queue.test.ts create mode 100644 ui/lib/harness/.gitignore create mode 100644 ui/lib/harness/.npmrc create mode 100644 ui/lib/harness/LICENSE create mode 100644 ui/lib/harness/README.md create mode 100644 ui/lib/harness/package-lock.json create mode 100644 ui/lib/harness/package.json create mode 100644 ui/lib/harness/src/abort.ts create mode 100644 ui/lib/harness/src/harness.ts create mode 100644 ui/lib/harness/src/index.ts create mode 100644 ui/lib/harness/src/openai-client.ts create mode 100644 ui/lib/harness/src/trace/args.ts create mode 100644 ui/lib/harness/src/trace/index.ts create mode 100644 ui/lib/harness/src/trace/phrasing.ts create mode 100644 ui/lib/harness/src/trace/types.ts create mode 100644 ui/lib/harness/src/types.ts create mode 100644 ui/lib/harness/tests/harness.test.ts create mode 100644 ui/lib/harness/tests/openai-client.test.ts create mode 100644 ui/lib/harness/tests/trace.test.ts create mode 100644 ui/lib/harness/tsconfig.build.json create mode 100644 ui/lib/harness/tsconfig.json diff --git a/.devops/cann.Dockerfile b/.devops/cann.Dockerfile index 791b583ca6a5..83beced0add1 100644 --- a/.devops/cann.Dockerfile +++ b/.devops/cann.Dockerfile @@ -25,10 +25,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${CANN_BASE_IMAGE} AS build diff --git a/.devops/cpu.Dockerfile b/.devops/cpu.Dockerfile index f63e005ec930..fb3b5e9d9744 100644 --- a/.devops/cpu.Dockerfile +++ b/.devops/cpu.Dockerfile @@ -15,10 +15,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/cuda.Dockerfile b/.devops/cuda.Dockerfile index cf1715d43a4c..058212e2c2a8 100644 --- a/.devops/cuda.Dockerfile +++ b/.devops/cuda.Dockerfile @@ -23,10 +23,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_CUDA_DEV_CONTAINER} AS build diff --git a/.devops/intel.Dockerfile b/.devops/intel.Dockerfile index 0783ef738c9f..5a4ddabe5796 100644 --- a/.devops/intel.Dockerfile +++ b/.devops/intel.Dockerfile @@ -17,10 +17,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/intel/deep-learning-essentials:$ONEAPI_VERSION AS build diff --git a/.devops/musa.Dockerfile b/.devops/musa.Dockerfile index 3ae62a676e4b..66568885590b 100644 --- a/.devops/musa.Dockerfile +++ b/.devops/musa.Dockerfile @@ -21,10 +21,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM ${BASE_MUSA_DEV_CONTAINER} AS build diff --git a/.devops/nix/package.nix b/.devops/nix/package.nix index 4ac844ff959d..887270fb23bd 100644 --- a/.devops/nix/package.nix +++ b/.devops/nix/package.nix @@ -182,7 +182,7 @@ effectiveStdenv.mkDerivation (finalAttrs: { webui = stdenvNoCC.mkDerivation { pname = "webui"; version = llamaVersion; - # the app compiles Llama UI from its source in ../../lib/ui, so the source is ui/ as a whole + # the app compiles Llama UI and the harness from their sources in ../../lib, so the source is ui/ as a whole src = lib.cleanSource ../../ui; sourceRoot = "source/apps/chat"; diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile index fb8cb4c61f66..1509796dd225 100644 --- a/.devops/openvino.Dockerfile +++ b/.devops/openvino.Dockerfile @@ -34,10 +34,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ## Build Image diff --git a/.devops/rocm.Dockerfile b/.devops/rocm.Dockerfile index ba9e85a0ed19..b7e5938d935a 100644 --- a/.devops/rocm.Dockerfile +++ b/.devops/rocm.Dockerfile @@ -23,10 +23,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build ### Build image diff --git a/.devops/vulkan.Dockerfile b/.devops/vulkan.Dockerfile index 023847628366..4e97422d6d07 100644 --- a/.devops/vulkan.Dockerfile +++ b/.devops/vulkan.Dockerfile @@ -15,10 +15,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.devops/zendnn.Dockerfile b/.devops/zendnn.Dockerfile index e49df81ca45f..da2fea2dfc58 100644 --- a/.devops/zendnn.Dockerfile +++ b/.devops/zendnn.Dockerfile @@ -15,10 +15,11 @@ COPY ui/apps/chat/package.json ui/apps/chat/package-lock.json ./ RUN npm ci COPY ui/apps/chat/ ./ -# the app compiles Llama UI and Llama Voice from their sources next to it +# the app compiles Llama UI, Llama Voice and the harness from their sources next to it COPY ui/lib/ui/package.json /app/ui/lib/ui/package.json COPY ui/lib/ui/src/lib/ /app/ui/lib/ui/src/lib/ COPY ui/lib/voice/src/ /app/ui/lib/voice/src/ +COPY ui/lib/harness/src/ /app/ui/lib/harness/src/ RUN LLAMA_BUILD_NUMBER="$APP_VERSION" npm run build FROM docker.io/ubuntu:$UBUNTU_VERSION AS build diff --git a/.github/workflows/ui-self-hosted.yml b/.github/workflows/ui-self-hosted.yml index 4967de07ca21..f254f3b0c7d2 100644 --- a/.github/workflows/ui-self-hosted.yml +++ b/.github/workflows/ui-self-hosted.yml @@ -20,6 +20,7 @@ on: 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', 'ui/lib/voice/**.*', + 'ui/lib/harness/**.*', 'tools/server/tests/**.*' ] pull_request: @@ -30,6 +31,7 @@ on: 'ui/apps/chat/**.*', 'ui/lib/ui/**.*', 'ui/lib/voice/**.*', + 'ui/lib/harness/**.*', 'tools/server/tests/**.*' ] diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 65e5c36ffdbf..bba032416bfb 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -181,6 +181,37 @@ jobs: run: npm run prepack working-directory: ui/lib/voice + harness-checks: + name: Harness checks + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/lib/harness + + - name: Run type checking + run: npm run check + working-directory: ui/lib/harness + + - name: Run tests + run: npm test + working-directory: ui/lib/harness + + - name: Build the package + run: npm run prepack + working-directory: ui/lib/harness + e2e-tests: name: E2E Tests needs: ui-build diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake index a3b4f16d7b68..8079c1c09651 100644 --- a/scripts/ui-assets.cmake +++ b/scripts/ui-assets.cmake @@ -21,11 +21,13 @@ set(DIST_DIR "${UI_BINARY_DIR}/dist") set(SRC_DIST_DIR "${UI_SOURCE_DIR}/dist") # The stage keeps the layout of ui/: the app in apps/chat, with the sources of # Llama UI that it compiles next to it in lib/ui (see ui/apps/chat/scripts/llama-ui.js), -# and those of Llama Voice in lib/voice (see ui/apps/chat/vite.config.ts). +# and those of Llama Voice and the harness in lib/voice and lib/harness (see +# ui/apps/chat/vite.config.ts). set(STAGE_DIR "${UI_BINARY_DIR}/ui-src") set(WORK_DIR "${STAGE_DIR}/apps/chat") set(UI_LIB_DIR "${UI_SOURCE_DIR}/../../lib/ui") set(UI_VOICE_DIR "${UI_SOURCE_DIR}/../../lib/voice") +set(HARNESS_DIR "${UI_SOURCE_DIR}/../../lib/harness") set(STAMP_FILE "${UI_BINARY_DIR}/.ui-stamp") set(EMBED_STAMP "${UI_BINARY_DIR}/.ui-embed.sha256") set(UI_CPP "${UI_BINARY_DIR}/ui.cpp") @@ -325,7 +327,7 @@ function(npm_build_should_skip out_var) endfunction() function(stage_sources) - # everything but the app goes: the library, restaged below, and what a stage + # everything but the app goes: the packages, restaged below, and what a stage # from before this layout left at the top, its node_modules included if(EXISTS "${STAGE_DIR}") file(GLOB staged RELATIVE "${STAGE_DIR}" "${STAGE_DIR}/*") @@ -349,7 +351,8 @@ function(stage_sources) PATTERN "node_modules" EXCLUDE ) - # what the app reads of the library: its sources and the dependency list + # what the app reads of the packages: Llama UI's sources and dependency list, + # and the harness's sources file(COPY "${UI_LIB_DIR}/package.json" DESTINATION "${STAGE_DIR}/lib/ui" NO_SOURCE_PERMISSIONS @@ -364,6 +367,10 @@ function(stage_sources) DESTINATION "${STAGE_DIR}/lib/voice" NO_SOURCE_PERMISSIONS ) + file(COPY "${HARNESS_DIR}/src" + DESTINATION "${STAGE_DIR}/lib/harness" + NO_SOURCE_PERMISSIONS + ) endfunction() function(npm_build out_var) diff --git a/ui/README.md b/ui/README.md index 0f210a40c80c..3d6521b58ac4 100644 --- a/ui/README.md +++ b/ui/README.md @@ -5,10 +5,11 @@ The UI of llama.cpp: the packages in `lib` and the apps built on them. ```text ui/ ├── lib/ -│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components -│ └── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation +│ ├── ui/ @ggml-org/llama-ui: design tokens, fonts, surfaces and components +│ ├── voice/ @ggml-org/llama-voice: microphone capture, transcription and dictation +│ └── harness/ @ggml-org/llama-harness: the agentic loop, headless └── apps/ - └── chat/ Llama Chat, the chat app that llama-server serves + └── chat/ Llama Chat, the chat app that llama-server serves ``` - [`lib/ui`](lib/ui/README.md) draws the parts and handles interaction, with no business logic. It is built with @@ -17,12 +18,18 @@ ui/ - [`lib/voice`](lib/voice/README.md) records the microphone and turns speech into text through llama-server, with no UI: Llama UI draws the voice parts. It is plain TypeScript built with `tsc`, plus a Svelte entry (`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet. -- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop. CMake - builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as `@ggml-org/llama-chat` - (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server. +- [`lib/harness`](lib/harness/README.md) is the agentic loop: plain TypeScript with no UI and no dependencies. An app + gives it an inference client and tools, and reads its events. +- [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop through the + harness. CMake builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as + `@ggml-org/llama-chat` (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server. Each folder is its own npm package with its own `package-lock.json`: run `npm ci` in the one you work on. Building, -checking and testing `apps/chat` needs no install in `lib/ui` or `lib/voice`. +checking and testing `apps/chat` needs no install in `lib/ui`, `lib/voice` or `lib/harness`. + +The split between library and app is not finished. Llama Chat takes its tokens, fonts, surfaces and base components +from `lib/ui`, but still has its own versions of what the library holds above those (ActionIcon, SearchInput, Logo, +SyntaxHighlightedCode and the Model UI), and `DESIGN.md`, `BRAND.md` and the full Storybook still sit beside the app. ## Releases diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md index 32e6a009a2c9..0b4884de3167 100644 --- a/ui/apps/chat/AGENTS.md +++ b/ui/apps/chat/AGENTS.md @@ -1,6 +1,6 @@ # Instructions for ui/apps/chat -These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. +These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. The agentic loop is `ui/lib/harness` (`@ggml-org/llama-harness`). - **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated. - **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/`, one folder per `src/lib/components/app/` (`chat/` has one per Chat folder), titled `Llama Chat//`. An accessibility story sits next to its component's, as `.a11y.stories.svelte`, titled `...//Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here. diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index abee5d43bb0d..891fe6b2a422 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -84,16 +84,17 @@ Llama Chat is the first app on Llama UI, and the reference for the line between The app imports the library as `@ggml-org/llama-ui/ui/` and compiles its sources in its own build, with no install of the library (see `scripts/vite-plugin-llama-ui.ts`). Data flows one way, through these layers: -| Layer | Lives in | What it holds | -| -------------- | ------------------------- | --------------------------------------------------------------------------------------------------- | -| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | -| App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area | -| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | -| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) | -| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | -| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | -| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox | -| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` | +| Layer | Lives in | What it holds | +| -------------- | ------------------------- | ---------------------------------------------------------------------------------------------------- | +| Routes | `src/routes` | `/`, `/chat/[id]`, `/models`, `/mcp-servers`, `/settings`, `/search` | +| App components | `src/lib/components/app` | Chat, navigation, models, MCP, settings and dialogs, grouped by area | +| UI components | `ui/lib/ui` | shadcn-svelte on bits-ui, from Llama UI | +| Voice | `ui/lib/voice` | Microphone capture, transcription and dictation, from Llama Voice (`@ggml-org/llama-voice`) | +| Hooks | `src/lib/hooks` | View logic between components and stores: scroll, drag and drop, pickers, keyboard | +| Stores | `src/lib/stores` | Application state as Svelte 5 runes: chat, conversations, the agentic loop, tools, models, settings | +| Agentic loop | `ui/lib/harness` | Llama Harness: streams a turn, runs the tools the model called, repeats until it answers without one | +| Services | `src/lib/services` | Stateless I/O: the llama-server API, IndexedDB, MCP, the Hugging Face Hub, the tool sandbox | +| Storage + API | the browser, llama-server | IndexedDB and localStorage; llama-server's `/v1`, `/props`, `/models`, `/tools`, `/slots` | ```mermaid flowchart LR diff --git a/ui/apps/chat/sources.cmake b/ui/apps/chat/sources.cmake index d3daee6c9d37..f12daa8134c1 100644 --- a/ui/apps/chat/sources.cmake +++ b/ui/apps/chat/sources.cmake @@ -3,10 +3,11 @@ set(UI_SOURCE_GLOBS src/* static/* - # Llama UI, which the app compiles from source + # Llama UI and the harness, which the app compiles from source ../../lib/ui/src/lib/* # Llama Voice, also compiled from source ../../lib/voice/src/* + ../../lib/harness/src/* ) set(UI_SOURCE_FILES diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte index 0cbe86535a22..9485dc8f11cf 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockDefault.svelte @@ -3,9 +3,9 @@ // Renders section.toolArgs / section.toolResult directly using the // shared chrome shell. - import { simpleToolArgFields } from './parsers/tool-call-phrasing'; import ToolCallBlock from './ToolCallBlock.svelte'; import ToolCallTitle from './ToolCallTitle.svelte'; + import { simpleToolArgFields } from '@ggml-org/llama-harness'; import { Loader2 } from '@lucide/svelte'; import { MarkdownContent, SyntaxHighlightedCode } from '#lib/components/app/index.ts'; import { MAX_HEIGHT_CODE_BLOCK } from '#lib/constants/index.ts'; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte index f8f9ee05be45..2f45f9a37ca3 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ToolCallBlock.svelte @@ -8,17 +8,18 @@ // Components supply only their `meta`, a title snippet, and a body // snippet - everything around them is this single source of truth. - import { - describeToolCall, - formatToolCallLine, - isToolCallRunning - } from './parsers/tool-call-phrasing'; + import { describeToolCall } from './parsers/tool-call-phrasing'; import { useToolCallElapsed } from './tool-call-elapsed'; import ToolCallElapsed from './ToolCallElapsed.svelte'; + import { + formatToolCallLine, + isToolCallRunning, + type ToolCallDescription + } from '@ggml-org/llama-harness'; import { CollapsibleContentBlock } from '#lib/components/app/index.ts'; import { AgenticSectionType } from '#lib/enums/index.ts'; import { settingsStore } from '#lib/stores/index.ts'; - import type { AgenticSection, ToolCallDescription } from '#lib/types/index.ts'; + import type { AgenticSection } from '#lib/types/index.ts'; import { imageExtras, toolCallShownArg } from '#lib/utils/index.ts'; import type { Snippet } from 'svelte'; import { fade } from 'svelte/transition'; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts index e11a1fa4d336..122d70b540fb 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/_shared.ts @@ -4,14 +4,10 @@ // args-present check, JSON parse), plus the same path aliases - keeping // them here lets each parser stay focused on its own format quirks. -import { - FILE_PATH_SEPARATOR_REGEX, - TOOL_ARG_PATH_KEYS, - TOOL_ARG_STRING_FIELD_PATTERN_TEMPLATE -} from '#lib/constants/index.ts'; +import { parsePartialJsonArgs } from '@ggml-org/llama-harness'; +import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; import { BuiltInTool } from '#lib/enums/index.ts'; import type { AgenticSection } from '#lib/types/agentic.js'; -import { parsePartialJsonArgs } from '#lib/utils/parse-partial-json-args.ts'; /** * Strict (final-state) JSON parser for a tool-args blob. Mirrors the @@ -33,55 +29,6 @@ function parseFinalToolArgs(blob: string): Record | null { } } -// Compiled per key on first use; the key set is tiny and fixed. -const toolArgStringRegexes = new Map(); - -/** - * Extract a string field from a JSON tool-args blob without parsing the - * whole document. write_file and edit_file args embed full file contents, - * yet the block title needs only the path; a targeted key match plus a - * JSON.parse of the captured string literal alone keeps title rendering - * O(path) instead of O(blob). Returns undefined when the key is missing - * or its value is not a string; callers fall back to the full parse. - */ -export function extractToolArgString( - toolArgs: string, - keys: readonly string[] -): string | undefined { - for (const key of keys) { - let pattern = toolArgStringRegexes.get(key); - - if (!pattern) { - pattern = new RegExp(TOOL_ARG_STRING_FIELD_PATTERN_TEMPLATE.replace('{key}', key)); - toolArgStringRegexes.set(key, pattern); - } - - const match = pattern.exec(toolArgs); - - if (!match) continue; - - try { - const value: unknown = JSON.parse(`"${match[1]}"`); - - if (typeof value === 'string') return value; - } catch { - // fall through to the next key; the full parse is the fallback - } - } - - return undefined; -} - -/** - * File name shown in a block title, from a tool-call path. Undefined when - * the call carries no path; the title then shows the tool label alone. - */ -export function fileNameFromPath(filePath: string | undefined): string | undefined { - if (!filePath) return undefined; - - return filePath.split(FILE_PATH_SEPARATOR_REGEX).pop() || filePath; -} - /** * Read the path argument out of an already parsed args object, checking * the aliases in `TOOL_ARG_PATH_KEYS`. Returns undefined when the call diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts index 72c1306a71af..d36979f82321 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/edit-file.ts @@ -4,12 +4,8 @@ // `error` fields. The path is display-only (block title), so a call // that has not streamed one still shows its diffs. -import { - extractToolArgPath, - extractToolArgString, - fileNameFromPath, - parseToolArgs -} from './_shared'; +import { extractToolArgPath, parseToolArgs } from './_shared'; +import { extractToolArgString, fileNameFromPath } from '@ggml-org/llama-harness'; import { TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; import { BuiltInTool, DiffLineKind } from '#lib/enums/index.ts'; import type { diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts index 8792bc90aac4..91d864e60cf1 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts @@ -1,44 +1,24 @@ -// Plain-language lines for tool calls: what one call did ("Read a file -// sheet_new.jpg"), what it is doing now ("Reading package.json") and what -// a run of calls did ("Ran 3 commands, read 2 files"). A call that has the -// arg the settings pick (`description` by default) shows it as the model -// wrote it. Otherwise built-in tools use TOOL_CALL_PHRASING, and MCP and -// unknown tools read as "Used " with their main argument. +// Plain-language lines for the tool calls of a trace. The phrasing itself is +// Llama Harness's (`createTracePhraser`), which knows llama-server's built-in +// tools; this module adds Llama Chat's own: the browser tools, web search and +// tool_search. -import { extractToolArgString, fileNameFromPath } from './_shared'; import { - TOOL_ARG_PATH_KEYS, - TOOL_CALL_MAIN_ARG_KEYS, + createTracePhraser, + fileNameFromPath, + toolCallPath, + type ToolCallResolver +} from '@ggml-org/llama-harness'; +import { TOOL_CALL_PHRASING, - TOOL_CALL_SHOWN_ARG_DEFAULT, - TOOL_CALL_SIMPLE_ARG_MAX_CHARS, - TOOL_CALL_SUMMARY, - TOOL_CALL_TARGET_MAX_CHARS, - TOOL_CALL_THINKING_LABEL, TOOL_SEARCH_LOAD_PHRASING, TOOL_SEARCH_PHRASING_NAME, TOOL_SEARCH_PHRASING_SELECT_PREFIX, TOOL_SEARCH_QUERY_PHRASING, WEB_SEARCH_PHRASING } from '#lib/constants/index.ts'; -import { AgenticSectionType, BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts'; -import type { AgenticSection, ToolCallDescription, ToolCallPhrasing } from '#lib/types/index.ts'; -import { isWebSearchToolName, memoizeBounded, parsePartialJsonArgs } from '#lib/utils/index.ts'; - -/** How many results each cache below holds. */ -const CACHE_MAX_SIZE = 256; -/** Args longer than this ( whole files ) are not worth holding as cache keys. */ -const CACHE_MAX_ARGS_CHARS = 2000; - -type ToolArgField = { label: string; value: string }; - -function shorten(text: string): string { - const oneLine = text.replace(/\s+/g, ' ').trim(); - - return oneLine.length > TOOL_CALL_TARGET_MAX_CHARS - ? `${oneLine.slice(0, TOOL_CALL_TARGET_MAX_CHARS - 3)}...` - : oneLine; -} +import { BuiltInTool } from '#lib/enums/index.ts'; +import { isWebSearchToolName } from '#lib/utils/index.ts'; function stringArg(args: Record | null, key: string): string | undefined { const value = args?.[key]; @@ -46,92 +26,25 @@ function stringArg(args: Record | null, key: string): string | return typeof value === 'string' && value.trim() ? value : undefined; } -function genericMainArg(args: Record | null): string | undefined { - if (!args) return undefined; - - for (const key of TOOL_CALL_MAIN_ARG_KEYS) { - const value = stringArg(args, key); - - if (value) return value; - } - - for (const value of Object.values(args)) { - if (typeof value === 'number') return String(value); - - if (typeof value === 'string' && value.trim() && value.length <= TOOL_CALL_TARGET_MAX_CHARS) { - return value; - } - } - - return undefined; -} - -function genericPhrasing(toolName: string): ToolCallPhrasing { - return { - object: toolName, - past: 'Used', - present: 'Using', - summary: ToolCallSummaryKind.OTHER, - targetObject: toolName - }; -} - -interface ResolvedCall { - phrasing: ToolCallPhrasing; - target?: string; - count?: number; -} - -function resolveCall(toolName: string, toolArgs: string): ResolvedCall { - // write_file and edit_file args hold whole files: read the path with a - // targeted match instead of parsing the blob - if ( - toolName === BuiltInTool.SERVER_READ_FILE || - toolName === BuiltInTool.SERVER_WRITE_FILE || - toolName === BuiltInTool.SERVER_EDIT_FILE || - toolName === BuiltInTool.BROWSER_READ_MEDIA - ) { - const path = - extractToolArgString(toolArgs, TOOL_ARG_PATH_KEYS) ?? - stringArg(parsePartialJsonArgs(toolArgs), 'path'); - - return { phrasing: TOOL_CALL_PHRASING[toolName], target: fileNameFromPath(path) }; - } - - const args = toolArgs ? parsePartialJsonArgs(toolArgs) : null; - - if (toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND) { - // the targeted match keeps the command in the line while a later arg - // is still streaming and the JSON does not parse - return { - phrasing: TOOL_CALL_PHRASING[toolName], - target: stringArg(args, 'command') ?? extractToolArgString(toolArgs, ['command']) - }; - } - - switch (toolName) { - case BuiltInTool.SERVER_GREP_SEARCH: - return { phrasing: TOOL_CALL_PHRASING[toolName], target: stringArg(args, 'pattern') }; - - case BuiltInTool.SERVER_FILE_GLOB_SEARCH: { - const include = stringArg(args, 'include'); - +const chatToolResolver: ToolCallResolver = (call) => { + switch (call.name) { + case BuiltInTool.BROWSER_READ_MEDIA: return { - phrasing: TOOL_CALL_PHRASING[toolName], - target: include && include !== '**' ? include : undefined + phrasing: TOOL_CALL_PHRASING[call.name], + target: fileNameFromPath(toolCallPath(call)) }; - } case BuiltInTool.BROWSER_SEARCH_CHATS: { - const matches = Array.isArray(args?.by_matches) - ? args.by_matches.filter((m): m is string => typeof m === 'string' && m.trim() !== '') + const byMatches = call.args()?.by_matches; + const matches = Array.isArray(byMatches) + ? byMatches.filter((m): m is string => typeof m === 'string' && m.trim() !== '') : []; - return { phrasing: TOOL_CALL_PHRASING[toolName], target: matches.join(', ') || undefined }; + return { phrasing: TOOL_CALL_PHRASING[call.name], target: matches.join(', ') || undefined }; } case TOOL_SEARCH_PHRASING_NAME: { - const query = stringArg(args, 'query')?.trim(); + const query = stringArg(call.args(), 'query')?.trim(); if (query?.startsWith(TOOL_SEARCH_PHRASING_SELECT_PREFIX)) { const names = query @@ -151,295 +64,14 @@ function resolveCall(toolName: string, toolArgs: string): ResolvedCall { } } - if (isWebSearchToolName(toolName)) { - return { phrasing: WEB_SEARCH_PHRASING, target: stringArg(args, 'query') }; - } - - const known = TOOL_CALL_PHRASING[toolName]; - - if (known) return { phrasing: known }; - - return { phrasing: genericPhrasing(toolName), target: genericMainArg(args) }; -} - -/** An arg name the settings can pick: a plain key, so it is safe in a pattern. */ -const SHOWN_ARG_PATTERN = /^[\w-]+$/; - -/** - * The value of the arg a call's line shows, when the call has it. Whole-file - * args are not parsed for it: the targeted match reads it instead. - */ -function shownArgValue(toolArgs: string, shownArg: string | null): string | undefined { - if (!shownArg || !toolArgs || !SHOWN_ARG_PATTERN.test(shownArg)) return undefined; - - const value = - toolArgs.length <= CACHE_MAX_ARGS_CHARS - ? stringArg(parsePartialJsonArgs(toolArgs), shownArg) - : extractToolArgString(toolArgs, [shownArg]); - - return value?.trim() || undefined; -} - -/** - * Describe one tool call as a short sentence, in the past tense once it is - * done and the present tense while `running`. `shownArg` names the arg - * shown instead when the call has it ( null for none ). - */ -export function describeToolCall( - toolName: string | undefined, - toolArgs: string | undefined, - running = false, - shownArg: string | null = TOOL_CALL_SHOWN_ARG_DEFAULT -): ToolCallDescription { - return describeCached(toolName || 'a tool', toolArgs ?? '', running, shownArg ?? ''); -} - -// Sections are rebuilt on every streamed chunk, so the same finished call is -// described again and again: remember the answer for its args. Every caller -// of one call reads the same frozen object, so a title cannot edit the line -// out for the others. -const describeCached = memoizeBounded( - (name: string, args: string, running: boolean, shownArg: string) => - Object.freeze(buildDescription(name, args, running, shownArg || null)), - (name, args, running, shownArg) => - args.length <= CACHE_MAX_ARGS_CHARS - ? `${running ? 1 : 0}\0${shownArg}\0${name}\0${args}` - : null, - CACHE_MAX_SIZE -); - -function buildDescription( - name: string, - args: string, - running: boolean, - shownArg: string | null -): ToolCallDescription { - const { count = 1, phrasing, target } = resolveCall(name, args); - const shown = shownArgValue(args, shownArg); - // an arg the row already shows as its target ( a shell command ) would - // only repeat it - const described = shown && shown !== target?.trim() ? shown : undefined; - - if (described) { - return { - count, - described: true, - // shown as the model wrote it: rewriting its tense by rule mangles - // anything that does not start with a plain verb - label: shorten(described).replace(/[.\s]+$/, ''), - quoted: false, - summary: phrasing.summary - }; - } - - const verb = running ? phrasing.present : phrasing.past; - const shortTarget = target ? shorten(target) : undefined; - const object = shortTarget ? phrasing.targetObject : phrasing.object; - - return { - count, - label: object ? `${verb} ${object}` : verb, - quoted: Boolean(phrasing.quoteTarget && shortTarget), - summary: phrasing.summary, - target: shortTarget - }; -} - -/** One line of plain text for a description, e.g. `Searched for 'issue'`. */ -export function formatToolCallLine(description: ToolCallDescription): string { - if (!description.target) return description.label; - - const target = description.quoted ? `'${description.target}'` : description.target; - - return `${description.label} ${target}`; -} - -export function isToolCallSection(section: AgenticSection): boolean { - return ( - section.type === AgenticSectionType.TOOL_CALL || - section.type === AgenticSectionType.TOOL_CALL_PENDING || - section.type === AgenticSectionType.TOOL_CALL_STREAMING - ); -} - -/** True while the call has no result yet and the reply is still streaming. */ -export function isToolCallRunning(section: AgenticSection, isStreaming: boolean): boolean { - return ( - isStreaming && - (section.type === AgenticSectionType.TOOL_CALL_PENDING || - section.type === AgenticSectionType.TOOL_CALL_STREAMING) - ); -} - -/** - * Summarize a run of tool calls, e.g. "Ran 3 commands, read 2 files". - * Kinds keep the order they first appear in; other tools come last. - */ -export function summarizeToolCalls(sections: readonly AgenticSection[]): string { - const counts = new Map(); - - for (const section of sections) { - if (!isToolCallSection(section)) continue; - - const { count, summary } = describeToolCall(section.toolName, section.toolArgs); - - counts.set(summary, (counts.get(summary) ?? 0) + count); - } - - const other = counts.get(ToolCallSummaryKind.OTHER); - - if (other !== undefined) { - counts.delete(ToolCallSummaryKind.OTHER); - counts.set(ToolCallSummaryKind.OTHER, other); - } - - const clauses = [...counts].map(([kind, n]) => TOOL_CALL_SUMMARY[kind](n)); - const text = clauses.join(', '); - - return text.charAt(0).toUpperCase() + text.slice(1); -} - -/** - * What a run of calls is doing now, in user words ("Running a command", - * "Thinking"): the model thinking at its end, or the last call still - * running; null when neither is. - */ -export function describeToolActivity( - sections: readonly AgenticSection[], - isStreaming: boolean, - executingToolCallId?: string | null, - shownArgFor: (toolName: string | undefined) => string | null = () => TOOL_CALL_SHOWN_ARG_DEFAULT -): string | null { - // the model thinking at the end of the run, between calls or before its answer - if (isStreaming && sections.at(-1)?.type === AgenticSectionType.REASONING_PENDING) { - return TOOL_CALL_THINKING_LABEL; - } - - for (let i = sections.length - 1; i >= 0; i--) { - const section = sections[i]; - const executing = - section.toolCallId !== undefined && section.toolCallId === executingToolCallId; - - if (executing || isToolCallRunning(section, isStreaming)) { - return formatToolCallLine( - describeToolCall(section.toolName, section.toolArgs, true, shownArgFor(section.toolName)) - ); - } - } - - return null; -} - -/** - * Tool args as labelled fields when every value is a short, one-line - * scalar; null when the args need the JSON view instead. Memoized like - * describeToolCall: the row that shows them re-renders on every chunk. - */ -export function simpleToolArgFields(toolArgs: string | undefined): ToolArgField[] | null { - return toolArgs ? argFieldsCached(toolArgs) : null; -} - -const argFieldsCached = memoizeBounded( - buildSimpleToolArgFields, - (toolArgs) => (toolArgs.length <= CACHE_MAX_ARGS_CHARS ? toolArgs : null), - CACHE_MAX_SIZE -); - -function buildSimpleToolArgFields(toolArgs: string): ToolArgField[] | null { - let parsed: unknown; - - try { - parsed = JSON.parse(toolArgs); - } catch { - return null; - } - - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; - - const entries = Object.entries(parsed as Record); - - if (entries.length === 0) return null; - - const fields: ToolArgField[] = []; - - for (const [key, value] of entries) { - if (value !== null && typeof value === 'object') return null; - - const text = String(value); - - if (text.length > TOOL_CALL_SIMPLE_ARG_MAX_CHARS || text.includes('\n')) return null; - - fields.push({ label: humanizeArgKey(key), value: text }); + if (isWebSearchToolName(call.name)) { + return { phrasing: WEB_SEARCH_PHRASING, target: stringArg(call.args(), 'query') }; } - return fields; -} - -/** `max_results` / `maxResults` -> `Max results`. */ -export function humanizeArgKey(key: string): string { - const words = key - .replace(/([a-z0-9])([A-Z])/g, '$1 $2') - .replace(/[_-]+/g, ' ') - .trim() - .toLowerCase(); - - return words.charAt(0).toUpperCase() + words.slice(1); -} - -export function isReasoningSection(section: AgenticSection): boolean { - return ( - section.type === AgenticSectionType.REASONING || - section.type === AgenticSectionType.REASONING_PENDING - ); -} - -/** - * Split section positions into single items and runs of tool work, e.g. - * [0, [1, 2, 3], 4]. A run is the calls and all the reasoning around them, - * up to the next text, so the answer follows the work as one row: it is - * grouped once it holds `minCalls` calls, or one call with reasoning beside - * it. Reasoning with no call in reach, and text, stay apart. - */ -export function groupToolCallRuns( - sections: readonly AgenticSection[], - indices: readonly number[], - minCalls: number -): (number | number[])[] { - const items: (number | number[])[] = []; - - let run: number[] = []; - let calls = 0; - // reasoning seen since the last call: it ends the run if text follows, - // and leads into it if another call does - let thinking: number[] = []; - - const flush = () => { - const whole = [...run, ...thinking]; - - if (calls >= minCalls || (calls > 0 && whole.length > calls)) items.push(whole); - else items.push(...whole); - - run = []; - thinking = []; - calls = 0; - }; - - for (const index of indices) { - const section = sections[index]; - - if (isToolCallSection(section)) { - run.push(...thinking, index); - thinking = []; - calls++; - } else if (isReasoningSection(section)) { - thinking.push(index); - } else { - flush(); - items.push(index); - } - } - - flush(); + return undefined; +}; - return items; -} +export const { describeToolActivity, describeToolCall, summarizeToolCalls } = createTracePhraser({ + phrasings: TOOL_CALL_PHRASING, + resolvers: [chatToolResolver] +}); diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts index 3a88fb5f9f21..63557211c5c4 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/write-file.ts @@ -4,12 +4,8 @@ // result blob. The path is display-only (title + highlight language), // so a call that has not streamed one still shows its content. -import { - extractToolArgPath, - extractToolArgString, - fileNameFromPath, - parseToolArgs -} from './_shared'; +import { extractToolArgPath, parseToolArgs } from './_shared'; +import { extractToolArgString, fileNameFromPath } from '@ggml-org/llama-harness'; import { CODE_BLOCK, TOOL_ARG_PATH_KEYS } from '#lib/constants/index.ts'; import { BuiltInTool } from '#lib/enums/index.ts'; import type { AgenticSection, WriteFileMeta, WriteFileTitleMeta } from '#lib/types/index.ts'; diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte index f0e7bffde8dd..988cb11d9afa 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessageAgentTrace.svelte @@ -2,12 +2,9 @@ import ChatMessageToolCallBlock from './ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlock.svelte'; import ChatMessageToolCallGroup from './ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte'; import { parseExecShellCommandMeta } from './ChatMessage/ChatMessageToolCall/parsers/exec-shell-command'; - import { - groupToolCallRuns, - isToolCallSection - } from './ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing'; import { setToolCallElapsedContext } from './ChatMessage/ChatMessageToolCall/tool-call-elapsed'; import ChatMessageReasoningBlock from './ChatMessageReasoningBlock.svelte'; + import { groupToolCallRuns, isToolCallStep } from '@ggml-org/llama-harness'; import { ChatMessageActionCardContinueRequest, ChatMessageActionCardPermissionRequest, @@ -168,7 +165,7 @@ result.push(groupToolCallRuns(sections, indices, TOOL_CALL_GROUP_MIN_CALLS)); for (let i = 0; i < sections.length; i++) { - const isTool = isToolCallSection(sections[i]); + const isTool = isToolCallStep(sections[i]); // a turn ends where its tool calls do if (!isTool && prevWasTool && indices.length > 0) { @@ -202,7 +199,7 @@ return toolCallId ? { startedAt: taskStartedAt, toolCallId } : null; }); - const lastToolIndex = $derived(sections.findLastIndex((section) => isToolCallSection(section))); + const lastToolIndex = $derived(sections.findLastIndex((section) => isToolCallStep(section))); // The status row shows only while nothing else in the reply is moving: a // running row, a permission card or streaming text already says what is diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts index 3109299c3feb..8182fb372575 100644 --- a/ui/apps/chat/src/lib/constants/settings.constants.ts +++ b/ui/apps/chat/src/lib/constants/settings.constants.ts @@ -4,9 +4,9 @@ import { COMPACTION } from './compaction.constants'; import { DEFAULT_MCP_CONFIG } from './mcp.constants'; import { SETTINGS_KEYS } from './settings-keys.constants'; import { TITLE_GENERATION } from './title-generation.constants'; -import { TOOL_CALL_SHOWN_ARG_DEFAULT } from './tool-call-phrasing.constants'; import { VOICE_TRANSCRIPTION_MODEL_AUTO } from './voice.constants'; import { FILE_GLOB_SEARCH_PICKERS } from './working-directory.constants'; +import { TOOL_CALL_SHOWN_ARG_DEFAULT } from '@ggml-org/llama-harness'; import { VOICE_MICROPHONE_AUTO } from '@ggml-org/llama-voice'; import AudioLines from '@lucide/svelte/icons/audio-lines'; import Code from '@lucide/svelte/icons/code'; diff --git a/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts b/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts index e74260be2993..47db87d725dc 100644 --- a/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-call-args.constants.ts @@ -13,11 +13,3 @@ export const JSON_OBJECT_OPEN = '{'; /** Opening character of a JSON array; successful sandbox output is one. */ export const JSON_ARRAY_OPEN = '['; - -/** - * Matches `"": ""` in a JSON args blob ( whitespace between - * tokens allowed ), capturing the raw string literal so only that literal - * gets decoded; escaped quotes stay inside the value group. `{key}` is - * replaced with the field name before use. - */ -export const TOOL_ARG_STRING_FIELD_PATTERN_TEMPLATE = '"{key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"'; diff --git a/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts b/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts index e811ee243b48..66d73a119fd0 100644 --- a/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-call-phrasing.constants.ts @@ -1,10 +1,9 @@ -// Plain-language phrasing for tool calls in the chat trace: the line each -// call reads as ("Read a file", "Searched for 'issue'"), the live -// description while it runs ("Reading package.json") and the counts in a -// group summary ("Ran 3 commands, read 2 files"). +// Phrasing of Llama Chat's own tools in the chat trace: the browser tools, web +// search and tool_search. Llama Harness phrases llama-server's built-in tools +// and any other tool (see createTracePhraser). -import { BuiltInTool, ToolCallSummaryKind } from '#lib/enums/index.ts'; -import type { ToolCallPhrasing } from '#lib/types/index.ts'; +import { type ToolCallPhrasing, ToolCallSummaryKind } from '@ggml-org/llama-harness'; +import { BuiltInTool } from '#lib/enums/index.ts'; /** * A tool that loads tools on demand, and the `select:` prefix its query uses @@ -14,37 +13,13 @@ import type { ToolCallPhrasing } from '#lib/types/index.ts'; export const TOOL_SEARCH_PHRASING_NAME = 'tool_search'; export const TOOL_SEARCH_PHRASING_SELECT_PREFIX = 'select:'; -/** Longest target shown after the verb before it is cut with "...". */ -export const TOOL_CALL_TARGET_MAX_CHARS = 60; - /** Fewest consecutive tool calls that collapse into one group row. */ export const TOOL_CALL_GROUP_MIN_CALLS = 2; -/** Live title of a tool group while the model thinks inside it. */ -export const TOOL_CALL_THINKING_LABEL = 'Thinking'; - /** Status shown while a reply waits on the server and no finer status is known. */ export const REPLY_STATUS_FALLBACK = 'Processing...'; -/** Args a generic (MCP or unknown) tool call is described by, first match wins. */ -export const TOOL_CALL_MAIN_ARG_KEYS: readonly string[] = [ - 'query', - 'q', - 'path', - 'file_path', - 'filePath', - 'url', - 'name', - 'command', - 'pattern', - 'prompt', - 'text', - 'id' -]; - -/** Args that count as "simple" stay below this length and on one line. */ -export const TOOL_CALL_SIMPLE_ARG_MAX_CHARS = 200; - +/** Llama Chat's browser tools; llama-server's tools are phrased by Llama Harness. */ export const TOOL_CALL_PHRASING: Readonly> = { // its own row reads "Current time is ...", so this entry serves group titles [BuiltInTool.BROWSER_GET_DATETIME]: { @@ -72,52 +47,6 @@ export const TOOL_CALL_PHRASING: Readonly> = { quoteTarget: true, summary: ToolCallSummaryKind.SEARCH, targetObject: 'chats for' - }, - [BuiltInTool.SERVER_EDIT_FILE]: { - object: 'a file', - past: 'Edited', - present: 'Editing', - summary: ToolCallSummaryKind.EDIT - }, - [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { - object: 'a command', - past: 'Ran', - present: 'Running', - summary: ToolCallSummaryKind.COMMAND - }, - [BuiltInTool.SERVER_FILE_GLOB_SEARCH]: { - object: 'files', - past: 'Listed', - present: 'Listing', - quoteTarget: true, - summary: ToolCallSummaryKind.SEARCH, - targetObject: 'files matching' - }, - [BuiltInTool.SERVER_GET_INFO]: { - object: 'runtime info', - past: 'Checked', - present: 'Checking', - summary: ToolCallSummaryKind.OTHER - }, - [BuiltInTool.SERVER_GREP_SEARCH]: { - object: 'files', - past: 'Searched', - present: 'Searching', - quoteTarget: true, - summary: ToolCallSummaryKind.SEARCH, - targetObject: 'for' - }, - [BuiltInTool.SERVER_READ_FILE]: { - object: 'a file', - past: 'Read', - present: 'Reading', - summary: ToolCallSummaryKind.READ - }, - [BuiltInTool.SERVER_WRITE_FILE]: { - object: 'a file', - past: 'Wrote', - present: 'Writing', - summary: ToolCallSummaryKind.WRITE } }; @@ -147,29 +76,5 @@ export const WEB_SEARCH_PHRASING: ToolCallPhrasing = { targetObject: 'the web for' }; -function counted(n: number, singular: string, plural: string): string { - return `${n} ${n === 1 ? singular : plural}`; -} - -/** Group summary clause per kind, in lower case; the summary capitalizes the first one. */ -export const TOOL_CALL_SUMMARY: Readonly string>> = { - [ToolCallSummaryKind.COMMAND]: (n) => `ran ${counted(n, 'command', 'commands')}`, - [ToolCallSummaryKind.EDIT]: (n) => `edited ${counted(n, 'file', 'files')}`, - [ToolCallSummaryKind.LOAD_TOOLS]: (n) => `loaded ${counted(n, 'tool', 'tools')}`, - [ToolCallSummaryKind.OTHER]: (n) => `used ${counted(n, 'tool', 'tools')}`, - [ToolCallSummaryKind.READ]: (n) => `read ${counted(n, 'file', 'files')}`, - [ToolCallSummaryKind.SCRIPT]: (n) => `ran ${counted(n, 'script', 'scripts')}`, - [ToolCallSummaryKind.SEARCH]: (n) => (n === 1 ? 'searched once' : `searched ${n} times`), - [ToolCallSummaryKind.VIEW]: (n) => `viewed ${counted(n, 'media file', 'media files')}`, - [ToolCallSummaryKind.WRITE]: (n) => `wrote ${counted(n, 'file', 'files')}` -}; - -/** - * Arg a call's line shows by default when the call has it: tools that want a - * readable line declare it in their own schema, and the line reads it as the - * model wrote it. Settings can pick another arg, globally or per tool. - */ -export const TOOL_CALL_SHOWN_ARG_DEFAULT = 'description'; - /** Per-tool choice that turns the shown arg off and keeps the sentence. */ export const TOOL_CALL_SHOWN_ARG_NONE = ''; diff --git a/ui/apps/chat/src/lib/enums/agentic.enums.ts b/ui/apps/chat/src/lib/enums/agentic.enums.ts index 6dc46b0850ac..31f72bafd992 100644 --- a/ui/apps/chat/src/lib/enums/agentic.enums.ts +++ b/ui/apps/chat/src/lib/enums/agentic.enums.ts @@ -43,3 +43,35 @@ export enum DiffLineKind { CONTEXT = 'context', REMOVE = 'remove' } + +/** + * Events of a harness run. The values mirror `HarnessEvent` of `@ggml-org/llama-harness`. + */ +export enum HarnessEventType { + COMPLETION_ID = 'completion_id', + DONE = 'done', + ERROR = 'error', + MESSAGE = 'message', + MODEL = 'model', + REASONING = 'reasoning', + TEXT = 'text', + TIMINGS = 'timings', + TOOL_CALL = 'tool_call', + TOOL_CALL_DELTA = 'tool_call_delta', + TOOL_RESULT = 'tool_result', + TOOL_UPDATE = 'tool_update', + TURN_END = 'turn_end', + TURN_START = 'turn_start' +} + +/** + * Events of one streamed completion. The values mirror `InferenceEvent` of `@ggml-org/llama-harness`. + */ +export enum InferenceEventType { + COMPLETION_ID = 'completion_id', + MODEL = 'model', + REASONING = 'reasoning', + TEXT = 'text', + TIMINGS = 'timings', + TOOL_CALLS = 'tool_calls' +} diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 9fb53f8af05c..510e3d18fb7a 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -10,6 +10,8 @@ export { AgenticSectionType, ContinueIntentKind, DiffLineKind, + HarnessEventType, + InferenceEventType, ToolResultKind, ToolCallType } from './agentic.enums'; @@ -116,7 +118,6 @@ export { GlobSearchType, SearchChatsMessageSelection, SearchChatsOrder, - ToolCallSummaryKind, ToolSource, ToolPermissionDecision, ToolResponseField diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index 5049be5cb790..2bda6872284b 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -67,16 +67,3 @@ export enum SearchChatsOrder { ASC = 'asc', DESC = 'desc' } - -/** Bucket a tool call counts in for a tool-call group's summary line. */ -export enum ToolCallSummaryKind { - COMMAND = 'command', - EDIT = 'edit', - LOAD_TOOLS = 'load_tools', - OTHER = 'other', - READ = 'read', - SCRIPT = 'script', - SEARCH = 'search', - VIEW = 'view', - WRITE = 'write' -} diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts index b4e0fa335179..602d49bfb367 100644 --- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts @@ -1,15 +1,26 @@ /** - * AgenticStore - Multi-turn agentic loop orchestration + * AgenticStore - Llama Chat's side of the agentic loop * - * Drives the agentic loop over MCP tools: streams each LLM turn, detects - * tool calls, executes them via mcpStore, and enforces the turn limit. Each - * turn produces one assistant message (with tool_calls) and one tool result - * message per executed call, persisted as separate DB rows. + * The loop itself is `@ggml-org/llama-harness`: it streams each LLM turn, runs + * the tool calls and enforces the turn limit. This store gives it what the + * app owns: ChatService as its inference client, the enabled tools behind + * the permission gate, and the callbacks that persist each turn as one + * assistant message (with tool_calls) and one tool result message per call. * - * Uses ChatService for streaming and mcpStore for tool execution; waits on - * the permission/continue/steering gates owned by {@link AgenticGates}. + * Waits on the permission/continue/steering gates owned by {@link AgenticGates}. */ +import { + type ContentPart, + createHarness, + type InferenceClient, + type InferenceEvent, + type Message, + type Tool, + type ToolCall, + type ToolContext, + type ToolResult +} from '@ggml-org/llama-harness'; import { DEFAULT_AGENTIC_CONFIG, NEWLINE } from '#lib/constants/index.ts'; import { AUDIO_MIME_TO_EXTENSION, @@ -24,6 +35,8 @@ import { BuiltInTool, ToolPermissionDecision, ToolSource } from '#lib/enums/inde import { AttachmentType, ContentPartType, + HarnessEventType, + InferenceEventType, MessageRole, MimeTypePrefix, ToolCallType @@ -44,25 +57,13 @@ import type { AgenticFlowCallbacks, AgenticFlowOptions, AgenticMessage, - AgenticToolCallList, AgenticToolPolicy, PendingPermissionRequest, SteeringMessage } from '#lib/types/agentic.js'; +import type { ApiChatMessageData } from '#lib/types/api.js'; +import type { ChatMessagePromptProgress, ChatMessageTimings } from '#lib/types/chat.js'; import type { - ApiChatCompletionToolCall, - ApiChatMessageContentPart, - ApiChatMessageData -} from '#lib/types/api.js'; -import type { - ChatMessageAgenticTimings, - ChatMessageAgenticTurnStats, - ChatMessagePromptProgress, - ChatMessageTimings, - ChatMessageToolCallTiming -} from '#lib/types/chat.js'; -import type { - DatabaseMessage, DatabaseMessageExtra, DatabaseMessageExtraAudioFile, DatabaseMessageExtraImageFile @@ -77,11 +78,13 @@ import type { ToolExecutionResult } from '#lib/types/index.ts'; import type { OpenAIToolDefinition } from '#lib/types/mcp.js'; +import { createAsyncQueue } from '#lib/utils/async-queue.ts'; import { executeBrowserInfoTool, executeGetDatetimeTool, getAudioInputFormat, - isAbortError + isAbortError, + throwIfAborted } from '#lib/utils/index.ts'; import { SvelteMap } from 'svelte/reactivity'; @@ -145,9 +148,14 @@ function toAgenticMessages(messages: ApiChatMessageData[]): AgenticMessage[] { }); } +/** The timings with the task's wall time since `startedAt` on its run totals, when it has them. */ +function withTotalTime(timings: T, startedAt: number): T { + if (!timings?.agentic) return timings; + + return { ...timings, agentic: { ...timings.agentic, totalMs: Date.now() - startedAt } }; +} + class AgenticStore { - /** When each running flow started, keyed by its timings object; see buildFinalTimings */ - private flowStarts = new WeakMap(); // permission, continue and steering gates the loop waits on between turns private gates = new AgenticGates(); private sessions = new SvelteMap(); @@ -416,27 +424,142 @@ class AgenticStore { return `${MCP_ATTACHMENT_NAME_PREFIX}-${Date.now()}-${index}.${extension}`; } - private buildFinalTimings( - capturedTimings: ChatMessageTimings | undefined, - agenticTimings: ChatMessageAgenticTimings - ): ChatMessageTimings | undefined { - if (agenticTimings.toolCallsCount === 0) return capturedTimings; + /** + * The media of a tool result as content parts, only what the model can read. + */ + private buildContentParts( + attachments: DatabaseMessageExtra[], + effectiveModel: string + ): ContentPart[] { + const contentParts: ContentPart[] = []; + + for (const attachment of attachments) { + if (attachment.type === AttachmentType.AUDIO) { + if (modelsStore.props.modelSupportsAudio(effectiveModel)) { + contentParts.push({ + input_audio: { + data: (attachment as DatabaseMessageExtraAudioFile).base64Data, + format: getAudioInputFormat((attachment as DatabaseMessageExtraAudioFile).mimeType) + }, + type: ContentPartType.INPUT_AUDIO + }); + } + } else if (attachment.type === AttachmentType.IMAGE) { + if (modelsStore.props.modelSupportsVision(effectiveModel)) { + contentParts.push({ + image_url: { + url: (attachment as DatabaseMessageExtraImageFile).base64Url + }, + type: ContentPartType.IMAGE_URL + }); + } else { + console.info( + `[AgenticStore] Skipping image attachment (model "${effectiveModel}" does not support vision)` + ); + } + } + } - const startedAt = this.flowStarts.get(agenticTimings); + return contentParts; + } - return { - agentic: - startedAt === undefined - ? agenticTimings - : { ...agenticTimings, totalMs: Date.now() - startedAt }, - cache_n: capturedTimings?.cache_n, - predicted_ms: capturedTimings?.predicted_ms, - predicted_n: capturedTimings?.predicted_n, - prompt_ms: capturedTimings?.prompt_ms, - prompt_n: capturedTimings?.prompt_n + /** + * Run a tool call where its source runs it: on llama-server, in the + * browser or on an MCP server. Throws when the call fails. + */ + private async dispatchTool(params: { + callbacks: AgenticFlowCallbacks; + context: ToolContext; + conversationId: string; + effectiveModel: string; + toolCall: ToolCall; + }): Promise { + const { callbacks, context, conversationId, effectiveModel, toolCall } = params; + const { signal } = context; + const toolName = toolCall.function.name; + const toolSource = toolsStore.getToolSource(toolName); + + if ( + toolSource === ToolSource.SERVER && + toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND && + callbacks.createToolResultMessage && + callbacks.updateToolResultMessage + ) { + const args = this.parseToolArguments(toolCall.function.arguments); + const cwd = conversationsStore.activeConversation?.cwd; + + // the first update creates the result message, so the output shows live + context.update(''); + + let accumulated = ''; + let isError = false; + + for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) { + if (ev.chunk !== null) { + accumulated += ev.chunk; + context.update(accumulated); + } + + if (ev.done) { + if (ev.error) { + accumulated = accumulated ? `${accumulated}\nError: ${ev.error}` : `Error: ${ev.error}`; + context.update(accumulated); + isError = true; + } + + break; + } + } + + return { content: accumulated, isError }; + } + + if (toolSource === ToolSource.SERVER) { + const args = this.parseToolArguments(toolCall.function.arguments); + const cwd = conversationsStore.activeConversation?.cwd; + + return ToolsService.executeTool(toolName, args, signal, cwd); + } + + if (toolSource === ToolSource.BROWSER) { + const args = this.parseToolArguments(toolCall.function.arguments); + + if (toolName === BuiltInTool.BROWSER_GET_DATETIME) return executeGetDatetimeTool(); + + if (toolName === BuiltInTool.SERVER_GET_INFO) return executeBrowserInfoTool(); + + if (toolName === BuiltInTool.BROWSER_SEARCH_CHATS) { + return SearchChatsService.executeTool(args, conversationId); + } + + if (toolName === BuiltInTool.BROWSER_READ_MEDIA) { + return ReadMediaService.executeTool( + args, + { + audio: modelsStore.props.modelSupportsAudio(effectiveModel), + vision: modelsStore.props.modelSupportsVision(effectiveModel) + }, + signal, + conversationsStore.activeConversation?.cwd + ); + } + + return SandboxService.executeTool(toolName, args, signal); + } + + const mcpCall: MCPToolCall = { + function: { arguments: toolCall.function.arguments, name: toolName }, + id: toolCall.id }; + const executionResult = await mcpStore.executeTool(mcpCall, signal); + + return { content: executionResult.content, isError: false }; } + /** + * Run the harness and turn its events into the flow's callbacks and the + * session state the UI reads. + */ private async executeAgenticLoop(params: { conversationId: string; messages: ApiChatMessageData[]; @@ -462,551 +585,255 @@ class AgenticStore { onTurnComplete, updateToolResultMessage } = callbacks; - const sessionMessages: AgenticMessage[] = toAgenticMessages(messages); - - let capturedTimings: ChatMessageTimings | undefined; - let totalToolCallCount = 0; - - const agenticTimings: ChatMessageAgenticTimings = { - llm: { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }, - perTurn: [], - toolCalls: [], - toolCallsCount: 0, - toolsMs: 0, - turns: 0 - }; - - // the run's start travels with its timings, so every exit of the loop - // stamps the total task time without being handed it - this.flowStarts.set(agenticTimings, this.sessions.get(conversationId)?.startedAt ?? Date.now()); - - const maxTurns = agenticConfig.maxTurns; + // the task's wall time, waits included, is stamped on every timings the run reports + const startedAt = this.sessions.get(conversationId)?.startedAt ?? Date.now(); const effectiveModel = options.model || modelsStore.models[0]?.model || ''; - - let turn = 0; - - while (true) { - if (turn >= maxTurns) { + const harness = createHarness(this.inferenceClient(options, conversationId)); + const harnessTools: Tool[] = tools.map((definition) => ({ + definition, + execute: (toolCall, context) => + this.executeTool({ callbacks, context, conversationId, effectiveModel, toolCall }) + })); + // result messages of streaming tools, created while the tool runs, by tool call id + const streamedResults = new SvelteMap(); + const events = harness.run(toAgenticMessages(messages) as Message[], harnessTools, signal, { + interrupted: () => this.gates.hasPendingSteeringMessage(conversationId), + maxTurns: agenticConfig.maxTurns, + onTurnLimit: async () => { // Turn limit reached - ask user whether to continue const shouldContinue = await this.gates.requestContinue(conversationId, signal); // Yield to allow Svelte to flush the UI update await new Promise((r) => setTimeout(r, 0)); - if (!shouldContinue || signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // User chose to continue - extend the limit - turn = 0; - } - - this.updateSession(conversationId, { currentTurn: turn + 1 }); - agenticTimings.turns = turn + 1; - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // For turns > 0, create a new assistant message via callback - if (turn > 0 && createAssistantMessage) { - await createAssistantMessage(); + return shouldContinue; } + }); - let turnContent = ''; - let turnReasoningContent = ''; - let turnToolCalls: ApiChatCompletionToolCall[] = []; - let lastStreamingToolCallName = ''; - let lastStreamingToolCallArgsLength = 0; - let turnTimings: ChatMessageTimings | undefined; - - const turnStats: ChatMessageAgenticTurnStats = { - llm: { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }, - toolCalls: [], - toolsMs: 0, - turn: turn + 1 - }; - - try { - await ChatService.sendMessage( - sessionMessages as ApiChatMessageData[], - { - ...options, - onChunk: (chunk: string) => { - turnContent += chunk; - onChunk?.(chunk); - }, - onComplete: () => { - /* Completion handled after sendMessage resolves */ - }, - onCompletionId, - onError: (error: Error) => { - throw error; - }, - onModel, - onReasoningChunk: (chunk: string) => { - turnReasoningContent += chunk; - onReasoningChunk?.(chunk); - }, - onTimings: (timings?: ChatMessageTimings, progress?: ChatMessagePromptProgress) => { - onTimings?.(timings, progress); - - if (timings) { - capturedTimings = timings; - turnTimings = timings; - - // completed turns + in-flight turn live counts - this.updateSession(conversationId, { - liveLlm: { - predicted_ms: agenticTimings.llm.predicted_ms + (timings.predicted_ms ?? 0), - predicted_n: agenticTimings.llm.predicted_n + (timings.predicted_n ?? 0), - prompt_ms: agenticTimings.llm.prompt_ms + (timings.prompt_ms ?? 0), - prompt_n: agenticTimings.llm.prompt_n + (timings.prompt_n ?? 0) - } - }); - } - }, - onToolCallChunk: (serialized: string) => { - try { - turnToolCalls = JSON.parse(serialized) as ApiChatCompletionToolCall[]; - - onToolCallsStreaming?.(turnToolCalls); - - if (turnToolCalls.length > 0 && turnToolCalls[0]?.function) { - const name = turnToolCalls[0].function.name || ''; - const args = turnToolCalls[0].function.arguments || ''; - const argsLengthBucket = Math.floor(args.length / 100); - - if ( - name !== lastStreamingToolCallName || - argsLengthBucket !== lastStreamingToolCallArgsLength - ) { - lastStreamingToolCallName = name; - lastStreamingToolCallArgsLength = argsLengthBucket; - this.updateSession(conversationId, { - streamingToolCall: { arguments: args, name } - }); - } - } - } catch { - /* Ignore parse errors during streaming */ - } - }, - stream: true, - tools: tools.length > 0 ? tools : undefined - }, - conversationId, - signal - ); - - this.updateSession(conversationId, { streamingToolCall: null }); - - if (turnTimings) { - agenticTimings.llm.predicted_n += turnTimings.predicted_n || 0; - agenticTimings.llm.predicted_ms += turnTimings.predicted_ms || 0; - agenticTimings.llm.prompt_n += turnTimings.prompt_n || 0; - agenticTimings.llm.prompt_ms += turnTimings.prompt_ms || 0; - turnStats.llm.predicted_n = turnTimings.predicted_n || 0; - turnStats.llm.predicted_ms = turnTimings.predicted_ms || 0; - turnStats.llm.prompt_n = turnTimings.prompt_n || 0; - turnStats.llm.prompt_ms = turnTimings.prompt_ms || 0; - } - } catch (error) { - if (signal?.aborted) { - // Save whatever we have for this turn before exiting - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + let totalToolCallCount = 0; + let lastStreamingToolCallName = ''; + let lastStreamingToolCallArgsLength = 0; - return; - } + for await (const event of events) { + switch (event.type) { + case HarnessEventType.TURN_START: + this.updateSession(conversationId, { currentTurn: event.turn }); + lastStreamingToolCallName = ''; + lastStreamingToolCallArgsLength = 0; - const normalizedError = error instanceof Error ? error : new Error('LLM stream error'); + // the caller created the first turn's assistant message + if (event.turn > 1 && createAssistantMessage) await createAssistantMessage(); - // preserve partial output as is, the outer error dialog informs the user separately - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - throw normalizedError; - } + case HarnessEventType.TEXT: + onChunk?.(event.delta); - // If the abort landed while ChatService.sendMessage was still resolving, the - // outer catch above never fires because ChatService swallows the AbortError - // and returns normally. Bail out here so a half-received tool_call (truncated - // arguments JSON) is not persisted as if it were complete. - if (signal?.aborted) { - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - return; - } + case HarnessEventType.REASONING: + onReasoningChunk?.(event.delta); - // === Steering check: if a user message was queued during this turn, exit the flow. - // The caller (chatStore) will consume the pending message and re-send it normally. - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log('[AgenticStore] Steering message detected after turn, exiting agentic flow'); - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - turnToolCalls.length > 0 ? this.normalizeToolCalls(turnToolCalls) : undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - return; - } + case HarnessEventType.TOOL_CALL_DELTA: { + onToolCallsStreaming?.(event.toolCalls); - // No tool calls = final turn, save and complete - if (turnToolCalls.length === 0) { - agenticTimings.perTurn!.push(turnStats); + const streamingCall = event.toolCalls[0]?.function; - const finalTimings = this.buildFinalTimings(capturedTimings, agenticTimings); + if (streamingCall) { + const name = streamingCall.name || ''; + const args = streamingCall.arguments || ''; + const argsLengthBucket = Math.floor(args.length / 100); - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - finalTimings, - undefined - ); + if ( + name !== lastStreamingToolCallName || + argsLengthBucket !== lastStreamingToolCallArgsLength + ) { + lastStreamingToolCallName = name; + lastStreamingToolCallArgsLength = argsLengthBucket; + this.updateSession(conversationId, { + streamingToolCall: { arguments: args, name } + }); + } + } - if (finalTimings) onTurnComplete?.(finalTimings); + break; + } - onFlowComplete?.(finalTimings); + case HarnessEventType.TIMINGS: + onTimings?.(event.timings, event.progress); - return; - } + // completed turns + in-flight turn live counts + if (event.llm) this.updateSession(conversationId, { liveLlm: event.llm }); - // Normalize and save assistant turn with tool calls - const normalizedCalls = this.normalizeToolCalls(turnToolCalls); + break; - if (normalizedCalls.length === 0) { - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - this.buildFinalTimings(capturedTimings, agenticTimings), - undefined - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + case HarnessEventType.MODEL: + onModel?.(event.model); - return; - } + break; - totalToolCallCount += normalizedCalls.length; - this.updateSession(conversationId, { totalToolCalls: totalToolCallCount }); - - // Save the assistant message with its tool calls - await onAssistantTurnComplete?.( - turnContent, - turnReasoningContent || undefined, - turnTimings, - normalizedCalls - ); - - // Add assistant message to session history - sessionMessages.push({ - content: turnContent || undefined, - reasoning_content: turnReasoningContent || undefined, - role: MessageRole.ASSISTANT, - tool_calls: normalizedCalls - }); + case HarnessEventType.COMPLETION_ID: + onCompletionId?.(event.id); - // Execute each tool call and create result messages - for (let i = 0; i < normalizedCalls.length; i++) { - const toolCall = normalizedCalls[i]; + break; - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + case HarnessEventType.MESSAGE: + this.updateSession(conversationId, { streamingToolCall: null }); - return; - } + if (event.toolCalls && !event.final) { + totalToolCallCount += event.toolCalls.length; + this.updateSession(conversationId, { totalToolCalls: totalToolCallCount }); + } - // Check for pending steering message - skip remaining tool calls - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log( - `[AgenticStore] Steering message detected, skipping ${normalizedCalls.length - i} remaining tool call(s)` + await onAssistantTurnComplete?.( + event.content, + event.reasoning, + withTotalTime(event.timings, startedAt), + event.toolCalls ); - for (let j = i; j < normalizedCalls.length; j++) { - const remainingCall = normalizedCalls[j]; - const interruptedContent = 'Tool execution was interrupted by a new user message.'; - if (createToolResultMessage) { - await createToolResultMessage(remainingCall.id, interruptedContent); - } + break; - sessionMessages.push({ - content: interruptedContent, - role: MessageRole.TOOL, - tool_call_id: remainingCall.id + case HarnessEventType.TOOL_UPDATE: { + if (!createToolResultMessage || !updateToolResultMessage) break; + + const streamed = streamedResults.get(event.toolCall.id); + + if (streamed) { + streamed.content = event.content; + await updateToolResultMessage(streamed.messageId, event.content); + } else { + const message = await createToolResultMessage( + event.toolCall.id, + event.content, + undefined, + conversationsStore.activeConversation?.cwd + ); + + streamedResults.set(event.toolCall.id, { + content: event.content, + messageId: message.id }); } break; } - const toolName = toolCall.function.name; - const serverLabel = toolsStore.getToolServerLabel(toolName); - // Ask for permission before executing the tool - const permission = await this.gates.requestPermission( - conversationId, - toolName, - serverLabel, - toolCall.id, - signal - ); - - // Yield to allow Svelte to flush the UI update (hide permission dialog) - await new Promise((r) => setTimeout(r, 0)); - - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - const toolStartTime = performance.now(); - const toolSource = toolsStore.getToolSource(toolName); - - let result = ''; - let toolSuccess = true; - let createdToolResultMessageId: string | null = null; - - // Streaming tools (currently only exec_shell_command): mark - // the session so the matching renderer can switch to live mode. - // Cleared unconditionally below. - this.updateSession(conversationId, { executingToolCallId: toolCall.id }); - - if (permission === ToolPermissionDecision.DENY) { - result = 'Tool execution was denied by the user.'; - toolSuccess = false; - } else { - try { - if ( - toolSource === ToolSource.SERVER && - toolName === BuiltInTool.SERVER_EXEC_SHELL_COMMAND && - createToolResultMessage && - updateToolResultMessage - ) { - const args = this.parseToolArguments(toolCall.function.arguments); - const cwd = conversationsStore.activeConversation?.cwd; - const msg = await createToolResultMessage(toolCall.id, '', undefined, cwd); - - createdToolResultMessageId = msg.id; - - let accumulated = ''; - - for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) { - if (ev.chunk !== null) { - accumulated += ev.chunk; - await updateToolResultMessage(msg.id, accumulated); - } - - if (ev.done) { - if (ev.error) { - accumulated = accumulated - ? `${accumulated}\nError: ${ev.error}` - : `Error: ${ev.error}`; - await updateToolResultMessage(msg.id, accumulated); - toolSuccess = false; - } - - break; - } - } - result = accumulated; - } else if (toolSource === ToolSource.SERVER) { - const args = this.parseToolArguments(toolCall.function.arguments); - const cwd = conversationsStore.activeConversation?.cwd; - const executionResult = await ToolsService.executeTool(toolName, args, signal, cwd); - - result = executionResult.content; - - if (executionResult.isError) toolSuccess = false; - } else if (toolSource === ToolSource.BROWSER) { - const args = this.parseToolArguments(toolCall.function.arguments); - - let executionResult: ToolExecutionResult; - - if (toolName === BuiltInTool.BROWSER_GET_DATETIME) { - executionResult = executeGetDatetimeTool(); - } else if (toolName === BuiltInTool.SERVER_GET_INFO) { - executionResult = executeBrowserInfoTool(); - } else if (toolName === BuiltInTool.BROWSER_SEARCH_CHATS) { - executionResult = await SearchChatsService.executeTool(args, conversationId); - } else if (toolName === BuiltInTool.BROWSER_READ_MEDIA) { - executionResult = await ReadMediaService.executeTool( - args, - { - audio: modelsStore.props.modelSupportsAudio(effectiveModel), - vision: modelsStore.props.modelSupportsVision(effectiveModel) - }, - signal, - conversationsStore.activeConversation?.cwd - ); - } else { - executionResult = await SandboxService.executeTool(toolName, args, signal); - } - - result = executionResult.content; + case HarnessEventType.TOOL_RESULT: { + const { content } = event.result; + const attachments = (event.result.details as DatabaseMessageExtra[] | undefined) ?? []; + const extras = attachments.length > 0 ? attachments : undefined; + const streamed = streamedResults.get(event.toolCall.id); - if (executionResult.isError) toolSuccess = false; - } else { - const mcpCall: MCPToolCall = { - function: { arguments: toolCall.function.arguments, name: toolName }, - id: toolCall.id - }; - const executionResult = await mcpStore.executeTool(mcpCall, signal); + let toolResultMessageId: string | undefined; - result = executionResult.content; - } - } catch (error) { - if (isAbortError(error)) { - this.updateSession(conversationId, { executingToolCallId: null }); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); - - return; - } - - // Carry the partial stream contents already mirrored to the UI - - // they show up as live output even if the stream broke off mid-run. - result = result - ? `${result}\nError: ${error instanceof Error ? error.message : String(error)}` - : `Error: ${error instanceof Error ? error.message : String(error)}`; - toolSuccess = false; + if (streamed) { + toolResultMessageId = streamed.messageId; - if (createdToolResultMessageId && updateToolResultMessage) { - await updateToolResultMessage(createdToolResultMessageId, result); + // the message already shows the streamed output: rewrite it only when the result differs + if (extras || content !== streamed.content) { + await updateToolResultMessage?.(streamed.messageId, content, extras); } + } else if (createToolResultMessage) { + toolResultMessageId = ( + await createToolResultMessage(event.toolCall.id, content, extras) + ).id; } - } - this.updateSession(conversationId, { executingToolCallId: null }); + if (extras && toolResultMessageId) onAttachments?.(toolResultMessageId, extras); - const toolDurationMs = performance.now() - toolStartTime; - const toolTiming: ChatMessageToolCallTiming = { - duration_ms: Math.round(toolDurationMs), - name: toolCall.function.name, - success: toolSuccess - }; + break; + } - agenticTimings.toolCalls!.push(toolTiming); - agenticTimings.toolCallsCount++; - agenticTimings.toolsMs += Math.round(toolDurationMs); - turnStats.toolCalls.push(toolTiming); - turnStats.toolsMs += Math.round(toolDurationMs); + case HarnessEventType.TURN_END: + onTurnComplete?.(withTotalTime(event.timings, startedAt)); - if (signal?.aborted) { - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + break; - return; - } + case HarnessEventType.DONE: + onFlowComplete?.(withTotalTime(event.timings, startedAt)); - const { attachments, cleanedResult } = this.extractBase64Attachments(result); + break; - // For streaming tools the result message was created empty - // at the start of execution and updated in place as chunks - // arrived via updateToolResultMessage. Skip the second - // create call - just attach any base64 attachments found in - // the final accumulator (rare, since chunks usually don't - // carry image data URIs) and emit the attachments callback. - let toolResultMessage: DatabaseMessage | undefined; + case HarnessEventType.ERROR: + onFlowComplete?.(withTotalTime(event.timings, startedAt)); - if (createdToolResultMessageId) { - toolResultMessage = { id: createdToolResultMessageId } as DatabaseMessage; + throw event.error; + } + } + } - if (attachments.length > 0 && updateToolResultMessage) { - await updateToolResultMessage(createdToolResultMessageId, cleanedResult, attachments); - } - } else if (createToolResultMessage) { - toolResultMessage = await createToolResultMessage( - toolCall.id, - cleanedResult, - attachments.length > 0 ? attachments : undefined - ); - } + /** + * A tool of the harness: the permission gate, then the call, then the + * result with its media taken out of the text. + */ + private async executeTool(params: { + callbacks: AgenticFlowCallbacks; + context: ToolContext; + conversationId: string; + effectiveModel: string; + toolCall: ToolCall; + }): Promise { + const { callbacks, context, conversationId, effectiveModel, toolCall } = params; + const toolName = toolCall.function.name; + const serverLabel = toolsStore.getToolServerLabel(toolName); + // Ask for permission before executing the tool + const permission = await this.gates.requestPermission( + conversationId, + toolName, + serverLabel, + toolCall.id, + context.signal + ); - if (attachments.length > 0 && toolResultMessage) { - onAttachments?.(toolResultMessage.id, attachments); - } + // Yield to allow Svelte to flush the UI update (hide permission dialog) + await new Promise((r) => setTimeout(r, 0)); - // Build content parts for session history (including images for vision models) - const contentParts: ApiChatMessageContentPart[] = [ - { text: cleanedResult, type: ContentPartType.TEXT } - ]; - - for (const attachment of attachments) { - if (attachment.type === AttachmentType.AUDIO) { - if (modelsStore.props.modelSupportsAudio(effectiveModel)) { - contentParts.push({ - input_audio: { - data: (attachment as DatabaseMessageExtraAudioFile).base64Data, - format: getAudioInputFormat( - (attachment as DatabaseMessageExtraAudioFile).mimeType - ) - }, - type: ContentPartType.INPUT_AUDIO - }); - } - } else if (attachment.type === AttachmentType.IMAGE) { - if (modelsStore.props.modelSupportsVision(effectiveModel)) { - contentParts.push({ - image_url: { - url: (attachment as DatabaseMessageExtraImageFile).base64Url - }, - type: ContentPartType.IMAGE_URL - }); - } else { - console.info( - `[AgenticStore] Skipping image attachment (model "${effectiveModel}" does not support vision)` - ); - } - } - } + throwIfAborted(context.signal); - sessionMessages.push({ - content: contentParts.length === 1 ? cleanedResult : contentParts, - role: MessageRole.TOOL, - tool_call_id: toolCall.id - }); - } + // the time waiting for permission does not count + const toolStartTime = performance.now(); - if (turnStats.toolCalls.length > 0) { - agenticTimings.perTurn!.push(turnStats); + let execution: ToolExecutionResult; - const intermediateTimings = this.buildFinalTimings(capturedTimings, agenticTimings); + // Streaming tools (currently only exec_shell_command): mark + // the session so the matching renderer can switch to live mode. + this.updateSession(conversationId, { executingToolCallId: toolCall.id }); - if (intermediateTimings) onTurnComplete?.(intermediateTimings); - } + try { + execution = + permission === ToolPermissionDecision.DENY + ? { content: 'Tool execution was denied by the user.', isError: true } + : await this.dispatchTool({ + callbacks, + context, + conversationId, + effectiveModel, + toolCall + }); + } catch (error) { + if (isAbortError(error)) throw error; - // If tools were interrupted by a steering message, exit now instead of starting another LLM turn - if (this.gates.hasPendingSteeringMessage(conversationId)) { - console.log( - '[AgenticStore] Steering message detected after tool execution, exiting agentic flow' - ); - onFlowComplete?.(this.buildFinalTimings(capturedTimings, agenticTimings)); + execution = { + content: `Error: ${error instanceof Error ? error.message : String(error)}`, + isError: true + }; + } finally { + this.updateSession(conversationId, { executingToolCallId: null }); + } - return; - } + const durationMs = performance.now() - toolStartTime; + const { attachments, cleanedResult } = this.extractBase64Attachments(execution.content); - turn++; - } + return { + content: cleanedResult, + details: attachments, + durationMs, + isError: execution.isError, + parts: this.buildContentParts(attachments, effectiveModel) + }; } private extractBase64Attachments(result: string): { @@ -1064,17 +891,57 @@ class AgenticStore { return { attachments, cleanedResult: cleanedLines.join(NEWLINE) }; } - private normalizeToolCalls(toolCalls: ApiChatCompletionToolCall[]): AgenticToolCallList { - if (!toolCalls) return []; + /** + * ChatService as the harness's inference client: one streamed completion + * per turn, its callbacks turned into events. + */ + private inferenceClient(options: AgenticFlowOptions, conversationId: string): InferenceClient { + return { + stream: ({ messages, signal, tools }) => { + const events = createAsyncQueue(); - return toolCalls.map((call, index) => ({ - function: { - arguments: call?.function?.arguments ?? '', - name: call?.function?.name ?? '' - }, - id: call?.id ?? `tool_${index}`, - type: (call?.type as ToolCallType.FUNCTION) ?? ToolCallType.FUNCTION - })); + ChatService.sendMessage( + messages as ApiChatMessageData[], + { + ...options, + onChunk: (chunk: string) => + events.push({ delta: chunk, type: InferenceEventType.TEXT }), + onComplete: () => { + /* Completion handled after sendMessage resolves */ + }, + onCompletionId: (id: string) => + events.push({ id, type: InferenceEventType.COMPLETION_ID }), + onError: (error: Error) => { + throw error; + }, + onModel: (model: string) => events.push({ model, type: InferenceEventType.MODEL }), + onReasoningChunk: (chunk: string) => + events.push({ delta: chunk, type: InferenceEventType.REASONING }), + onTimings: (timings?: ChatMessageTimings, progress?: ChatMessagePromptProgress) => + events.push({ progress, timings, type: InferenceEventType.TIMINGS }), + onToolCallChunk: (serialized: string) => { + try { + events.push({ + toolCalls: JSON.parse(serialized), + type: InferenceEventType.TOOL_CALLS + }); + } catch { + /* Ignore parse errors during streaming */ + } + }, + stream: true, + tools + }, + conversationId, + signal + ).then( + () => events.close(), + (error: unknown) => events.fail(error) + ); + + return events; + } + }; } private parseToolArguments(args: string | Record): Record { diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts index b931f76ee43b..eb3ef07017d1 100644 --- a/ui/apps/chat/src/lib/types/index.ts +++ b/ui/apps/chat/src/lib/types/index.ts @@ -245,8 +245,6 @@ export type { EditFileEdit, EditFileMeta, EditFileTitleMeta, - ToolCallDescription, - ToolCallPhrasing, ToolEntry, ToolGroup, ToolUiEntry, diff --git a/ui/apps/chat/src/lib/types/tools.d.ts b/ui/apps/chat/src/lib/types/tools.d.ts index a96a7e3ce840..4f1ab120a1f2 100644 --- a/ui/apps/chat/src/lib/types/tools.d.ts +++ b/ui/apps/chat/src/lib/types/tools.d.ts @@ -1,5 +1,5 @@ import type { OpenAIToolDefinition } from './mcp'; -import type { ToolCallSummaryKind, ToolSource } from '#lib/enums/index.ts'; +import type { ToolSource } from '#lib/enums/index.ts'; import type { Component } from 'svelte'; /** @@ -81,32 +81,3 @@ export interface EditFileTitleMeta { editsApplied?: number; errorMessage?: string; } - -/** How a tool call reads in the chat trace; see TOOL_CALL_PHRASING. */ -export interface ToolCallPhrasing { - /** Verb once the call is done, e.g. "Read". */ - past: string; - /** Verb while the call runs, e.g. "Reading". */ - present: string; - /** Words after the verb when the call has no target, e.g. "a file". */ - object: string; - /** Words between the verb and the target, e.g. "for". */ - targetObject?: string; - /** Show the target in quotes, for search terms. */ - quoteTarget?: boolean; - summary: ToolCallSummaryKind; -} - -/** A tool call as one plain sentence: label, then an optional target. */ -export interface ToolCallDescription { - /** Verb and object, e.g. "Read a file" or "Searched for". */ - label: string; - /** What the call acted on, e.g. a file name or a search term. */ - target?: string; - quoted: boolean; - summary: ToolCallSummaryKind; - /** How many things the call counts as in the group summary. */ - count: number; - /** True when the label is the model's own description of the call. */ - described?: boolean; -} diff --git a/ui/apps/chat/src/lib/utils/async-queue.ts b/ui/apps/chat/src/lib/utils/async-queue.ts new file mode 100644 index 000000000000..48988dd93951 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/async-queue.ts @@ -0,0 +1,50 @@ +/** + * A queue read as an async iterable, to turn a callback API into a stream. + * The iteration ends after `close`, and throws after `fail`, once the pushed items are read. + */ +export interface AsyncQueue extends AsyncIterable { + push(item: T): void; + close(): void; + fail(error: unknown): void; +} + +export function createAsyncQueue(): AsyncQueue { + const items: T[] = []; + + let closed = false; + let failure: { error: unknown } | undefined; + let wake: (() => void) | undefined; + + const notify = () => { + wake?.(); + wake = undefined; + }; + + return { + close() { + closed = true; + notify(); + }, + fail(error) { + failure = { error }; + notify(); + }, + push(item) { + items.push(item); + notify(); + }, + async *[Symbol.asyncIterator]() { + while (true) { + if (items.length > 0) { + yield items.shift()!; + } else if (failure) { + throw failure.error; + } else if (closed) { + return; + } else { + await new Promise((resolve) => (wake = resolve)); + } + } + } + }; +} diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index ae28ff9cd23c..4476ac63f40f 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -295,7 +295,6 @@ export { computeLineDiff, prefixFor, renderUnifiedDiff, type DiffLine } from './ // Partial-incremental JSON parser for streaming tool arguments export { memoizeBounded } from './memoize-bounded'; -export { parsePartialJsonArgs } from './parse-partial-json-args'; // `exec_shell_command` result parsing export { parseExecShellCommandError } from './parse-exec-shell-error'; diff --git a/ui/apps/chat/src/lib/utils/parse-partial-json-args.ts b/ui/apps/chat/src/lib/utils/parse-partial-json-args.ts deleted file mode 100644 index 49bc1bc70434..000000000000 --- a/ui/apps/chat/src/lib/utils/parse-partial-json-args.ts +++ /dev/null @@ -1,124 +0,0 @@ -// JSON delimiters used while scanning partial streamed JSON. Single-char -// tokens so they only need eq-comparison, but naming them keeps the -// scanner readable and keeps the literal source-of-truth in one place. -const JSON_QUOTE = '"'; -const JSON_BACKSLASH = '\\'; -const JSON_OBJECT_OPEN = '{'; -const JSON_OBJECT_CLOSE = '}'; -const JSON_ARRAY_OPEN = '['; -const JSON_ARRAY_CLOSE = ']'; -// Trailing punctuation to strip before re-closing a partial object/array. -// Matches an optional trailing comma plus any trailing whitespace; lets -// us re-emit a syntactically-valid JSON document without an orphaned -// comma when the model cut off mid-key. -const TRAILING_JSON_PUNCTUATION_REGEX = /,?\s*$/; -/** Bounded cache for parsePartialJsonArgs results. */ -const PARTIAL_JSON_CACHE_MAX_SIZE = 32; -const partialJsonCache = new Map | null>(); - -function cacheResult(input: string, result: Record | null): void { - if (partialJsonCache.size >= PARTIAL_JSON_CACHE_MAX_SIZE) { - partialJsonCache.delete(partialJsonCache.keys().next().value!); - } - - partialJsonCache.set(input, result); -} - -// Parse partial tool-arg JSON streamed token-by-token. Closes any -// unterminated string and dangling open containers (in reverse order), -// so parsers can still surface keys already received while the call -// is still in flight. Memoized: the char-by-char scanner runs on every -// render during streaming even when toolArgs hasn't changed. -export function parsePartialJsonArgs(toolArgsString: string): Record | null { - const cached = partialJsonCache.get(toolArgsString); - - if (cached !== undefined) return cached; - - let result: Record | null; - - try { - const parsed: unknown = JSON.parse(toolArgsString); - - result = - parsed && typeof parsed === 'object' && !Array.isArray(parsed) - ? (parsed as Record) - : null; - } catch { - result = scanPartialJson(toolArgsString); - } - - cacheResult(toolArgsString, result); - - return result; -} - -/** Char-by-char scanner for unterminated partial JSON. */ -function scanPartialJson(toolArgsString: string): Record | null { - let inString = false; - let escape = false; - - const stack: ('{' | '[')[] = []; - - for (let i = 0; i < toolArgsString.length; i++) { - const ch = toolArgsString[i]; - - if (escape) { - escape = false; - - continue; - } - - if (ch === JSON_BACKSLASH && inString) { - escape = true; - - continue; - } - - if (ch === JSON_QUOTE) { - inString = !inString; - - continue; - } - - if (inString) continue; - - if (ch === JSON_OBJECT_OPEN) stack.push(JSON_OBJECT_OPEN); - else if (ch === JSON_OBJECT_CLOSE) { - if (stack.length === 0 || stack[stack.length - 1] !== JSON_OBJECT_OPEN) return null; - - stack.pop(); - } else if (ch === JSON_ARRAY_OPEN) stack.push(JSON_ARRAY_OPEN); - else if (ch === JSON_ARRAY_CLOSE) { - if (stack.length === 0 || stack[stack.length - 1] !== JSON_ARRAY_OPEN) return null; - - stack.pop(); - } - } - - let completed = toolArgsString; - - if (escape) { - // Dangling escape at end of partial JSON: escape the trailing - // backslash as a literal so we can close the string cleanly. - completed += JSON_BACKSLASH; - } - - if (inString) completed += JSON_QUOTE; - - if (!inString) completed = completed.replace(TRAILING_JSON_PUNCTUATION_REGEX, ''); - - // Close in reverse nesting order: innermost container first. - for (let i = stack.length - 1; i >= 0; i--) { - completed += stack[i] === JSON_OBJECT_OPEN ? JSON_OBJECT_CLOSE : JSON_ARRAY_CLOSE; - } - - try { - const parsed: unknown = JSON.parse(completed); - - return parsed && typeof parsed === 'object' && !Array.isArray(parsed) - ? (parsed as Record) - : null; - } catch { - return null; - } -} diff --git a/ui/apps/chat/tests/unit/agentic-flow.test.ts b/ui/apps/chat/tests/unit/agentic-flow.test.ts new file mode 100644 index 000000000000..1003f8fcb871 --- /dev/null +++ b/ui/apps/chat/tests/unit/agentic-flow.test.ts @@ -0,0 +1,373 @@ +// The agentic flow end to end, with the server and the tools mocked: what the +// model is sent each turn, and the order the flow's callbacks fire in. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: {} +})); + +import { BuiltInTool, MessageRole, ToolPermissionDecision, ToolSource } from '#lib/enums/index.ts'; +import { ChatService } from '#lib/services/chat.service.ts'; +import { ToolsService } from '#lib/services/tools.service.ts'; +import { agenticStore } from '#lib/stores/agentic/index.svelte.ts'; +import { modelsStore } from '#lib/stores/models/index.svelte.ts'; +import { permissionsStore } from '#lib/stores/permissions.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { AgenticFlowCallbacks } from '#lib/types/agentic.js'; +import type { ApiChatMessageData } from '#lib/types/api.js'; +import type { ChatMessageTimings } from '#lib/types/chat.js'; +import type { DatabaseMessage } from '#lib/types/database.js'; + +const CONV_ID = 'conv-1'; +const USER_MESSAGES: ApiChatMessageData[] = [{ content: 'hi', role: MessageRole.USER }]; +const IMAGE_DATA_URI = 'data:image/png;base64,AAAA'; + +type StreamOptions = { + onChunk?: (chunk: string) => void; + onReasoningChunk?: (chunk: string) => void; + onTimings?: (timings?: ChatMessageTimings) => void; + onToolCallChunk?: (serialized: string) => void; +}; +type Turn = (options: StreamOptions) => void | Promise; + +function toolCalls(...names: string[]): string { + return JSON.stringify( + names.map((name, index) => ({ function: { arguments: '{}', name }, id: `call_${index}` })) + ); +} + +// each request plays the next scripted turn; returns what every request was sent +function mockTurns(...turns: Turn[]): ApiChatMessageData[][] { + const requests: ApiChatMessageData[][] = []; + + vi.spyOn(ChatService, 'sendMessage').mockImplementation(async (messages, options) => { + requests.push(structuredClone(messages) as ApiChatMessageData[]); + await turns[requests.length - 1]?.(options as StreamOptions); + }); + + return requests; +} + +function mockTools(source: ToolSource, ...names: string[]) { + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue( + names.map((name) => ({ function: { name, parameters: {} }, type: 'function' })) + ); + vi.spyOn(toolsStore, 'getToolSource').mockReturnValue(source); +} + +// callbacks that log their calls in order +function recorder() { + const calls: unknown[][] = []; + const log = + (name: string) => + (...args: unknown[]) => { + calls.push([name, ...args]); + }; + + let nextMessageId = 0; + + const createMessage = + (name: string) => + async (...args: unknown[]) => { + calls.push([name, ...args]); + + return { id: `msg_${nextMessageId++}` } as DatabaseMessage; + }; + const callbacks: AgenticFlowCallbacks = { + createAssistantMessage: createMessage('createAssistantMessage'), + createToolResultMessage: createMessage('createToolResultMessage'), + onAssistantTurnComplete: async (...args) => { + calls.push(['onAssistantTurnComplete', ...args]); + }, + onAttachments: log('onAttachments'), + onChunk: log('onChunk'), + onError: log('onError'), + onFlowComplete: log('onFlowComplete'), + onReasoningChunk: log('onReasoningChunk'), + onToolCallsStreaming: log('onToolCallsStreaming'), + onTurnComplete: log('onTurnComplete'), + updateToolResultMessage: async (...args) => { + calls.push(['updateToolResultMessage', ...args]); + } + }; + + return { + callbacks, + calls, + named: (name: string) => calls.filter((call) => call[0] === name), + names: () => calls.map((call) => call[0]) + }; +} + +function runFlow(callbacks: AgenticFlowCallbacks, signal?: AbortSignal) { + return agenticStore.runAgenticFlow({ + callbacks, + conversationId: CONV_ID, + messages: USER_MESSAGES, + signal + }); +} + +beforeEach(() => { + vi.restoreAllMocks(); + agenticStore.clearSession(CONV_ID); + vi.spyOn(console, 'log').mockImplementation(() => {}); + vi.spyOn(ChatService, 'normalizeMessagesForApi').mockImplementation( + async (messages) => messages as ApiChatMessageData[] + ); + vi.spyOn(toolsStore, 'fetchServerTools').mockResolvedValue(); + vi.spyOn(toolsStore, 'getToolServerLabel').mockReturnValue('Browser'); + vi.spyOn(toolsStore, 'getPermissionKey').mockReturnValue('tool-key'); + vi.spyOn(permissionsStore, 'hasTool').mockReturnValue(true); +}); + +describe('agentic flow', () => { + it('is not handled when no tool is enabled', async () => { + vi.spyOn(toolsStore, 'getEnabledToolsForLLM').mockReturnValue([]); + + const send = vi.spyOn(ChatService, 'sendMessage'); + + expect(await runFlow(recorder().callbacks)).toEqual({ handled: false }); + expect(send).not.toHaveBeenCalled(); + }); + + it('runs a tool call, then lets the model answer', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + + const requests = mockTurns( + (options) => { + options.onChunk?.('checking'); + options.onToolCallChunk?.(toolCalls(BuiltInTool.BROWSER_GET_DATETIME)); + options.onTimings?.({ predicted_ms: 10, predicted_n: 4, prompt_ms: 20, prompt_n: 8 }); + }, + (options) => { + options.onReasoningChunk?.('hm'); + options.onChunk?.('it is noon'); + options.onTimings?.({ predicted_ms: 5, predicted_n: 2, prompt_ms: 1, prompt_n: 1 }); + } + ); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(names()).toEqual([ + 'onChunk', + 'onToolCallsStreaming', + 'onAssistantTurnComplete', + 'createToolResultMessage', + 'onTurnComplete', + 'createAssistantMessage', + 'onReasoningChunk', + 'onChunk', + 'onAssistantTurnComplete', + 'onTurnComplete', + 'onFlowComplete' + ]); + + const [toolTurn, finalTurn] = named('onAssistantTurnComplete'); + const call = { + function: { arguments: '{}', name: BuiltInTool.BROWSER_GET_DATETIME }, + id: 'call_0', + type: 'function' + }; + + expect(toolTurn.slice(1)).toEqual([ + 'checking', + undefined, + { predicted_ms: 10, predicted_n: 4, prompt_ms: 20, prompt_n: 8 }, + [call] + ]); + expect(finalTurn.slice(1, 3)).toEqual(['it is noon', 'hm']); + expect(finalTurn[4]).toBeUndefined(); + + const [, toolCallId, toolResult, extras] = named('createToolResultMessage')[0]; + + expect([toolCallId, extras]).toEqual(['call_0', undefined]); + expect(requests[1].slice(1)).toEqual([ + { content: 'checking', role: 'assistant', tool_calls: [call] }, + { content: toolResult, role: 'tool', tool_call_id: 'call_0' } + ]); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { + llm: { predicted_ms: 15, predicted_n: 6, prompt_ms: 21, prompt_n: 9 }, + perTurn: [{ turn: 1 }, { turn: 2 }], + toolCalls: [{ name: BuiltInTool.BROWSER_GET_DATETIME, success: true }], + toolCallsCount: 1, + turns: 2 + }, + predicted_n: 2 + }); + expect(agenticStore.getTotalToolCalls(CONV_ID)).toBe(1); + expect(agenticStore.isRunning(CONV_ID)).toBe(false); + }); + + it('waits for permission and tells the model when it is denied', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + vi.mocked(permissionsStore.hasTool).mockReturnValue(false); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls(BuiltInTool.BROWSER_GET_DATETIME)), + (options) => options.onChunk?.('ok') + ); + const { callbacks, named } = recorder(); + const flow = runFlow(callbacks); + + await vi.waitFor(() => + expect(agenticStore.getPendingPermissionRequest(CONV_ID)).toEqual({ + serverLabel: 'Browser', + toolCallId: 'call_0', + toolName: BuiltInTool.BROWSER_GET_DATETIME + }) + ); + agenticStore.resolvePermission(CONV_ID, ToolPermissionDecision.DENY); + await flow; + + expect(named('createToolResultMessage')[0].slice(1)).toEqual([ + 'call_0', + 'Tool execution was denied by the user.', + undefined + ]); + expect(requests[1][2]).toMatchObject({ content: 'Tool execution was denied by the user.' }); + expect(named('onFlowComplete')[0][1]).toMatchObject({ + agentic: { toolCalls: [{ success: false }] } + }); + }); + + it('reports a failing tool to the model and goes on', async () => { + mockTools(ToolSource.SERVER, 'read_file'); + vi.spyOn(ToolsService, 'executeTool').mockRejectedValue(new Error('no such file')); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('read_file')), + (options) => options.onChunk?.('sorry') + ); + const { callbacks } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(requests[1][2]).toMatchObject({ content: 'Error: no such file', role: 'tool' }); + }); + + it('shows the output of a streaming tool while it runs', async () => { + mockTools(ToolSource.SERVER, BuiltInTool.SERVER_EXEC_SHELL_COMMAND); + vi.spyOn(ToolsService, 'streamTool').mockImplementation(async function* () { + yield { chunk: 'one\n', done: false }; + await new Promise((resolve) => setTimeout(resolve, 0)); + yield { chunk: 'two\n', done: false }; + await new Promise((resolve) => setTimeout(resolve, 0)); + yield { chunk: null, done: true }; + }); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls(BuiltInTool.SERVER_EXEC_SHELL_COMMAND)), + (options) => options.onChunk?.('done') + ); + const { callbacks, named } = recorder(); + + await runFlow(callbacks); + + // created empty when the tool starts, then rewritten in place: never created twice + expect(named('createToolResultMessage').map((call) => call.slice(1))).toEqual([ + ['call_0', '', undefined, undefined] + ]); + expect(named('updateToolResultMessage').map((call) => call.slice(1))).toEqual([ + ['msg_0', 'one\n'], + ['msg_0', 'one\ntwo\n'] + ]); + expect(requests[1][2]).toMatchObject({ content: 'one\ntwo\n', role: 'tool' }); + }); + + it('takes an image out of a tool result and sends it to a model with vision', async () => { + mockTools(ToolSource.SERVER, 'screenshot'); + vi.spyOn(ToolsService, 'executeTool').mockResolvedValue({ + content: `saved\n${IMAGE_DATA_URI}`, + isError: false + }); + vi.spyOn(modelsStore.props, 'modelSupportsVision').mockReturnValue(true); + + const requests = mockTurns( + (options) => options.onToolCallChunk?.(toolCalls('screenshot')), + (options) => options.onChunk?.('here') + ); + const { callbacks, named } = recorder(); + + await runFlow(callbacks); + + const [, , content, extras] = named('createToolResultMessage')[0]; + + expect(content).toMatch(/^saved\n\[Attachment saved: .+\.png\]$/); + expect(extras).toMatchObject([{ base64Url: IMAGE_DATA_URI, type: 'IMAGE' }]); + expect(named('onAttachments')[0].slice(1)).toEqual(['msg_0', extras]); + expect(requests[1][2]).toEqual({ + content: [ + { text: content, type: 'text' }, + { image_url: { url: IMAGE_DATA_URI }, type: 'image_url' } + ], + role: 'tool', + tool_call_id: 'call_0' + }); + }); + + it('leaves the flow when a steering message is queued, skipping the tool calls left', async () => { + mockTools(ToolSource.SERVER, 'first', 'second'); + vi.spyOn(ToolsService, 'executeTool').mockImplementation(async () => { + agenticStore.injectSteeringMessage(CONV_ID, 'wait'); + + return { content: 'first ran', isError: false }; + }); + + const requests = mockTurns((options) => + options.onToolCallChunk?.(toolCalls('first', 'second')) + ); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks)).toEqual({ handled: true }); + expect(named('createToolResultMessage').map((call) => call.slice(1, 3))).toEqual([ + ['call_0', 'first ran'], + ['call_1', 'Tool execution was interrupted by a new user message.'] + ]); + expect(names().slice(-2)).toEqual(['onTurnComplete', 'onFlowComplete']); + expect(requests).toHaveLength(1); + expect(agenticStore.consumePendingSteeringMessage(CONV_ID)).toMatchObject({ content: 'wait' }); + }); + + it('keeps the partial turn and reports the error when the stream fails', async () => { + mockTools(ToolSource.BROWSER, BuiltInTool.BROWSER_GET_DATETIME); + mockTurns((options) => { + options.onChunk?.('par'); + + throw new Error('HTTP 500'); + }); + + const { callbacks, named, names } = recorder(); + const result = await runFlow(callbacks); + + expect(result).toMatchObject({ error: { message: 'HTTP 500' }, handled: true }); + expect(names()).toEqual(['onChunk', 'onAssistantTurnComplete', 'onFlowComplete', 'onError']); + expect(named('onAssistantTurnComplete')[0].slice(1)).toEqual([ + 'par', + undefined, + undefined, + undefined + ]); + expect(agenticStore.getLastError(CONV_ID)?.message).toBe('HTTP 500'); + }); + + it('stops without a tool result when the user aborts during a tool call', async () => { + const controller = new AbortController(); + + mockTools(ToolSource.SERVER, 'slow'); + vi.spyOn(ToolsService, 'executeTool').mockImplementation(async () => { + controller.abort(); + + return { content: 'late', isError: false }; + }); + + const requests = mockTurns((options) => options.onToolCallChunk?.(toolCalls('slow'))); + const { callbacks, named, names } = recorder(); + + expect(await runFlow(callbacks, controller.signal)).toEqual({ handled: true }); + expect(named('createToolResultMessage')).toEqual([]); + expect(names().slice(-1)).toEqual(['onFlowComplete']); + expect(requests).toHaveLength(1); + }); +}); diff --git a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts index c46f3fe4bf68..0da763bd3d76 100644 --- a/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts +++ b/ui/apps/chat/tests/unit/agentic-hotpath.bench.ts @@ -6,6 +6,7 @@ // // Run: npx vitest bench --project=unit tests/unit/agentic-hotpath.bench.ts +import { parsePartialJsonArgs } from '@ggml-org/llama-harness'; import { classifyToolResult, parseToolResultWithMedia } from '#lib/utils/agentic.ts'; import { detectIncompleteCodeBlock, @@ -14,7 +15,6 @@ import { } from '#lib/utils/code.ts'; import { computeLineDiff } from '#lib/utils/compute-line-diff.ts'; import { preprocessLaTeX } from '#lib/utils/latex-protection.ts'; -import { parsePartialJsonArgs } from '#lib/utils/parse-partial-json-args.ts'; import { extractSearchQuery, extractSearchResults } from '#lib/utils/search-results.ts'; import { all as lowlightAll } from 'lowlight'; import rehypeHighlight from 'rehype-highlight'; diff --git a/ui/apps/chat/tests/unit/async-queue.test.ts b/ui/apps/chat/tests/unit/async-queue.test.ts new file mode 100644 index 000000000000..4856f74d3ba6 --- /dev/null +++ b/ui/apps/chat/tests/unit/async-queue.test.ts @@ -0,0 +1,42 @@ +import { createAsyncQueue } from '#lib/utils/async-queue.ts'; +import { describe, expect, it } from 'vitest'; + +async function collect(queue: AsyncIterable): Promise { + const items: T[] = []; + + for await (const item of queue) items.push(item); + + return items; +} + +describe('createAsyncQueue', () => { + it('yields the items pushed before and during the iteration, then ends on close', async () => { + const queue = createAsyncQueue(); + + queue.push(1); + + const collected = collect(queue); + + await Promise.resolve(); + queue.push(2); + queue.push(3); + queue.close(); + + expect(await collected).toEqual([1, 2, 3]); + }); + + it('throws the failure after the pushed items are read', async () => { + const queue = createAsyncQueue(); + const seen: number[] = []; + + queue.push(1); + queue.fail(new Error('cut')); + + await expect( + (async () => { + for await (const item of queue) seen.push(item); + })() + ).rejects.toThrow('cut'); + expect(seen).toEqual([1]); + }); +}); diff --git a/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts index 1433d32250cd..459ff227f4dd 100644 --- a/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts +++ b/ui/apps/chat/tests/unit/tool-call-phrasing.test.ts @@ -1,10 +1,12 @@ import { - describeToolActivity, - describeToolCall, formatToolCallLine, groupToolCallRuns, humanizeArgKey, - simpleToolArgFields, + simpleToolArgFields +} from '@ggml-org/llama-harness'; +import { + describeToolActivity, + describeToolCall, summarizeToolCalls } from '#lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/parsers/tool-call-phrasing.ts'; import { AgenticSectionType, BuiltInTool } from '#lib/enums/index.ts'; diff --git a/ui/apps/chat/tsconfig.json b/ui/apps/chat/tsconfig.json index 74af0cce0360..fed5bbe9d198 100644 --- a/ui/apps/chat/tsconfig.json +++ b/ui/apps/chat/tsconfig.json @@ -47,7 +47,8 @@ "tw-animate-css/*": ["./node_modules/tw-animate-css/*"], "vaul-svelte": ["./node_modules/vaul-svelte"], "vaul-svelte/*": ["./node_modules/vaul-svelte/*"], - "@lucide/svelte/icons/*": ["./node_modules/@lucide/svelte/dist/icons/*"] + "@lucide/svelte/icons/*": ["./node_modules/@lucide/svelte/dist/icons/*"], + "@ggml-org/llama-harness": ["../../lib/harness/src/index.ts"] }, "sourceMap": true, "strict": true diff --git a/ui/apps/chat/vite.config.ts b/ui/apps/chat/vite.config.ts index fb9c666a9577..68493dad9656 100644 --- a/ui/apps/chat/vite.config.ts +++ b/ui/apps/chat/vite.config.ts @@ -17,6 +17,8 @@ import { defineConfig, loadEnv, searchForWorkspaceRoot } from 'vite'; const __dirname = dirname(fileURLToPath(import.meta.url)); const LLAMA_VOICE_SOURCE = resolve(__dirname, '../../lib/voice/src'); +// the harness has no build step in the repo: the app compiles it from source +const LLAMA_HARNESS_ENTRY = resolve(__dirname, '../../lib/harness/src/index.ts'); // eslint-disable-next-line @typescript-eslint/no-explicit-any const browserBaseConfig: any = { enabled: true, @@ -85,6 +87,7 @@ export default defineConfig(({ mode }) => { replacement: resolve(LLAMA_VOICE_SOURCE, 'svelte/index.ts') }, { find: /^@ggml-org\/llama-voice$/, replacement: resolve(LLAMA_VOICE_SOURCE, 'index.ts') }, + { find: /^@ggml-org\/llama-harness$/, replacement: LLAMA_HARNESS_ENTRY }, { find: 'katex-fonts', replacement: resolve('node_modules/katex/dist/fonts') } ] }, @@ -94,7 +97,8 @@ export default defineConfig(({ mode }) => { allow: [ searchForWorkspaceRoot(process.cwd()), resolve(__dirname, 'tests'), - LLAMA_VOICE_SOURCE + LLAMA_VOICE_SOURCE, + resolve(__dirname, '../../lib/harness') ] }, headers: { diff --git a/ui/lib/harness/.gitignore b/ui/lib/harness/.gitignore new file mode 100644 index 000000000000..16339ab2e87f --- /dev/null +++ b/ui/lib/harness/.gitignore @@ -0,0 +1,6 @@ +node_modules +/dist + +# OS +.DS_Store +Thumbs.db diff --git a/ui/lib/harness/.npmrc b/ui/lib/harness/.npmrc new file mode 100644 index 000000000000..b6f27f135954 --- /dev/null +++ b/ui/lib/harness/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/ui/lib/harness/LICENSE b/ui/lib/harness/LICENSE new file mode 100644 index 000000000000..50c59c51c158 --- /dev/null +++ b/ui/lib/harness/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) ggml + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, 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 THE +SOFTWARE. diff --git a/ui/lib/harness/README.md b/ui/lib/harness/README.md new file mode 100644 index 000000000000..140a06d9e58b --- /dev/null +++ b/ui/lib/harness/README.md @@ -0,0 +1,83 @@ +# @ggml-org/llama-harness + +Llama Harness, the agentic loop of Llama Chat, as a package: it streams a turn, runs the tools the model called, gives it the results, and repeats until the model answers without a tool call. It is headless TypeScript with no UI, no DOM and no dependencies, so the same loop runs in a browser, in Node and in a worker. It lives in llama.cpp at `ui/lib/harness`. + +It talks to llama-server's chat completions endpoint (`/v1/chat/completions`) and reads the timings and prompt progress llama-server adds. + +## Use + +```ts +import { createHarness, createOpenAIClient, type Tool } from "@ggml-org/llama-harness"; + +const harness = createHarness(createOpenAIClient({ baseUrl: "http://localhost:8080" })); + +const getTime: Tool = { + definition: { + type: "function", + function: { + name: "get_time", + description: "The current time", + parameters: { type: "object", properties: {} }, + }, + }, + execute: async () => ({ content: new Date().toISOString() }), +}; + +for await (const event of harness.run([{ role: "user", content: "What time is it?" }], [getTime])) { + if (event.type === "text") process.stdout.write(event.delta); +} +``` + +## The contract + +```ts +interface Harness { + run(messages, tools, signal?, options?): AsyncIterable; +} +``` + +- **Messages and tools** use the OpenAI shapes. A tool is its definition plus an `execute` function. +- **Events:** `turn_start`, `text`, `reasoning`, `tool_call_delta`, `timings`, `model`, `completion_id`, `message` (a turn's assistant message), `tool_call`, `tool_update` (a streaming tool's output so far), `tool_result`, `turn_end`, and last `done` or `error`. `run` never throws. +- **The loop waits for you.** It does not go on until you ask for the next event, so you can store each message before the next step runs. +- **It keeps nothing.** No conversation state, no storage: the app owns the history and passes it in. +- **Stopping:** `signal` stops at once. `options.interrupted` ends the run at the next safe point, e.g. when the user sent a new message. `options.maxTurns` with `options.onTurnLimit` asks before it goes past a turn limit. + +An app can put another loop behind the same `Harness` interface. What sits above the loop is the same for every loop: the tools, and whatever an app wraps around `execute`, such as a permission prompt. + +## Traces + +A run's steps also read as an agent trace: what each tool call did, in plain words. That part is headless too, so any app on the harness can show the same lines. + +```ts +import { createTracePhraser, formatToolCallLine, groupToolCallRuns } from "@ggml-org/llama-harness"; + +const { describeToolCall, summarizeToolCalls, describeToolActivity } = createTracePhraser(); + +formatToolCallLine(describeToolCall("read_file", '{"path":"src/app.ts"}')); // "Read app.ts" +summarizeToolCalls(steps); // "Ran 3 commands, read 2 files" +describeToolActivity(steps, true); // "Running npm test", or "Thinking" +``` + +- **Steps** are anything with a `type` from `TraceStepType` (text, reasoning, or a tool call that is done, pending or still streaming) plus the call's name and arguments. +- **Phrasing** knows llama-server's built-in tools. An app adds its own tools with `resolvers` (a function per tool or family of tools) and `phrasings` (a table by name); any other tool reads as "Used " with its main argument. A call whose arguments carry `description` shows the model's own words instead. +- **Streaming:** arguments are read while they stream (`parsePartialJsonArgs`), and arguments that hold whole files are read for their path only (`extractToolArgString`). +- **Grouping:** `groupToolCallRuns` folds the calls and the reasoning around them into one row, up to the next text. + +## What the app keeps + +Llama Chat (`ui/apps/chat`) is the first app on it. Its agentic store gives the harness: + +- **An inference client:** its own chat service, which knows the servers, the settings and how to resume a stream. +- **The tools:** built-in tools, llama-server tools and MCP tools, each behind the permission gate. +- **Storage:** it turns the events into messages in its database. + +## Develop + +```sh +npm ci +npm run check # type check +npm test # unit tests +npm run prepack # build dist/ and lint the package +``` + +Llama Chat does not need a build of this package: it compiles `src/` directly, through the `@ggml-org/llama-harness` alias in its `vite.config.ts`. diff --git a/ui/lib/harness/package-lock.json b/ui/lib/harness/package-lock.json new file mode 100644 index 000000000000..952987aff8df --- /dev/null +++ b/ui/lib/harness/package-lock.json @@ -0,0 +1,1255 @@ +{ + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "license": "MIT", + "devDependencies": { + "@types/node": "^24", + "publint": "^0.3.21", + "typescript": "^6.0.3", + "vitest": "5.0.5" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@publint/pack": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@publint/pack/-/pack-0.1.7.tgz", + "integrity": "sha512-4EDEmvxWtgsCnnVeBvtFIFZtUhPPt1+bA9JrSwU4Sa//6oKtzCSlGGXYJr44OD9aGISymbieJ4mCKHUygUDU+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyexec": "^1.3.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.18.tgz", + "integrity": "sha512-ubTG+4KlidvioxjOFdsdEa2F6JVGZb8m2ByJUqQ7fYzUeT1cEn194POcsQ10PKH4p//q0YQn4SB3YpSuzcA1Yg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.18.tgz", + "integrity": "sha512-2Xa1t/JeFGTZn5TbzgPppcCftF8sCVnTNvrIvoSdcZhoFzAuVy1L3xxQUQ4sfWDtwVzg1u6Yi1R3SlJugRNV2Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.18.tgz", + "integrity": "sha512-iUzw9HshVvrWci9gVXjxWS7/M/IcLvNo67vu2c/w9zKBz4hIvPRixdUpIW/iCfhldLaq9ER2hecsI9UY5z0/yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.18.tgz", + "integrity": "sha512-XuDHFzbFEtZl0QGJi92+fmG67tfnp1iZ9VOeDkwasGyTq2VG3/5PnJnvAr+MTzFh/rNScJ3VhN+XpZyyGsN7Jw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.18.tgz", + "integrity": "sha512-MM8opLfsLK15oEXDz6iBc0t3ahu+ew9jsAmha+ovZ33hSwYgqo7YmpRITqFTfW7xA71BLEQ3jJdTsaCmhB1c9w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.18.tgz", + "integrity": "sha512-J6EoCWiy5RnFQzHrKyHXXevZ9lukQfGpnchX/zG/k/WC2nc9O9XyS1JgA8kI9VxMFggMbCPjpv7LcikriXfehw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.18.tgz", + "integrity": "sha512-HIkFuLF7CdDeki+1aCZLLbLq0hk/PHntb+z4/YCTo47JbksTD6jJEELIz92tYROmDmvMrNqUMqBi71BkJLDR+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.18.tgz", + "integrity": "sha512-4oqWItLLYt7IceOnElCct8T2ek5p7PmD7LN04TRJRXGo5f3HtKTgGH6PhYRFK4C2ICkq/LMUU0BVPvvlAKhm8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.18.tgz", + "integrity": "sha512-+AkRly5SrCEgnPhGRfub7pucASYEC2fTsxZg7VCcnozpA2+Wn/gCYy1t7LuJS67/xyJu/7noYBJncDUkbwgw2A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.18.tgz", + "integrity": "sha512-Ttg1r9vVykMnQrE/GwYO9icKtXiuiMfRe/w74xJkeoVuvhRG+WtT6LEMOf58Yl63yd77lhHzO8Y55R8CC3XALA==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.18.tgz", + "integrity": "sha512-xX1Tt4o5jUMma0vJsXp5eRZA9nOuyigb2dKJMMzZRmzMxLYGE9PaKKSqHPzPvSQgM8ZOEacSTQwDQcwWfh0xmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.18.tgz", + "integrity": "sha512-4VVlGI5K2kociZlW3lSN8VjG3TW5yQIlAcfCdBXMgGjJxZll15Fa4ocRHXHvIVVnwlibCw/NQajJrNDiqqpiiw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.18.tgz", + "integrity": "sha512-PApTsgH1jLYuyy3tSCz9De82Gq5qXwi7vImVZhEzTgX1C4150Cp5M2ZfL3pLvbCvbEHL0oJeC6pd6podtv8Y5w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.18.tgz", + "integrity": "sha512-J2XjWjx/SP+4x0H4r6dz3Vzb5WVkg7re40Do9K7HJ3sK2/xcmZrWwakXlSwaMvOkvruLJCD4CL/3wqsIR/thgg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.18.tgz", + "integrity": "sha512-XwRJxRQvkuEtS0hIIt29QrqPJ+JzMJSNYHJw4ae/mc6uEarfRG1ceyg4HmmWiBdL/YCb6g7N5BLbSvmRJRYZHw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.0.tgz", + "integrity": "sha512-K+NU2HDCEem4sClgHH4ZZXwdJeNFkJo+hRk479DIwdIviAPN2hFJH1KHHwg8CxHQXvi0M5XY4deTXINfIiSG6w==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.19.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.19.2.tgz", + "integrity": "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/package-manager-detector": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/package-manager-detector/-/package-manager-detector-1.9.0.tgz", + "integrity": "sha512-zAMfbta9nPA8AKkA4WdmNAT8R8s6Dk0/xwPsqNnRidMFcLo1YkLuPDTgs2f64XdzS8vbLNnoJ+uUIkgbz7oRHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/publint": { + "version": "0.3.25", + "resolved": "https://registry.npmjs.org/publint/-/publint-0.3.25.tgz", + "integrity": "sha512-WMMbn/d7JqRlfXQL/JUI4n5skC8cJ5WVr8/wT5mmiYWkUdENkZr1I5rgs2+dQPVRgoJd+JRYtB46MTsuDylw9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@publint/pack": "^0.1.7", + "package-manager-detector": "^1.8.0", + "picocolors": "^1.1.1", + "sade": "^1.8.1" + }, + "bin": { + "publint": "src/cli.js" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://bjornlu.com/sponsor" + } + }, + "node_modules/rolldown": { + "version": "1.2.18", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.18.tgz", + "integrity": "sha512-C1uuT3UR60SShuCaPQFAAZyefJCWZlAKB02BV3BuPE2Rs4fevRQltEKoFO2tV5W9/eJhU5RieV6vJj3euulfNQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.18", + "@rolldown/binding-android-arm64": "1.2.18", + "@rolldown/binding-darwin-arm64": "1.2.18", + "@rolldown/binding-darwin-x64": "1.2.18", + "@rolldown/binding-freebsd-x64": "1.2.18", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.18", + "@rolldown/binding-linux-arm64-gnu": "1.2.18", + "@rolldown/binding-linux-arm64-musl": "1.2.18", + "@rolldown/binding-linux-ppc64-gnu": "1.2.18", + "@rolldown/binding-linux-s390x-gnu": "1.2.18", + "@rolldown/binding-linux-x64-gnu": "1.2.18", + "@rolldown/binding-linux-x64-musl": "1.2.18", + "@rolldown/binding-openharmony-arm64": "1.2.18", + "@rolldown/binding-win32-arm64-msvc": "1.2.18", + "@rolldown/binding-win32-x64-msvc": "1.2.18" + } + }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.24.6", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.24.6.tgz", + "integrity": "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.7", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.7.tgz", + "integrity": "sha512-oxh0dMxrayBr33ScJvvBJ2HBQ2jc1TBrXKR2NyL/MJ9WPuX19mN2DXWUmywKdyw5RFVQBo8hmtb2FMC0LHrnng==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + } + } +} diff --git a/ui/lib/harness/package.json b/ui/lib/harness/package.json new file mode 100644 index 000000000000..b93deffb207d --- /dev/null +++ b/ui/lib/harness/package.json @@ -0,0 +1,39 @@ +{ + "name": "@ggml-org/llama-harness", + "version": "0.1.0", + "description": "Headless agentic loop for llama.cpp frontend apps.", + "homepage": "https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/harness", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ggml-org/llama.cpp.git", + "directory": "ui/lib/harness" + }, + "files": [ + "dist" + ], + "type": "module", + "sideEffects": false, + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "check": "tsc --noEmit", + "prepack": "npm run build && publint", + "test": "vitest --run" + }, + "devDependencies": { + "@types/node": "^24", + "publint": "^0.3.21", + "typescript": "^6.0.3", + "vitest": "5.0.5" + }, + "engines": { + "node": ">=20" + } +} diff --git a/ui/lib/harness/src/abort.ts b/ui/lib/harness/src/abort.ts new file mode 100644 index 000000000000..636dd21ed718 --- /dev/null +++ b/ui/lib/harness/src/abort.ts @@ -0,0 +1,17 @@ +const ABORT_ERROR_NAME = "AbortError"; +// TypeErrors a browser throws when a fetch stream is cut by page unload, navigation or a network drop +const ABORT_LIKE_MESSAGE_PATTERNS = [ + /input stream/i, + /network connection was lost/i, + /load failed/i, +]; + +export function isAbortError(error: unknown): boolean { + if (!(error instanceof Error)) return false; + + if (error.name === ABORT_ERROR_NAME) return true; + + return ( + error instanceof TypeError && ABORT_LIKE_MESSAGE_PATTERNS.some((re) => re.test(error.message)) + ); +} diff --git a/ui/lib/harness/src/harness.ts b/ui/lib/harness/src/harness.ts new file mode 100644 index 000000000000..e58e7ea25188 --- /dev/null +++ b/ui/lib/harness/src/harness.ts @@ -0,0 +1,375 @@ +import { isAbortError } from "./abort.js"; +import type { + DoneReason, + Harness, + HarnessEvent, + InferenceClient, + LlmTimings, + LlmTotals, + Message, + PartialToolCall, + RunOptions, + RunTimings, + Timings, + Tool, + ToolCall, + ToolResult, + TurnStats, +} from "./types.js"; + +/** The result of a tool call that did not run because the run was interrupted. */ +export const INTERRUPTED_TOOL_RESULT = "Tool execution was interrupted by a new user message."; + +function emptyTotals(): LlmTotals { + return { predicted_ms: 0, predicted_n: 0, prompt_ms: 0, prompt_n: 0 }; +} + +function addTimings(totals: LlmTotals, timings: LlmTimings): LlmTotals { + return { + predicted_ms: totals.predicted_ms + (timings.predicted_ms ?? 0), + predicted_n: totals.predicted_n + (timings.predicted_n ?? 0), + prompt_ms: totals.prompt_ms + (timings.prompt_ms ?? 0), + prompt_n: totals.prompt_n + (timings.prompt_n ?? 0), + }; +} + +function toToolCalls(partial: PartialToolCall[]): ToolCall[] { + return partial.map((call, index) => ({ + function: { + arguments: call?.function?.arguments ?? "", + name: call?.function?.name ?? "", + }, + id: call?.id ?? `tool_${index}`, + type: "function", + })); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * The default loop: stream a turn, run the tools the model called, give it the results, and repeat until it answers + * without a tool call. It keeps no state between runs and stores nothing: the app owns the conversation. + */ +export function createHarness(client: InferenceClient): Harness { + return { + run: (messages, tools, signal, options) => run(client, messages, tools, signal, options), + }; +} + +async function* run( + client: InferenceClient, + messages: Message[], + tools: Tool[], + signal?: AbortSignal, + options: RunOptions = {}, +): AsyncGenerator { + const { interrupted = () => false, maxTurns = Infinity, onTurnLimit } = options; + const history = [...messages]; + const definitions = tools.map((tool) => tool.definition); + const toolsByName = new Map(tools.map((tool) => [tool.definition.function.name, tool])); + const totals: RunTimings = { + llm: emptyTotals(), + perTurn: [], + toolCalls: [], + toolCallsCount: 0, + toolsMs: 0, + turns: 0, + }; + + let lastTimings: LlmTimings | undefined; + let turn = 0; + + const runTimings = (): Timings | undefined => { + if (totals.toolCallsCount === 0) return lastTimings; + + return { + agentic: totals, + cache_n: lastTimings?.cache_n, + predicted_ms: lastTimings?.predicted_ms, + predicted_n: lastTimings?.predicted_n, + prompt_ms: lastTimings?.prompt_ms, + prompt_n: lastTimings?.prompt_n, + }; + }; + const done = (reason: DoneReason): HarnessEvent => ({ + reason, + timings: runTimings(), + type: "done", + }); + + while (true) { + if (turn >= maxTurns) { + const more = onTurnLimit ? await onTurnLimit(signal) : false; + + if (!more || signal?.aborted) { + yield done(signal?.aborted ? "aborted" : "turn_limit"); + + return; + } + + turn = 0; + } + + totals.turns = turn + 1; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + yield { turn: turn + 1, type: "turn_start" }; + + let content = ""; + let reasoning = ""; + let partialCalls: PartialToolCall[] = []; + let turnTimings: LlmTimings | undefined; + + const stats: TurnStats = { llm: emptyTotals(), toolCalls: [], toolsMs: 0, turn: turn + 1 }; + // the turn's message when the run ends after it: what streamed so far, with the run's timings + const lastMessage = (toolCalls?: ToolCall[]): HarnessEvent => ({ + content, + final: true, + reasoning: reasoning || undefined, + timings: runTimings(), + toolCalls, + type: "message", + }); + + try { + const stream = client.stream({ + messages: history, + signal, + tools: definitions.length > 0 ? definitions : undefined, + }); + + for await (const event of stream) { + if (event.type === "text") { + content += event.delta; + yield event; + } else if (event.type === "reasoning") { + reasoning += event.delta; + yield event; + } else if (event.type === "tool_calls") { + partialCalls = event.toolCalls; + yield { toolCalls: partialCalls, type: "tool_call_delta" }; + } else if (event.type === "timings") { + if (event.timings) { + lastTimings = event.timings; + turnTimings = event.timings; + } + + yield { ...event, llm: event.timings && addTimings(totals.llm, event.timings) }; + } else { + yield event; + } + } + + if (turnTimings) { + totals.llm = addTimings(totals.llm, turnTimings); + stats.llm = addTimings(stats.llm, turnTimings); + } + } catch (error) { + // keep the partial output in both cases + yield lastMessage(); + + if (signal?.aborted) { + yield done("aborted"); + } else { + yield { + error: error instanceof Error ? error : new Error("LLM stream error"), + timings: runTimings(), + type: "error", + }; + } + + return; + } + + // a client can swallow the abort and end the stream normally: do not take a cut tool call for a complete one + if (signal?.aborted) { + yield lastMessage(); + yield done("aborted"); + + return; + } + + if (interrupted()) { + yield lastMessage(partialCalls.length > 0 ? toToolCalls(partialCalls) : undefined); + yield done("interrupted"); + + return; + } + + if (partialCalls.length === 0) { + totals.perTurn.push(stats); + + const timings = runTimings(); + + yield lastMessage(); + + if (timings) yield { timings, type: "turn_end" }; + + yield done("complete"); + + return; + } + + const toolCalls = toToolCalls(partialCalls); + + yield { + content, + final: false, + reasoning: reasoning || undefined, + timings: turnTimings, + toolCalls, + type: "message", + }; + + history.push({ + content: content || undefined, + reasoning_content: reasoning || undefined, + role: "assistant", + tool_calls: toolCalls, + }); + + for (let i = 0; i < toolCalls.length; i++) { + const toolCall = toolCalls[i]; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + if (interrupted()) { + for (const skippedCall of toolCalls.slice(i)) { + yield { + result: { content: INTERRUPTED_TOOL_RESULT }, + skipped: true, + toolCall: skippedCall, + type: "tool_result", + }; + + history.push({ + content: INTERRUPTED_TOOL_RESULT, + role: "tool", + tool_call_id: skippedCall.id, + }); + } + + break; + } + + yield { toolCall, type: "tool_call" }; + + const tool = toolsByName.get(toolCall.function.name); + const startTime = performance.now(); + + let result: ToolResult; + + if (!tool) { + result = { content: `Error: Unknown tool: ${toolCall.function.name}`, isError: true }; + } else { + // only the latest update matters, so a slow consumer skips the ones in between + let pendingUpdate: string | undefined; + let settled = false; + let wake: (() => void) | undefined; + + const notify = () => { + wake?.(); + wake = undefined; + }; + const execution = Promise.resolve() + .then(() => + tool.execute(toolCall, { + signal, + update: (updated) => { + pendingUpdate = updated; + notify(); + }, + }), + ) + .finally(() => { + settled = true; + notify(); + }); + + // the rejection is handled below, after the updates are drained + execution.catch(() => {}); + + while (true) { + if (pendingUpdate !== undefined) { + const updated = pendingUpdate; + + pendingUpdate = undefined; + yield { content: updated, toolCall, type: "tool_update" }; + } else if (settled) { + break; + } else { + await new Promise((resolve) => (wake = resolve)); + } + } + + try { + result = await execution; + } catch (error) { + if (isAbortError(error)) { + yield done("aborted"); + + return; + } + + result = { content: `Error: ${errorMessage(error)}`, isError: true }; + } + } + + const durationMs = Math.round(result.durationMs ?? performance.now() - startTime); + const timing = { + duration_ms: durationMs, + name: toolCall.function.name, + success: !result.isError, + }; + + totals.toolCalls.push(timing); + totals.toolCallsCount++; + totals.toolsMs += durationMs; + stats.toolCalls.push(timing); + stats.toolsMs += durationMs; + + if (signal?.aborted) { + yield done("aborted"); + + return; + } + + yield { result, skipped: false, toolCall, type: "tool_result" }; + + history.push({ + content: result.parts?.length + ? [{ text: result.content, type: "text" }, ...result.parts] + : result.content, + role: "tool", + tool_call_id: toolCall.id, + }); + } + + if (stats.toolCalls.length > 0) { + totals.perTurn.push(stats); + + const timings = runTimings(); + + if (timings) yield { timings, type: "turn_end" }; + } + + if (interrupted()) { + yield done("interrupted"); + + return; + } + + turn++; + } +} diff --git a/ui/lib/harness/src/index.ts b/ui/lib/harness/src/index.ts new file mode 100644 index 000000000000..1cbaf8aded43 --- /dev/null +++ b/ui/lib/harness/src/index.ts @@ -0,0 +1,5 @@ +export { isAbortError } from "./abort.js"; +export { createHarness, INTERRUPTED_TOOL_RESULT } from "./harness.js"; +export { createOpenAIClient, type OpenAIClientOptions } from "./openai-client.js"; +export type * from "./types.js"; +export * from "./trace/index.js"; diff --git a/ui/lib/harness/src/openai-client.ts b/ui/lib/harness/src/openai-client.ts new file mode 100644 index 000000000000..c1c45d9b840d --- /dev/null +++ b/ui/lib/harness/src/openai-client.ts @@ -0,0 +1,143 @@ +import type { InferenceClient, InferenceEvent, PartialToolCall } from "./types.js"; + +const CHAT_COMPLETIONS_PATH = "/v1/chat/completions"; +const SSE_DATA_PREFIX = "data:"; +const SSE_DONE = "[DONE]"; + +export interface OpenAIClientOptions { + /** Server root, e.g. `http://localhost:8080`. */ + baseUrl: string; + apiKey?: string; + model?: string; + /** Extra fields of the request body, e.g. `temperature`. */ + params?: Record; + headers?: Record; + /** Default: the global fetch. */ + fetch?: typeof fetch; +} + +interface ToolCallDelta extends PartialToolCall { + index?: number; +} + +function mergeToolCallDeltas(toolCalls: PartialToolCall[], deltas: ToolCallDelta[]): void { + for (const delta of deltas) { + // without an index, a delta with an id opens a call and any other one continues the last call + const index = + delta.index ?? (delta.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1); + const call = (toolCalls[index] ??= { function: { arguments: "", name: "" } }); + + if (delta.id) call.id = delta.id; + + if (delta.type) call.type = delta.type; + + call.function = { + arguments: (call.function?.arguments ?? "") + (delta.function?.arguments ?? ""), + name: (call.function?.name ?? "") + (delta.function?.name ?? ""), + }; + } +} + +async function errorFromResponse(response: Response): Promise { + const body = await response.text().catch(() => ""); + + let message = body; + + try { + message = JSON.parse(body).error?.message ?? body; + } catch { + // not JSON: keep the body text + } + + return new Error(`HTTP ${response.status}${message ? `: ${message}` : ""}`); +} + +/** + * An inference client for llama-server's chat completions endpoint. It reads the `timings` and + * `prompt_progress` fields llama-server adds. + */ +export function createOpenAIClient(options: OpenAIClientOptions): InferenceClient { + const { apiKey, baseUrl, headers, model, params } = options; + const url = baseUrl.replace(/\/+$/, "") + CHAT_COMPLETIONS_PATH; + + return { + async *stream({ messages, signal, tools }): AsyncGenerator { + const response = await (options.fetch ?? fetch)(url, { + body: JSON.stringify({ ...params, messages, model, stream: true, tools }), + headers: { + "Content-Type": "application/json", + ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}), + ...headers, + }, + method: "POST", + signal, + }); + + if (!response.ok) throw await errorFromResponse(response); + + if (!response.body) throw new Error("The response has no body"); + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + const toolCalls: PartialToolCall[] = []; + + let buffer = ""; + let completionId: string | undefined; + let modelName: string | undefined; + + try { + while (true) { + const { done, value } = await reader.read(); + + if (done) return; + + buffer += decoder.decode(value, { stream: true }); + + const lines = buffer.split("\n"); + + buffer = lines.pop() ?? ""; + + for (const line of lines) { + if (!line.startsWith(SSE_DATA_PREFIX)) continue; + + const data = line.slice(SSE_DATA_PREFIX.length).trim(); + + if (data === SSE_DONE) return; + + const chunk = JSON.parse(data); + + if (chunk.error) throw new Error(chunk.error.message ?? "Stream error"); + + if (chunk.id && chunk.id !== completionId) { + completionId = chunk.id; + yield { id: chunk.id, type: "completion_id" }; + } + + if (chunk.model && chunk.model !== modelName) { + modelName = chunk.model; + yield { model: chunk.model, type: "model" }; + } + + const delta = chunk.choices?.[0]?.delta; + const reasoning = delta?.reasoning_content ?? delta?.reasoning; + + if (reasoning) yield { delta: reasoning, type: "reasoning" }; + + if (delta?.content) yield { delta: delta.content, type: "text" }; + + if (delta?.tool_calls?.length) { + mergeToolCallDeltas(toolCalls, delta.tool_calls); + yield { toolCalls: toolCalls.map((call) => ({ ...call })), type: "tool_calls" }; + } + + if (chunk.timings || chunk.prompt_progress) { + yield { progress: chunk.prompt_progress, timings: chunk.timings, type: "timings" }; + } + } + } + } finally { + reader.cancel().catch(() => {}); + } + }, + }; +} diff --git a/ui/lib/harness/src/trace/args.ts b/ui/lib/harness/src/trace/args.ts new file mode 100644 index 000000000000..7349ee49579d --- /dev/null +++ b/ui/lib/harness/src/trace/args.ts @@ -0,0 +1,158 @@ +// Reading tool-call arguments while they stream: a lenient parse for cut-off +// JSON, and a targeted read of one string field for arguments that hold +// whole files. + +const PARTIAL_JSON_CACHE_MAX_SIZE = 32; +const partialJsonCache = new Map | null>(); + +function asObject(value: unknown): Record | null { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : null; +} + +/** + * Parse tool-call arguments that may be cut short mid-stream: an open string + * and open containers are closed so the keys received so far can be read. + * Null when the arguments are not an object. Memoized, since a trace parses the + * same arguments on every streamed chunk. + */ +export function parsePartialJsonArgs(args: string): Record | null { + const cached = partialJsonCache.get(args); + + if (cached !== undefined) return cached; + + let result: Record | null; + + try { + result = asObject(JSON.parse(args)); + } catch { + result = scanPartialJson(args); + } + + if (partialJsonCache.size >= PARTIAL_JSON_CACHE_MAX_SIZE) { + partialJsonCache.delete(partialJsonCache.keys().next().value!); + } + + partialJsonCache.set(args, result); + + return result; +} + +function scanPartialJson(args: string): Record | null { + let inString = false; + let escape = false; + + const stack: ("{" | "[")[] = []; + + for (const ch of args) { + if (escape) { + escape = false; + + continue; + } + + if (ch === "\\" && inString) { + escape = true; + + continue; + } + + if (ch === '"') { + inString = !inString; + + continue; + } + + if (inString) continue; + + if (ch === "{" || ch === "[") stack.push(ch); + else if (ch === "}" || ch === "]") { + if (stack.pop() !== (ch === "}" ? "{" : "[")) return null; + } + } + + let completed = args; + + // a dangling escape: keep the backslash as a literal so the string can close + if (escape) completed += "\\"; + + if (inString) completed += '"'; + else completed = completed.replace(/,?\s*$/, ""); + + for (let i = stack.length - 1; i >= 0; i--) completed += stack[i] === "{" ? "}" : "]"; + + try { + return asObject(JSON.parse(completed)); + } catch { + return null; + } +} + +const fieldPatterns = new Map(); + +/** + * Read one string field out of tool-call arguments without parsing them all: + * write and edit tools carry whole files, and a trace line needs only the + * path. The first of `keys` that holds a string wins; undefined when none does. + */ +export function extractToolArgString(args: string, keys: readonly string[]): string | undefined { + for (const key of keys) { + let pattern = fieldPatterns.get(key); + + if (!pattern) { + pattern = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`); + fieldPatterns.set(key, pattern); + } + + const match = pattern.exec(args); + + if (!match) continue; + + try { + const value: unknown = JSON.parse(`"${match[1]}"`); + + if (typeof value === "string") return value; + } catch { + // the next key, then the caller's full parse + } + } + + return undefined; +} + +/** The file name of a path, for a trace line; undefined without a path. */ +export function fileNameFromPath(path: string | undefined): string | undefined { + if (!path) return undefined; + + return path.split(/[\\/]/).pop() || path; +} + +/** + * Memoize `fn` by a string key, holding at most `maxSize` results; a full cache + * is emptied, which suits values that are cheap to rebuild. `keyOf` returns + * null for a call not worth caching. + */ +export function memoizeBounded( + fn: (...args: Args) => Result, + keyOf: (...args: Args) => string | null, + maxSize: number, +): (...args: Args) => Result { + const cache = new Map(); + + return (...args) => { + const key = keyOf(...args); + + if (key === null) return fn(...args); + + if (cache.has(key)) return cache.get(key) as Result; + + const result = fn(...args); + + if (cache.size >= maxSize) cache.clear(); + + cache.set(key, result); + + return result; + }; +} diff --git a/ui/lib/harness/src/trace/index.ts b/ui/lib/harness/src/trace/index.ts new file mode 100644 index 000000000000..75dfc649e255 --- /dev/null +++ b/ui/lib/harness/src/trace/index.ts @@ -0,0 +1,33 @@ +export { extractToolArgString, fileNameFromPath, parsePartialJsonArgs } from "./args.js"; +export { + createTracePhraser, + formatToolCallLine, + groupToolCallRuns, + humanizeArgKey, + isReasoningStep, + isToolCallRunning, + isToolCallStep, + LLAMA_SERVER_TOOL_PHRASING, + llamaServerToolResolver, + simpleToolArgFields, + TOOL_ARG_PATH_KEYS, + TOOL_CALL_MAIN_ARG_KEYS, + TOOL_CALL_SHOWN_ARG_DEFAULT, + TOOL_CALL_SIMPLE_ARG_MAX_CHARS, + TOOL_CALL_SUMMARY, + TOOL_CALL_TARGET_MAX_CHARS, + TOOL_CALL_THINKING_LABEL, + toolCallPath, + type TracePhraser, + type TracePhraserOptions, +} from "./phrasing.js"; +export { ToolCallSummaryKind, TraceStepType } from "./types.js"; +export type { + ResolvedToolCall, + ToolArgField, + ToolCallDescription, + ToolCallInput, + ToolCallPhrasing, + ToolCallResolver, + TraceStep, +} from "./types.js"; diff --git a/ui/lib/harness/src/trace/phrasing.ts b/ui/lib/harness/src/trace/phrasing.ts new file mode 100644 index 000000000000..1cbd02508574 --- /dev/null +++ b/ui/lib/harness/src/trace/phrasing.ts @@ -0,0 +1,497 @@ +// Plain-language lines for the tool calls of an agent trace: what one call did +// ("Read a file sheet_new.jpg"), what it is doing now ("Reading package.json") +// and what a run of calls did ("Ran 3 commands, read 2 files"). A call that +// has the argument the app picks (`description` by default) shows it as the +// model wrote it. Otherwise the app's resolvers phrase it, then llama-server's +// built-in tools, then a phrasing table, and any other tool reads as +// "Used " with its main argument. + +import { extractToolArgString, fileNameFromPath, memoizeBounded, parsePartialJsonArgs } from "./args.js"; +import { + type ResolvedToolCall, + type ToolArgField, + type ToolCallDescription, + type ToolCallInput, + type ToolCallPhrasing, + type ToolCallResolver, + ToolCallSummaryKind, + type TraceStep, + TraceStepType, +} from "./types.js"; + +/** Longest target shown after the verb before it is cut with "...". */ +export const TOOL_CALL_TARGET_MAX_CHARS = 60; + +/** Arguments of a short, one-line value read as fields instead of JSON. */ +export const TOOL_CALL_SIMPLE_ARG_MAX_CHARS = 200; + +/** The argument a call's line shows when the call has it: the model's own words for it. */ +export const TOOL_CALL_SHOWN_ARG_DEFAULT = "description"; + +/** Live title of a run of calls while the model thinks inside it. */ +export const TOOL_CALL_THINKING_LABEL = "Thinking"; + +/** Arguments a tool without a phrasing is described by; the first one present wins. */ +export const TOOL_CALL_MAIN_ARG_KEYS: readonly string[] = [ + "query", + "q", + "path", + "file_path", + "filePath", + "url", + "name", + "command", + "pattern", + "prompt", + "text", + "id", +]; + +/** Argument names a path can come under. */ +export const TOOL_ARG_PATH_KEYS: readonly string[] = ["path", "file_path", "filePath"]; + +function counted(n: number, singular: string, plural: string): string { + return `${n} ${n === 1 ? singular : plural}`; +} + +/** The group summary's clause per kind, in lower case; the summary capitalizes the first. */ +export const TOOL_CALL_SUMMARY: Readonly string>> = { + [ToolCallSummaryKind.COMMAND]: (n) => `ran ${counted(n, "command", "commands")}`, + [ToolCallSummaryKind.EDIT]: (n) => `edited ${counted(n, "file", "files")}`, + [ToolCallSummaryKind.LOAD_TOOLS]: (n) => `loaded ${counted(n, "tool", "tools")}`, + [ToolCallSummaryKind.OTHER]: (n) => `used ${counted(n, "tool", "tools")}`, + [ToolCallSummaryKind.READ]: (n) => `read ${counted(n, "file", "files")}`, + [ToolCallSummaryKind.SCRIPT]: (n) => `ran ${counted(n, "script", "scripts")}`, + [ToolCallSummaryKind.SEARCH]: (n) => (n === 1 ? "searched once" : `searched ${n} times`), + [ToolCallSummaryKind.VIEW]: (n) => `viewed ${counted(n, "media file", "media files")}`, + [ToolCallSummaryKind.WRITE]: (n) => `wrote ${counted(n, "file", "files")}`, +}; + +/** How llama-server's built-in tools read (`--tools`). */ +export const LLAMA_SERVER_TOOL_PHRASING: Readonly> = { + edit_file: { object: "a file", past: "Edited", present: "Editing", summary: ToolCallSummaryKind.EDIT }, + exec_shell_command: { + object: "a command", + past: "Ran", + present: "Running", + summary: ToolCallSummaryKind.COMMAND, + }, + file_glob_search: { + object: "files", + past: "Listed", + present: "Listing", + quoteTarget: true, + summary: ToolCallSummaryKind.SEARCH, + targetObject: "files matching", + }, + get_info: { object: "runtime info", past: "Checked", present: "Checking", summary: ToolCallSummaryKind.OTHER }, + grep_search: { + object: "files", + past: "Searched", + present: "Searching", + quoteTarget: true, + summary: ToolCallSummaryKind.SEARCH, + targetObject: "for", + }, + read_file: { object: "a file", past: "Read", present: "Reading", summary: ToolCallSummaryKind.READ }, + write_file: { object: "a file", past: "Wrote", present: "Writing", summary: ToolCallSummaryKind.WRITE }, +}; + +function stringArg(args: Record | null, key: string): string | undefined { + const value = args?.[key]; + + return typeof value === "string" && value.trim() ? value : undefined; +} + +/** The path of a call, read without parsing arguments that may hold a whole file. */ +export function toolCallPath(call: ToolCallInput): string | undefined { + return extractToolArgString(call.rawArgs, TOOL_ARG_PATH_KEYS) ?? stringArg(call.args(), "path"); +} + +/** Phrases llama-server's built-in tools, with what each acted on. */ +export const llamaServerToolResolver: ToolCallResolver = (call) => { + const phrasing = LLAMA_SERVER_TOOL_PHRASING[call.name]; + + if (!phrasing) return undefined; + + switch (call.name) { + case "read_file": + case "write_file": + case "edit_file": + return { phrasing, target: fileNameFromPath(toolCallPath(call)) }; + + case "exec_shell_command": + // the targeted read keeps the command in the line while a later + // argument still streams and the JSON does not parse + return { + phrasing, + target: stringArg(call.args(), "command") ?? extractToolArgString(call.rawArgs, ["command"]), + }; + + case "grep_search": + return { phrasing, target: stringArg(call.args(), "pattern") }; + + case "file_glob_search": { + const include = stringArg(call.args(), "include"); + + return { phrasing, target: include && include !== "**" ? include : undefined }; + } + } + + return { phrasing }; +}; + +function shorten(text: string): string { + const oneLine = text.replace(/\s+/g, " ").trim(); + + return oneLine.length > TOOL_CALL_TARGET_MAX_CHARS + ? `${oneLine.slice(0, TOOL_CALL_TARGET_MAX_CHARS - 3)}...` + : oneLine; +} + +function genericMainArg(args: Record | null): string | undefined { + if (!args) return undefined; + + for (const key of TOOL_CALL_MAIN_ARG_KEYS) { + const value = stringArg(args, key); + + if (value) return value; + } + + for (const value of Object.values(args)) { + if (typeof value === "number") return String(value); + + if (typeof value === "string" && value.trim() && value.length <= TOOL_CALL_TARGET_MAX_CHARS) { + return value; + } + } + + return undefined; +} + +function genericPhrasing(toolName: string): ToolCallPhrasing { + return { + object: toolName, + past: "Used", + present: "Using", + summary: ToolCallSummaryKind.OTHER, + targetObject: toolName, + }; +} + +/** Results each cache below holds. */ +const CACHE_MAX_SIZE = 256; +/** Arguments longer than this (whole files) are not worth holding as cache keys. */ +const CACHE_MAX_ARGS_CHARS = 2000; + +/** An argument name an app can pick: a plain key, so it is safe in a pattern. */ +const SHOWN_ARG_PATTERN = /^[\w-]+$/; + +/** The value of the argument a call's line shows, when the call has it. */ +function shownArgValue(toolArgs: string, shownArg: string | null): string | undefined { + if (!shownArg || !toolArgs || !SHOWN_ARG_PATTERN.test(shownArg)) return undefined; + + const value = + toolArgs.length <= CACHE_MAX_ARGS_CHARS + ? stringArg(parsePartialJsonArgs(toolArgs), shownArg) + : extractToolArgString(toolArgs, [shownArg]); + + return value?.trim() || undefined; +} + +/** One line of plain text for a description, e.g. `Searched for 'issue'`. */ +export function formatToolCallLine(description: ToolCallDescription): string { + if (!description.target) return description.label; + + const target = description.quoted ? `'${description.target}'` : description.target; + + return `${description.label} ${target}`; +} + +export function isToolCallStep(step: TraceStep): boolean { + return ( + step.type === TraceStepType.TOOL_CALL || + step.type === TraceStepType.TOOL_CALL_PENDING || + step.type === TraceStepType.TOOL_CALL_STREAMING + ); +} + +export function isReasoningStep(step: TraceStep): boolean { + return step.type === TraceStepType.REASONING || step.type === TraceStepType.REASONING_PENDING; +} + +/** True while the call has no result yet and the reply is still streaming. */ +export function isToolCallRunning(step: TraceStep, isStreaming: boolean): boolean { + return ( + isStreaming && + (step.type === TraceStepType.TOOL_CALL_PENDING || step.type === TraceStepType.TOOL_CALL_STREAMING) + ); +} + +export interface TracePhraserOptions { + /** The app's own tools, tried in order before llama-server's built-in ones. */ + resolvers?: readonly ToolCallResolver[]; + /** Phrasing for tools whose line names no target, by tool name. */ + phrasings?: Readonly>; +} + +export interface TracePhraser { + /** + * One tool call as a short sentence, in the past tense once it is done and + * the present tense while `running`. `shownArg` names the argument shown + * instead when the call has it (null for none). + */ + describeToolCall( + toolName: string | undefined, + toolArgs: string | undefined, + running?: boolean, + shownArg?: string | null, + ): ToolCallDescription; + /** A run of calls in one line, e.g. "Ran 3 commands, read 2 files". */ + summarizeToolCalls(steps: readonly TraceStep[]): string; + /** + * What a run of calls is doing now ("Running a command", "Thinking"): the + * model thinking at its end, or the last call still running; null when neither. + */ + describeToolActivity( + steps: readonly TraceStep[], + isStreaming: boolean, + executingToolCallId?: string | null, + shownArgFor?: (toolName: string | undefined) => string | null, + ): string | null; +} + +/** Phrasing for an app's traces: its own tools first, then llama-server's, then any tool. */ +export function createTracePhraser(options: TracePhraserOptions = {}): TracePhraser { + const resolvers = [...(options.resolvers ?? []), llamaServerToolResolver]; + const phrasings = options.phrasings ?? {}; + + function resolveCall(name: string, rawArgs: string): ResolvedToolCall { + let parsed: Record | null | undefined; + + const call: ToolCallInput = { + args: () => (parsed === undefined ? (parsed = rawArgs ? parsePartialJsonArgs(rawArgs) : null) : parsed), + name, + rawArgs, + }; + + for (const resolve of resolvers) { + const resolved = resolve(call); + + if (resolved) return resolved; + } + + const known = phrasings[name]; + + if (known) return { phrasing: known }; + + return { phrasing: genericPhrasing(name), target: genericMainArg(call.args()) }; + } + + function buildDescription( + name: string, + args: string, + running: boolean, + shownArg: string | null, + ): ToolCallDescription { + const { count = 1, phrasing, target } = resolveCall(name, args); + const shown = shownArgValue(args, shownArg); + // an argument the line already shows as its target (a shell command) would only repeat it + const described = shown && shown !== target?.trim() ? shown : undefined; + + if (described) { + return { + count, + described: true, + // as the model wrote it: rewriting its tense by rule mangles anything + // that does not start with a plain verb + label: shorten(described).replace(/[.\s]+$/, ""), + quoted: false, + summary: phrasing.summary, + }; + } + + const verb = running ? phrasing.present : phrasing.past; + const shortTarget = target ? shorten(target) : undefined; + const object = shortTarget ? phrasing.targetObject : phrasing.object; + + return { + count, + label: object ? `${verb} ${object}` : verb, + quoted: Boolean(phrasing.quoteTarget && shortTarget), + summary: phrasing.summary, + target: shortTarget, + }; + } + + // A trace is rebuilt on every streamed chunk, so the same finished call is + // described again and again: remember the answer for its arguments. Every + // caller of one call reads the same frozen object. + const describeCached = memoizeBounded( + (name: string, args: string, running: boolean, shownArg: string) => + Object.freeze(buildDescription(name, args, running, shownArg || null)), + (name, args, running, shownArg) => + args.length <= CACHE_MAX_ARGS_CHARS ? `${running ? 1 : 0}\0${shownArg}\0${name}\0${args}` : null, + CACHE_MAX_SIZE, + ); + + const describeToolCall: TracePhraser["describeToolCall"] = ( + toolName, + toolArgs, + running = false, + shownArg = TOOL_CALL_SHOWN_ARG_DEFAULT, + ) => describeCached(toolName || "a tool", toolArgs ?? "", running, shownArg ?? ""); + + return { + describeToolActivity(steps, isStreaming, executingToolCallId, shownArgFor = () => TOOL_CALL_SHOWN_ARG_DEFAULT) { + // the model thinking at the end of the run, between calls or before its answer + if (isStreaming && steps.at(-1)?.type === TraceStepType.REASONING_PENDING) { + return TOOL_CALL_THINKING_LABEL; + } + + for (let i = steps.length - 1; i >= 0; i--) { + const step = steps[i]; + const executing = step.toolCallId !== undefined && step.toolCallId === executingToolCallId; + + if (executing || isToolCallRunning(step, isStreaming)) { + return formatToolCallLine(describeToolCall(step.toolName, step.toolArgs, true, shownArgFor(step.toolName))); + } + } + + return null; + }, + + describeToolCall, + + summarizeToolCalls(steps) { + const counts = new Map(); + + for (const step of steps) { + if (!isToolCallStep(step)) continue; + + const { count, summary } = describeToolCall(step.toolName, step.toolArgs); + + counts.set(summary, (counts.get(summary) ?? 0) + count); + } + + // kinds keep the order they first appear in; other tools come last + const other = counts.get(ToolCallSummaryKind.OTHER); + + if (other !== undefined) { + counts.delete(ToolCallSummaryKind.OTHER); + counts.set(ToolCallSummaryKind.OTHER, other); + } + + const text = [...counts].map(([kind, n]) => TOOL_CALL_SUMMARY[kind](n)).join(", "); + + return text.charAt(0).toUpperCase() + text.slice(1); + }, + }; +} + +/** + * Tool arguments as labelled fields when every value is a short, one-line + * scalar; null when they need the JSON view instead. Memoized: the row that + * shows them re-renders on every chunk. + */ +export function simpleToolArgFields(toolArgs: string | undefined): ToolArgField[] | null { + return toolArgs ? argFieldsCached(toolArgs) : null; +} + +const argFieldsCached = memoizeBounded( + buildSimpleToolArgFields, + (toolArgs) => (toolArgs.length <= CACHE_MAX_ARGS_CHARS ? toolArgs : null), + CACHE_MAX_SIZE, +); + +function buildSimpleToolArgFields(toolArgs: string): ToolArgField[] | null { + let parsed: unknown; + + try { + parsed = JSON.parse(toolArgs); + } catch { + return null; + } + + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; + + const entries = Object.entries(parsed as Record); + + if (entries.length === 0) return null; + + const fields: ToolArgField[] = []; + + for (const [key, value] of entries) { + if (value !== null && typeof value === "object") return null; + + const text = String(value); + + if (text.length > TOOL_CALL_SIMPLE_ARG_MAX_CHARS || text.includes("\n")) return null; + + fields.push({ label: humanizeArgKey(key), value: text }); + } + + return fields; +} + +/** `max_results` / `maxResults` -> `Max results`. */ +export function humanizeArgKey(key: string): string { + const words = key + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .replace(/[_-]+/g, " ") + .trim() + .toLowerCase(); + + return words.charAt(0).toUpperCase() + words.slice(1); +} + +/** + * Split step positions into single items and runs of tool work, e.g. + * [0, [1, 2, 3], 4]. A run is the calls and all the reasoning around them, up + * to the next text, so the answer follows the work as one row: it is grouped + * once it holds `minCalls` calls, or one call with reasoning beside it. + * Reasoning with no call in reach, and text, stay apart. + */ +export function groupToolCallRuns( + steps: readonly TraceStep[], + indices: readonly number[], + minCalls: number, +): (number | number[])[] { + const items: (number | number[])[] = []; + + let run: number[] = []; + let calls = 0; + // reasoning seen since the last call: it ends the run if text follows, and + // leads into it if another call does + let thinking: number[] = []; + + const flush = () => { + const whole = [...run, ...thinking]; + + if (calls >= minCalls || (calls > 0 && whole.length > calls)) items.push(whole); + else items.push(...whole); + + run = []; + thinking = []; + calls = 0; + }; + + for (const index of indices) { + const step = steps[index]; + + if (isToolCallStep(step)) { + run.push(...thinking, index); + thinking = []; + calls++; + } else if (isReasoningStep(step)) { + thinking.push(index); + } else { + flush(); + items.push(index); + } + } + + flush(); + + return items; +} diff --git a/ui/lib/harness/src/trace/types.ts b/ui/lib/harness/src/trace/types.ts new file mode 100644 index 000000000000..f445e6805427 --- /dev/null +++ b/ui/lib/harness/src/trace/types.ts @@ -0,0 +1,94 @@ +/** + * What a step of an agent trace is: the model's text, its reasoning, or a tool + * call, finished or still in flight. Apps keep their own step type; anything + * with these values in `type` reads as a trace step. + */ +export const TraceStepType = { + REASONING: "reasoning", + REASONING_PENDING: "reasoning_pending", + TEXT: "text", + TOOL_CALL: "tool_call", + TOOL_CALL_PENDING: "tool_call_pending", + TOOL_CALL_STREAMING: "tool_call_streaming", +} as const; + +export type TraceStepType = (typeof TraceStepType)[keyof typeof TraceStepType]; + +/** One step of an agent trace, as much of it as the phrasing reads. */ +export interface TraceStep { + /** A TraceStepType value. */ + type: string; + toolCallId?: string; + toolName?: string; + /** The call's arguments as streamed: JSON, possibly cut short. */ + toolArgs?: string; +} + +/** Which clause a call counts under in a group summary ("ran 3 commands"). */ +export const ToolCallSummaryKind = { + COMMAND: "command", + EDIT: "edit", + LOAD_TOOLS: "load_tools", + OTHER: "other", + READ: "read", + SCRIPT: "script", + SEARCH: "search", + VIEW: "view", + WRITE: "write", +} as const; + +export type ToolCallSummaryKind = (typeof ToolCallSummaryKind)[keyof typeof ToolCallSummaryKind]; + +/** How a tool call reads in a trace. */ +export interface ToolCallPhrasing { + /** Verb once the call is done, e.g. "Read". */ + past: string; + /** Verb while the call runs, e.g. "Reading". */ + present: string; + /** Words after the verb when the call has no target, e.g. "a file". */ + object: string; + /** Words between the verb and the target, e.g. "for". */ + targetObject?: string; + /** Show the target in quotes, for search terms. */ + quoteTarget?: boolean; + summary: ToolCallSummaryKind; +} + +/** A tool call as one plain sentence: label, then an optional target. */ +export interface ToolCallDescription { + /** Verb and object, e.g. "Read a file" or "Searched for". */ + label: string; + /** What the call acted on, e.g. a file name or a search term. */ + target?: string; + quoted: boolean; + summary: ToolCallSummaryKind; + /** How many things the call counts as in the group summary. */ + count: number; + /** True when the label is the model's own description of the call. */ + described?: boolean; +} + +/** A tool call as a resolver sees it. */ +export interface ToolCallInput { + name: string; + /** The arguments as streamed. Whole files for write tools: read them with extractToolArgString. */ + rawArgs: string; + /** The arguments parsed leniently, cut-off JSON included; parsed on first call. */ + args(): Record | null; +} + +/** How one call reads: its phrasing, what it acted on, and how many things it counts as. */ +export interface ResolvedToolCall { + phrasing: ToolCallPhrasing; + target?: string; + count?: number; +} + +/** Phrases the calls of one tool, or of a family of tools; undefined passes the call on. */ +export type ToolCallResolver = (call: ToolCallInput) => ResolvedToolCall | undefined; + +/** A tool argument shown as a labelled field. */ +export interface ToolArgField { + label: string; + value: string; +} diff --git a/ui/lib/harness/src/types.ts b/ui/lib/harness/src/types.ts new file mode 100644 index 000000000000..9167e37ca111 --- /dev/null +++ b/ui/lib/harness/src/types.ts @@ -0,0 +1,209 @@ +// Messages and tools use the OpenAI chat-completions shapes, so they go to the endpoint as they are. + +export interface TextPart { + type: "text"; + text: string; +} + +export interface ImagePart { + type: "image_url"; + image_url: { url: string }; +} + +export interface AudioPart { + type: "input_audio"; + input_audio: { data: string; format: string }; +} + +export type ContentPart = TextPart | ImagePart | AudioPart; + +export interface ToolCall { + id: string; + type: "function"; + function: { name: string; arguments: string }; +} + +/** A tool call as it streams in: any field can still be missing. */ +export interface PartialToolCall { + id?: string; + type?: string; + function?: { name?: string; arguments?: string }; +} + +export type Message = + | { role: "system" | "user"; content: string | ContentPart[] } + | { + role: "assistant"; + content?: string | ContentPart[]; + reasoning_content?: string; + tool_calls?: ToolCall[]; + } + | { role: "tool"; tool_call_id: string; content: string | ContentPart[] }; + +export interface ToolDefinition { + type: "function"; + function: { + name: string; + description?: string; + parameters?: Record; + }; +} + +export interface ToolContext { + signal?: AbortSignal; + /** Report the output so far of a tool that streams. Each call replaces the previous content. */ + update(content: string): void; +} + +export interface ToolResult { + /** Text the model reads. */ + content: string; + /** Media the model reads after the text, e.g. an image the tool produced. */ + parts?: ContentPart[]; + isError?: boolean; + /** Set it when the tool times itself, e.g. to leave out a wait for approval. Default: the time execute took. */ + durationMs?: number; + /** App data the loop does not read. It comes back on the tool_result event. */ + details?: unknown; +} + +export interface Tool { + definition: ToolDefinition; + /** Run the call. Reject with an AbortError to end the run, with any other error to report it to the model. */ + execute(call: ToolCall, context: ToolContext): Promise; +} + +/** Token counts and times of one request, as llama-server reports them. */ +export interface LlmTimings { + cache_n?: number; + predicted_ms?: number; + predicted_n?: number; + prompt_ms?: number; + prompt_n?: number; +} + +export interface LlmTotals { + predicted_ms: number; + predicted_n: number; + prompt_ms: number; + prompt_n: number; +} + +export interface ToolCallTiming { + name: string; + duration_ms: number; + success: boolean; +} + +export interface TurnStats { + turn: number; + llm: LlmTotals; + toolCalls: ToolCallTiming[]; + toolsMs: number; +} + +/** Totals of a run: every turn's requests and tool calls. */ +export interface RunTimings { + turns: number; + toolCallsCount: number; + toolsMs: number; + toolCalls: ToolCallTiming[]; + perTurn: TurnStats[]; + llm: LlmTotals; +} + +/** The last request's timings, with the run's totals once a tool has run. */ +export interface Timings extends LlmTimings { + agentic?: RunTimings; +} + +export interface PromptProgress { + cache: number; + processed: number; + time_ms: number; + total: number; +} + +export interface InferenceRequest { + messages: Message[]; + tools?: ToolDefinition[]; + signal?: AbortSignal; +} + +export type InferenceEvent = + | { type: "text"; delta: string } + | { type: "reasoning"; delta: string } + /** Every tool call of the response so far, not only the new part. */ + | { type: "tool_calls"; toolCalls: PartialToolCall[] } + | { type: "timings"; timings?: LlmTimings; progress?: PromptProgress } + | { type: "model"; model: string } + | { type: "completion_id"; id: string }; + +/** + * One streamed chat completion. The loop needs nothing else from llama-server. + * Timings, model and completion id are optional extras. + */ +export interface InferenceClient { + stream(request: InferenceRequest): AsyncIterable; +} + +export type DoneReason = + /** The model answered without calling a tool. */ + | "complete" + | "aborted" + /** `interrupted` returned true. */ + | "interrupted" + /** The turn limit was reached and `onTurnLimit` did not grant more turns. */ + | "turn_limit"; + +export type HarnessEvent = + /** `turn` starts at 1, and again at 1 once `onTurnLimit` grants more turns. */ + | { type: "turn_start"; turn: number } + | { type: "text"; delta: string } + | { type: "reasoning"; delta: string } + | { type: "tool_call_delta"; toolCalls: PartialToolCall[] } + /** `llm` is the run's totals including the request in flight. */ + | { type: "timings"; timings?: LlmTimings; progress?: PromptProgress; llm?: LlmTotals } + | { type: "model"; model: string } + | { type: "completion_id"; id: string } + /** The assistant message of a turn. `final` is true when the run ends after it and none of its tool calls runs. */ + | { + type: "message"; + content: string; + reasoning?: string; + toolCalls?: ToolCall[]; + timings?: Timings; + final: boolean; + } + | { type: "tool_call"; toolCall: ToolCall } + | { type: "tool_update"; toolCall: ToolCall; content: string } + /** `skipped` is true when the call did not run because the run was interrupted. */ + | { type: "tool_result"; toolCall: ToolCall; result: ToolResult; skipped: boolean } + | { type: "turn_end"; timings: Timings } + | { type: "done"; reason: DoneReason; timings?: Timings } + | { type: "error"; error: Error; timings?: Timings }; + +export interface RunOptions { + /** Turns before `onTurnLimit` is asked. Default: no limit. */ + maxTurns?: number; + /** Resolve true to run `maxTurns` more turns. Default: the run ends. */ + onTurnLimit?: (signal?: AbortSignal) => Promise; + /** + * Return true to end the run at the next safe point, e.g. when the user sent a new message. Tool calls that did + * not run yet get a result that says so. Use `signal` to stop at once. + */ + interrupted?: () => boolean; +} + +/** + * The contract an app runs a loop through. `run` never throws: it ends with a `done` or an `error` event. It waits + * for the consumer between events, so the consumer can store each one before the loop goes on. + */ +export interface Harness { + run( + messages: Message[], + tools: Tool[], + signal?: AbortSignal, + options?: RunOptions, + ): AsyncIterable; +} diff --git a/ui/lib/harness/tests/harness.test.ts b/ui/lib/harness/tests/harness.test.ts new file mode 100644 index 000000000000..4e302a14c5fe --- /dev/null +++ b/ui/lib/harness/tests/harness.test.ts @@ -0,0 +1,316 @@ +import { describe, expect, it } from "vitest"; +import { + createHarness, + INTERRUPTED_TOOL_RESULT, + type HarnessEvent, + type InferenceClient, + type InferenceEvent, + type InferenceRequest, + type Message, + type RunOptions, + type Tool, + type ToolResult, +} from "../src/index.js"; + +const USER: Message[] = [{ content: "hi", role: "user" }]; + +function callEvent(...names: string[]): InferenceEvent { + return { + toolCalls: names.map((name, index) => ({ + function: { arguments: "{}", name }, + id: `call_${index}`, + })), + type: "tool_calls", + }; +} + +// a client that plays one scripted turn per request and records what it was sent +function scriptedClient(turns: Array) { + const requests: InferenceRequest[] = []; + const client: InferenceClient = { + async *stream(request) { + requests.push({ ...request, messages: [...request.messages] }); + + const turn = turns[requests.length - 1] ?? []; + + if (turn instanceof Error) throw turn; + + yield* turn; + }, + }; + + return { client, requests }; +} + +function tool( + name: string, + execute: Tool["execute"] = async () => ({ content: `${name} ran` }), +): Tool { + return { definition: { function: { name }, type: "function" }, execute }; +} + +async function collect( + client: InferenceClient, + tools: Tool[] = [], + options?: RunOptions, + signal?: AbortSignal, +): Promise { + const events: HarnessEvent[] = []; + + for await (const event of createHarness(client).run(USER, tools, signal, options)) + events.push(event); + + return events; +} + +function types(events: HarnessEvent[]): string[] { + return events.map((event) => event.type); +} + +function last(events: HarnessEvent[]): HarnessEvent { + return events[events.length - 1]; +} + +function results(events: HarnessEvent[]) { + return events.filter((event) => event.type === "tool_result"); +} + +describe("createHarness", () => { + it("ends after a turn without tool calls", async () => { + const { client, requests } = scriptedClient([ + [ + { delta: "think", type: "reasoning" }, + { delta: "Hel", type: "text" }, + { delta: "lo", type: "text" }, + ], + ]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "reasoning", "text", "text", "message", "done"]); + expect(events[4]).toMatchObject({ content: "Hello", final: true, reasoning: "think" }); + expect(last(events)).toMatchObject({ reason: "complete" }); + expect(requests[0].tools).toBeUndefined(); + }); + + it("runs the called tool and sends its result with the next request", async () => { + const { client, requests } = scriptedClient([ + [{ delta: "let me look", type: "text" }, callEvent("read")], + [{ delta: "done", type: "text" }], + ]); + const events = await collect(client, [tool("read")]); + + expect(types(events)).toEqual([ + "turn_start", + "text", + "tool_call_delta", + "message", + "tool_call", + "tool_result", + "turn_end", + "turn_start", + "text", + "message", + "turn_end", + "done", + ]); + expect(events[3]).toMatchObject({ + final: false, + toolCalls: [{ id: "call_0", type: "function" }], + }); + expect(requests[1].messages.slice(1)).toEqual([ + { + content: "let me look", + reasoning_content: undefined, + role: "assistant", + tool_calls: [ + { function: { arguments: "{}", name: "read" }, id: "call_0", type: "function" }, + ], + }, + { content: "read ran", role: "tool", tool_call_id: "call_0" }, + ]); + expect(requests[0].tools).toEqual([{ function: { name: "read" }, type: "function" }]); + }); + + it("sends a result's media parts after its text", async () => { + const image = { image_url: { url: "data:image/png;base64,AAAA" }, type: "image_url" } as const; + const { client, requests } = scriptedClient([[callEvent("shot")], []]); + + await collect(client, [tool("shot", async () => ({ content: "saved", parts: [image] }))]); + + expect(requests[1].messages[2]).toEqual({ + content: [{ text: "saved", type: "text" }, image], + role: "tool", + tool_call_id: "call_0", + }); + }); + + it("reports an unknown tool and a tool that throws to the model", async () => { + const { client } = scriptedClient([[callEvent("missing", "broken")], []]); + const events = await collect(client, [ + tool("broken", async () => { + throw new Error("boom"); + }), + ]); + + expect(results(events).map((event) => event.result)).toEqual([ + { content: "Error: Unknown tool: missing", isError: true }, + { content: "Error: boom", isError: true }, + ]); + expect(last(events)).toMatchObject({ + timings: { + agentic: { toolCalls: [{ success: false }, { success: false }], toolCallsCount: 2 }, + }, + }); + }); + + it("emits a streaming tool's updates before its result", async () => { + const { client } = scriptedClient([[callEvent("shell")], []]); + const events = await collect(client, [ + tool("shell", async (_call, { update }) => { + update(""); + await Promise.resolve(); + update("a"); + update("ab"); + + return { content: "ab" }; + }), + ]); + const updates = events.filter((event) => event.type === "tool_update"); + + // "a" was replaced before the consumer asked for it + expect(updates.map((event) => event.content)).toEqual(["", "ab"]); + expect(types(events).indexOf("tool_result")).toBeGreaterThan( + types(events).lastIndexOf("tool_update"), + ); + }); + + it("uses the duration a tool reports", async () => { + const { client } = scriptedClient([[callEvent("slow")], []]); + const events = await collect(client, [ + tool("slow", async () => ({ content: "", durationMs: 1234 })), + ]); + + expect(last(events)).toMatchObject({ timings: { agentic: { toolsMs: 1234 } } }); + }); + + it("ends without a result when a tool rejects with an AbortError", async () => { + const { client, requests } = scriptedClient([[callEvent("gated")], []]); + const events = await collect(client, [ + tool("gated", async () => { + throw new DOMException("Operation was aborted", "AbortError"); + }), + ]); + + expect(results(events)).toEqual([]); + expect(last(events)).toMatchObject({ reason: "aborted" }); + expect(requests).toHaveLength(1); + }); + + it("keeps the partial output when the signal aborts mid-stream", async () => { + const controller = new AbortController(); + const client: InferenceClient = { + async *stream() { + yield { delta: "par", type: "text" }; + controller.abort(); + throw new DOMException("Operation was aborted", "AbortError"); + }, + }; + const events = await collect(client, [], undefined, controller.signal); + + expect(types(events)).toEqual(["turn_start", "text", "message", "done"]); + expect(events[2]).toMatchObject({ content: "par", final: true }); + expect(last(events)).toMatchObject({ reason: "aborted" }); + }); + + it("ends with an error event when the stream fails", async () => { + const { client } = scriptedClient([new Error("HTTP 500")]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "message", "error"]); + expect(last(events)).toMatchObject({ error: { message: "HTTP 500" } }); + }); + + it("keeps the tool calls of the turn it is interrupted after, and runs none", async () => { + const { client, requests } = scriptedClient([[callEvent("read")], []]); + const events = await collect(client, [tool("read")], { interrupted: () => true }); + + expect(types(events)).toEqual(["turn_start", "tool_call_delta", "message", "done"]); + expect(events[2]).toMatchObject({ final: true, toolCalls: [{ id: "call_0" }] }); + expect(last(events)).toMatchObject({ reason: "interrupted" }); + expect(requests).toHaveLength(1); + }); + + it("skips the tool calls left when it is interrupted between two", async () => { + let interrupted = false; + + const { client, requests } = scriptedClient([[callEvent("first", "second", "third")], []]); + const events = await collect( + client, + [ + tool("first", async (): Promise => { + interrupted = true; + + return { content: "first ran" }; + }), + tool("second"), + tool("third"), + ], + { interrupted: () => interrupted }, + ); + + expect(results(events).map((event) => [event.result.content, event.skipped])).toEqual([ + ["first ran", false], + [INTERRUPTED_TOOL_RESULT, true], + [INTERRUPTED_TOOL_RESULT, true], + ]); + expect(last(events)).toMatchObject({ reason: "interrupted" }); + expect(requests).toHaveLength(1); + }); + + it("asks at the turn limit and starts the turn count again when it goes on", async () => { + const answers = [true, false]; + const { client } = scriptedClient([[callEvent("read")], [callEvent("read")], []]); + const events = await collect(client, [tool("read")], { + maxTurns: 1, + onTurnLimit: async () => answers.shift() ?? false, + }); + const turns = events.filter((event) => event.type === "turn_start"); + + expect(turns.map((event) => event.turn)).toEqual([1, 1]); + expect(last(events)).toMatchObject({ reason: "turn_limit" }); + }); + + it("adds up the timings of every turn", async () => { + const timings = (n: number): InferenceEvent => ({ + timings: { cache_n: 1, predicted_ms: n, predicted_n: n, prompt_ms: n, prompt_n: n }, + type: "timings", + }); + const { client } = scriptedClient([[timings(10), callEvent("read")], [timings(5)]]); + const events = await collect(client, [tool("read")]); + const live = events + .filter((event) => event.type === "timings") + .map((event) => event.llm?.predicted_n); + + expect(live).toEqual([10, 15]); + expect(last(events)).toMatchObject({ + timings: { + agentic: { + llm: { predicted_ms: 15, predicted_n: 15, prompt_ms: 15, prompt_n: 15 }, + perTurn: [{ turn: 1 }, { turn: 2 }], + toolCallsCount: 1, + turns: 2, + }, + cache_n: 1, + predicted_n: 5, + }, + }); + }); + + it("reports the last request's timings alone when no tool ran", async () => { + const { client } = scriptedClient([[{ timings: { predicted_n: 3 }, type: "timings" }]]); + const events = await collect(client); + + expect(types(events)).toEqual(["turn_start", "timings", "message", "turn_end", "done"]); + expect(last(events)).toEqual({ reason: "complete", timings: { predicted_n: 3 }, type: "done" }); + }); +}); diff --git a/ui/lib/harness/tests/openai-client.test.ts b/ui/lib/harness/tests/openai-client.test.ts new file mode 100644 index 000000000000..fedcb59a0a8c --- /dev/null +++ b/ui/lib/harness/tests/openai-client.test.ts @@ -0,0 +1,130 @@ +import { describe, expect, it } from "vitest"; +import { createOpenAIClient, type InferenceEvent } from "../src/index.js"; + +function sse(...chunks: unknown[]): string { + return chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`).join("") + "data: [DONE]\n\n"; +} + +// answers every request with the given body, cut into pieces to cross read boundaries +function fakeFetch(body: string, init: ResponseInit = {}, pieceLength = 7) { + const calls: Array<{ url: string; init: RequestInit }> = []; + const fetch = (async (url: string, requestInit: RequestInit) => { + calls.push({ init: requestInit, url }); + + const bytes = new TextEncoder().encode(body); + const stream = new ReadableStream({ + start(controller) { + for (let i = 0; i < bytes.length; i += pieceLength) { + controller.enqueue(bytes.slice(i, i + pieceLength)); + } + + controller.close(); + }, + }); + + return new Response(stream, init); + }) as typeof globalThis.fetch; + + return { calls, fetch }; +} + +async function collect(stream: AsyncIterable): Promise { + const events: InferenceEvent[] = []; + + for await (const event of stream) events.push(event); + + return events; +} + +const delta = (fields: object, rest: object = {}) => ({ + choices: [{ delta: fields }], + id: "cmpl-1", + model: "m", + ...rest, +}); + +describe("createOpenAIClient", () => { + it("posts a streaming request to the chat completions endpoint", async () => { + const { calls, fetch } = fakeFetch(sse()); + const client = createOpenAIClient({ + apiKey: "key", + baseUrl: "http://localhost:8080/", + fetch, + model: "m", + params: { temperature: 0 }, + }); + + await collect(client.stream({ messages: [{ content: "hi", role: "user" }] })); + + expect(calls[0].url).toBe("http://localhost:8080/v1/chat/completions"); + expect(calls[0].init.headers).toMatchObject({ Authorization: "Bearer key" }); + expect(JSON.parse(calls[0].init.body as string)).toEqual({ + messages: [{ content: "hi", role: "user" }], + model: "m", + stream: true, + temperature: 0, + }); + }); + + it("turns the chunks into events", async () => { + const timings = { predicted_n: 2 }; + const { fetch } = fakeFetch( + sse( + delta({ reasoning_content: "hm" }), + delta({ content: "Hel" }), + delta({ content: "lo" }), + delta({}, { timings }), + ), + ); + const events = await collect( + createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }), + ); + + expect(events).toEqual([ + { id: "cmpl-1", type: "completion_id" }, + { model: "m", type: "model" }, + { delta: "hm", type: "reasoning" }, + { delta: "Hel", type: "text" }, + { delta: "lo", type: "text" }, + { progress: undefined, timings, type: "timings" }, + ]); + }); + + it("merges tool call deltas by index", async () => { + const { fetch } = fakeFetch( + sse( + delta({ + tool_calls: [ + { function: { arguments: "", name: "read" }, id: "a", index: 0, type: "function" }, + ], + }), + delta({ tool_calls: [{ function: { arguments: '{"path"' }, index: 0 }] }), + delta({ + tool_calls: [ + { function: { arguments: ':"x"}' }, index: 0 }, + { function: { arguments: "{}", name: "list" }, id: "b", index: 1, type: "function" }, + ], + }), + ), + ); + const events = await collect( + createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }), + ); + const toolCalls = events.filter((event) => event.type === "tool_calls"); + + expect(toolCalls).toHaveLength(3); + expect(toolCalls[2].toolCalls).toEqual([ + { function: { arguments: '{"path":"x"}', name: "read" }, id: "a", type: "function" }, + { function: { arguments: "{}", name: "list" }, id: "b", type: "function" }, + ]); + }); + + it("throws the server's error message", async () => { + const { fetch } = fakeFetch(JSON.stringify({ error: { message: "no model" } }), { + status: 400, + }); + const stream = createOpenAIClient({ baseUrl: "http://x", fetch }).stream({ messages: [] }); + + await expect(collect(stream)).rejects.toThrow("HTTP 400: no model"); + }); +}); diff --git a/ui/lib/harness/tests/trace.test.ts b/ui/lib/harness/tests/trace.test.ts new file mode 100644 index 000000000000..093c0366e0a6 --- /dev/null +++ b/ui/lib/harness/tests/trace.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it } from "vitest"; +import { + createTracePhraser, + extractToolArgString, + formatToolCallLine, + groupToolCallRuns, + humanizeArgKey, + parsePartialJsonArgs, + simpleToolArgFields, + ToolCallSummaryKind, + type TraceStep, + TraceStepType, +} from "../src/index.js"; + +function call(toolName: string, args: object | string, type: string = TraceStepType.TOOL_CALL): TraceStep { + return { toolArgs: typeof args === "string" ? args : JSON.stringify(args), toolName, type }; +} + +const phraser = createTracePhraser(); +const line = (name: string, args: object | string, running = false) => + formatToolCallLine(phraser.describeToolCall(name, typeof args === "string" ? args : JSON.stringify(args), running)); + +describe("parsePartialJsonArgs", () => { + it("reads the keys of arguments cut off mid-stream", () => { + expect(parsePartialJsonArgs('{"path": "src/a.ts", "content": "line')).toEqual({ + content: "line", + path: "src/a.ts", + }); + expect(parsePartialJsonArgs('{"items": [1, 2,')).toEqual({ items: [1, 2] }); + expect(parsePartialJsonArgs("[1, 2]")).toBeNull(); + }); + + it("reads one field of a whole-file argument without parsing it", () => { + expect(extractToolArgString('{"content": "x\\"y", "path": "a\\\\b.ts"}', ["file_path", "path"])).toBe("a\\b.ts"); + }); +}); + +describe("llama-server tools", () => { + it("say what each call acted on, in the past or present tense", () => { + expect(line("read_file", { path: "/repo/src/app.ts" })).toBe("Read app.ts"); + expect(line("read_file", { path: "/repo/src/app.ts" }, true)).toBe("Reading app.ts"); + expect(line("exec_shell_command", { command: "npm test" })).toBe("Ran npm test"); + expect(line("grep_search", { pattern: "TODO" })).toBe("Searched for 'TODO'"); + expect(line("file_glob_search", { include: "**" })).toBe("Listed files"); + }); + + it("keep the command in the line while a later argument still streams", () => { + expect(line("exec_shell_command", '{"command": "ls -la", "timeout": 1')).toBe("Ran ls -la"); + }); +}); + +describe("createTracePhraser", () => { + it("shows the model's own description of a call as it wrote it", () => { + expect(line("exec_shell_command", { command: "npm test", description: "Run the tests." })).toBe("Run the tests"); + }); + + it("reads any other tool as Used, with its main argument", () => { + expect(line("create_issue", { title: "Bug", query: "crash" })).toBe("Used create_issue crash"); + }); + + it("asks the app's resolvers first, then its phrasing table", () => { + const app = createTracePhraser({ + phrasings: { + get_datetime: { object: "the time", past: "Checked", present: "Checking", summary: ToolCallSummaryKind.OTHER }, + }, + resolvers: [ + (c) => + c.name === "read_file" + ? { phrasing: { object: "notes", past: "Opened", present: "Opening", summary: ToolCallSummaryKind.READ } } + : undefined, + ], + }); + + expect(formatToolCallLine(app.describeToolCall("read_file", '{"path":"a"}'))).toBe("Opened notes"); + expect(formatToolCallLine(app.describeToolCall("get_datetime", "{}"))).toBe("Checked the time"); + }); + + it("summarizes a run by kind, other tools last", () => { + const steps = [ + call("create_issue", {}), + call("exec_shell_command", { command: "a" }), + call("read_file", { path: "x" }), + call("exec_shell_command", { command: "b" }), + { type: TraceStepType.TEXT }, + ]; + + expect(phraser.summarizeToolCalls(steps)).toBe("Ran 2 commands, read 1 file, used 1 tool"); + }); + + it("describes what is running now, or the model thinking", () => { + const steps = [call("read_file", { path: "a.ts" }), call("grep_search", { pattern: "x" }, TraceStepType.TOOL_CALL_PENDING)]; + + expect(phraser.describeToolActivity(steps, true)).toBe("Searching for 'x'"); + expect(phraser.describeToolActivity(steps, false)).toBeNull(); + expect(phraser.describeToolActivity([{ type: TraceStepType.REASONING_PENDING }], true)).toBe("Thinking"); + }); +}); + +describe("groupToolCallRuns", () => { + it("groups calls with the reasoning around them, up to the next text", () => { + const steps: TraceStep[] = [ + { type: TraceStepType.REASONING }, + call("read_file", {}), + { type: TraceStepType.REASONING }, + call("grep_search", {}), + { type: TraceStepType.TEXT }, + call("read_file", {}), + ]; + + expect(groupToolCallRuns(steps, [0, 1, 2, 3, 4, 5], 2)).toEqual([[0, 1, 2, 3], 4, 5]); + }); +}); + +describe("tool arguments", () => { + it("read as fields only when every value is short and on one line", () => { + expect(simpleToolArgFields('{"max_results": 5, "query": "llama"}')).toEqual([ + { label: "Max results", value: "5" }, + { label: "Query", value: "llama" }, + ]); + expect(simpleToolArgFields('{"body": "a\\nb"}')).toBeNull(); + expect(humanizeArgKey("filePath")).toBe("File path"); + }); +}); diff --git a/ui/lib/harness/tsconfig.build.json b/ui/lib/harness/tsconfig.build.json new file mode 100644 index 000000000000..cb6a3121d48a --- /dev/null +++ b/ui/lib/harness/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "declaration": true, + "sourceMap": true + }, + "include": ["src"] +} diff --git a/ui/lib/harness/tsconfig.json b/ui/lib/harness/tsconfig.json new file mode 100644 index 000000000000..caa8927c4fc5 --- /dev/null +++ b/ui/lib/harness/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src", "tests"] +} From 6970118ef1f19aab1eeeef07bd121f8d9744dc21 Mon Sep 17 00:00:00 2001 From: uvos Date: Tue, 24 Nov 2026 12:35:00 +0100 Subject: [PATCH 094/401] HIP: CDNA1 MMQ config without stream-k (#32837) --- ggml/src/ggml-cuda/mmq-config-cdna.cuh | 344 ++++++++++++------------- ggml/src/ggml-cuda/mmq.cuh | 8 +- 2 files changed, 177 insertions(+), 175 deletions(-) diff --git a/ggml/src/ggml-cuda/mmq-config-cdna.cuh b/ggml/src/ggml-cuda/mmq-config-cdna.cuh index 4a8d89f72019..8666d79b8b54 100644 --- a/ggml/src/ggml-cuda/mmq-config-cdna.cuh +++ b/ggml/src/ggml-cuda/mmq-config-cdna.cuh @@ -1,185 +1,185 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_config_cdna(ggml_type type, int J, bool fallback) { - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q1_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_1, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q8_0, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q8_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); // --------------------------------------------------------------------------------------------- - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q2_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q3_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q4_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q5_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_Q6_K, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q2_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q2_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q3_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q4_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q5_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_Q6_K, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q6_K, MMQ_ITER_K, true, false); // --------------------------------------------------------------------------------------------- - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ1_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ2_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_XXS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ3_S, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_XS, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_IQ4_NL, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ1_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ2_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, true, false); // --------------------------------------------------------------------------------------------- - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_MXFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); - - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); - CASE(GGML_TYPE_NVFP4, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_MXFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, true, false); + + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, true); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); + CASE(GGML_TYPE_NVFP4, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_NVFP4, MMQ_ITER_K, true, false); return ggml_cuda_mmq_config(GGML_TYPE_COUNT, 512, 1, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, 256, false, true); } diff --git a/ggml/src/ggml-cuda/mmq.cuh b/ggml/src/ggml-cuda/mmq.cuh index be2f11430079..5030ae1da617 100644 --- a/ggml/src/ggml-cuda/mmq.cuh +++ b/ggml/src/ggml-cuda/mmq.cuh @@ -1536,13 +1536,15 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a const int ntiles_dst = args.ntj * nti * ntzw; const int tiles_nwaves = (ntiles_dst + nsm - 1) / nsm; const int tiles_efficiency_percent = 100 * ntiles_dst / (nsm*tiles_nwaves); - const int stream_k_blocks = GGML_CUDA_CC_IS_GCN(cc) ? nsm * config.occupancy : nsm; + // GCN and CDNA configs run several blocks per CU, so stream-k uses one block per occupancy slot. + const bool multi_block_cu = GGML_CUDA_CC_IS_GCN(cc) || GGML_CUDA_CC_IS_CDNA(cc); + const int stream_k_blocks = multi_block_cu ? nsm * config.occupancy : nsm; const int k_chunks = (args.ncols_x + config.K_vram - 1) / config.K_vram; // Use tiling when Stream-K is unlikely to improve performance: // With at least 2 full waves of tiles, tiling already saturates the device and Stream-K only adds overhead. // With few K chunks per tile, the extra parallelism of Stream-K is not needed. - const bool force_tiling = GGML_CUDA_CC_IS_GCN(cc) && + const bool force_tiling = multi_block_cu && (tiles_efficiency_percent >= 90 || ntiles_dst >= 2*stream_k_blocks || k_chunks <= config.occupancy * tiles_nwaves); @@ -1563,7 +1565,7 @@ static void launch_mul_mat_q(ggml_backend_cuda_context & ctx, const mmq_args & a const int nwork = ntiles_dst * k_chunks; // Maximum number of CUDA blocks that can do useful work. int nblocks_stream_k = GGML_CUDA_CC_IS_NVIDIA(cc) && tiles_efficiency_percent >= 90 ? ntiles_dst : std::min(stream_k_blocks, nwork); - if (GGML_CUDA_CC_IS_GCN(cc) && ntiles_dst < nsm) { + if (multi_block_cu && ntiles_dst < nsm) { // Use a 512-thread budget per CU when the tiles do not fill the device. nblocks_stream_k = std::min(nwork, nsm * std::max(1, 512 / config.nthreads)); } From a8ed7789149479dbf2abf0367c8fe8d10d73be82 Mon Sep 17 00:00:00 2001 From: thelittlefireman <5165783+thelittlefireman@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:36:32 +0100 Subject: [PATCH 095/401] hip: use MMQ over MMVQ for Q4_K,N8 and NVFP4,N7-8 on VEGA20 (#32805) --- ggml/src/ggml-cuda/mmvq.cu | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index 6f10428e682b..3549fbe3215a 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -441,6 +441,17 @@ bool ggml_cuda_should_use_mmvq(enum ggml_type type, int cc, int64_t ne11) { return ne11 <= MMVQ_MAX_BATCH_SIZE; } } + // VEGA20 devices are the only devices with dense MMQ -> ggml_cuda_should_use_mmq() + if (cc == GGML_CUDA_CC_VEGA20) { + switch (type) { // tuned on MI50 (gfx906) + case GGML_TYPE_Q4_K: + return ne11 <= 7; + case GGML_TYPE_NVFP4: + return ne11 <= 6; + default: + return ne11 <= MMVQ_MAX_BATCH_SIZE; + } + } return ne11 <= MMVQ_MAX_BATCH_SIZE; } From 94165b288d74e9fca6101018b4471881808c6f18 Mon Sep 17 00:00:00 2001 From: Takamichi Ohara Date: Tue, 24 Nov 2026 20:37:10 +0900 Subject: [PATCH 096/401] webgpu : add POOL_1D support (#32254) --- docs/ops.md | 2 +- docs/ops/WebGPU.csv | 288 +++++++++++++++--- .../ggml-webgpu/ggml-webgpu-shader-lib.hpp | 21 ++ ggml/src/ggml-webgpu/ggml-webgpu.cpp | 35 +++ ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl | 44 +++ 5 files changed, 341 insertions(+), 49 deletions(-) create mode 100644 ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl diff --git a/docs/ops.md b/docs/ops.md index 6c226e150020..e217fce87d56 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -89,7 +89,7 @@ Legend: | OUT_PROD | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | | PAD | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ | | PAD_REFLECT_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ | -| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | +| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | | POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | | REGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | RELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | diff --git a/docs/ops/WebGPU.csv b/docs/ops/WebGPU.csv index 8e09ddaf3de0..1b2080f3cf07 100644 --- a/docs/ops/WebGPU.csv +++ b/docs/ops/WebGPU.csv @@ -1283,54 +1283,246 @@ "WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=0,p1=1","support","1","yes","WebGPU" "WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=0","support","1","yes","WebGPU" "WebGPU: WebGPU","POOL_2D","pool_type=max,type_input=f32,ne_input=[10,10,3,1],k0=3,k1=3,s0=2,s1=2,p0=1,p1=1","support","1","yes","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","0","no","WebGPU" -"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","0","no","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=avg,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=1,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=2,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=1,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=2,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=1","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=2","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[11,1,3,2],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,2,1,3],k0=3,s0=3,p0=3","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,3,2,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[10,1024,1,1],k0=10,s0=10,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,3,2,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[128,1024,1,1],k0=128,s0=128,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,3,2,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[256,1024,1,1],k0=256,s0=256,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,3,2,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[1000,1024,1,1],k0=1000,s0=1000,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,3,2,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[2048,1024,1,1],k0=2048,s0=2048,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,3,2,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" +"WebGPU: WebGPU","POOL_1D","pool_type=max,type_input=f32,ne_input=[4099,1024,1,1],k0=4099,s0=4099,p0=0","support","1","yes","WebGPU" "WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f32,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU" "WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f32,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU" "WebGPU: WebGPU","IM2COL","type_input=f32,type_kernel=f16,dst_type=f16,ne_input=[3000,128,1,1],ne_kernel=[3,128,1280,1],s0=1,s1=0,p0=1,p1=0,d0=1,d1=0,is_2D=0","support","1","yes","WebGPU" diff --git a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp index 6b618bb16370..b256ce6b863c 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu-shader-lib.hpp @@ -1276,6 +1276,7 @@ class ggml_webgpu_shader_lib { std::unordered_map arange_pipelines; // key is fixed, no variants yet std::unordered_map count_equal_pipelines; // key is src_overlap std::unordered_map timestep_embedding_pipelines; // key is fixed, no variants yet + std::unordered_map pool1d_pipelines; std::unordered_map pool2d_pipelines; // key is ggml_op_pool std::unordered_map row_norm_pipelines; // op/inplace @@ -2078,6 +2079,26 @@ class ggml_webgpu_shader_lib { return arange_pipelines[1]; } + webgpu_pipeline get_pool1d_pipeline(const ggml_webgpu_shader_lib_context & context) { + const int key = ggml_get_op_params_i32(context.dst, 0); + + auto it = pool1d_pipelines.find(key); + if (it != pool1d_pipelines.end()) { + return it->second; + } + + std::vector defines = { "WG_SIZE=" + std::to_string(context.max_wg_size) }; + const char * variant = "pool1d_avg"; + if (key == GGML_OP_POOL_MAX) { + defines.emplace_back("POOL_MAX"); + variant = "pool1d_max"; + } + + auto pipeline = ggml_webgpu_create_pipeline(device, preprocessor.preprocess(wgsl_pool1d, defines), variant); + pool1d_pipelines.emplace(key, pipeline); + return pipeline; + } + webgpu_pipeline get_pool2d_pipeline(const ggml_webgpu_shader_lib_context & context) { const int key = ggml_get_op_params_i32(context.dst, 0); diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index daf83ee83ce4..74e6581b65a6 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -989,6 +989,38 @@ static webgpu_encoded_op ggml_webgpu_pad(webgpu_context & ctx, ggml_tensor * src return ggml_backend_webgpu_build(ctx, pipeline, params, entries, wg_x, wg_y); } +static webgpu_encoded_op ggml_webgpu_pool1d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { + ggml_webgpu_shader_lib_context shader_lib_ctx = {}; + shader_lib_ctx.dst = dst; + shader_lib_ctx.max_wg_size = ctx->global_ctx->capabilities.limits.maxComputeInvocationsPerWorkgroup; + + webgpu_pipeline pipeline = ctx->shader_lib->get_pool1d_pipeline(shader_lib_ctx); + + const uint32_t ne = (uint32_t) ggml_nelements(dst); + + std::vector params = { + ne, + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, src) / sizeof(float)), + (uint32_t) (ggml_webgpu_tensor_misalignment(ctx, dst) / sizeof(float)), + (uint32_t) src->ne[0], + (uint32_t) dst->ne[0], + (uint32_t) ggml_get_op_params_i32(dst, 1), + (uint32_t) ggml_get_op_params_i32(dst, 2), + (uint32_t) ggml_get_op_params_i32(dst, 3), + }; + + std::vector entries = { + ggml_webgpu_make_tensor_bind_group_entry(ctx, 0, src), + ggml_webgpu_make_tensor_bind_group_entry(ctx, 1, dst), + }; + + uint32_t wg_x; + uint32_t wg_y; + const uint32_t total_wg = CEIL_DIV(ne, shader_lib_ctx.max_wg_size); + compute_2d_workgroups(total_wg, ctx->global_ctx->capabilities.limits.maxComputeWorkgroupsPerDimension, wg_x, wg_y); + return ggml_backend_webgpu_build(ctx, pipeline, std::move(params), std::move(entries), wg_x, wg_y); +} + static webgpu_encoded_op ggml_webgpu_pool2d(webgpu_context & ctx, ggml_tensor * src, ggml_tensor * dst) { ggml_webgpu_shader_lib_context shader_lib_ctx = {}; shader_lib_ctx.src0 = src; @@ -3774,6 +3806,8 @@ static std::optional ggml_webgpu_encode(webgpu_context ctx, } case GGML_OP_ARANGE: return ggml_webgpu_arange(ctx, node); + case GGML_OP_POOL_1D: + return ggml_webgpu_pool1d(ctx, src0, node); case GGML_OP_POOL_2D: return ggml_webgpu_pool2d(ctx, src0, node); case GGML_OP_COL2IM_1D: @@ -5335,6 +5369,7 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const case GGML_OP_ARANGE: supports_op = op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); break; + case GGML_OP_POOL_1D: case GGML_OP_POOL_2D: supports_op = op->type == GGML_TYPE_F32 && src0->type == GGML_TYPE_F32 && ggml_is_contiguous(src0); break; diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl new file mode 100644 index 000000000000..3a212ed782fe --- /dev/null +++ b/ggml/src/ggml-webgpu/wgsl-shaders/pool1d.wgsl @@ -0,0 +1,44 @@ +struct Params { + ne: u32, + offset_src: u32, + offset_dst: u32, + src_ne0: u32, + dst_ne0: u32, + k0: i32, + s0: i32, + p0: i32, +}; + +@group(0) @binding(0) var src: array; +@group(0) @binding(1) var dst: array; +@group(0) @binding(2) var params: Params; + +@compute @workgroup_size(WG_SIZE) +fn main(@builtin(num_workgroups) num_wg: vec3, @builtin(global_invocation_id) gid: vec3) { + let idx = gid.x + num_wg.x * u32(WG_SIZE) * gid.y; + if (idx >= params.ne) { + return; + } + + let row = params.offset_src + (idx / params.dst_ne0) * params.src_ne0; + let x0 = i32(idx % params.dst_ne0) * params.s0 - params.p0; + let x_begin = max(x0, 0); + let x_end = min(x0 + params.k0, i32(params.src_ne0)); +#ifdef POOL_MAX + var value = bitcast(0xff7fffffu); +#else + var value = 0.0f; +#endif + for (var x = x_begin; x < x_end; x++) { + let v = src[row + u32(x)]; +#ifdef POOL_MAX + value = max(value, v); +#else + value += v; +#endif + } +#ifndef POOL_MAX + value /= f32(max(x_end - x_begin, 1)); +#endif + dst[params.offset_dst + idx] = value; +} From 6ac648d7a9ef8f1a8141aaa52d0bdb780e2571b7 Mon Sep 17 00:00:00 2001 From: Nikhil Jain Date: Tue, 24 Nov 2026 03:37:56 -0800 Subject: [PATCH 097/401] webgpu : Fix indexing bug in softmax kernel (#32691) * Only run webgpu CI on my fork * Add webgpu only workflow * resolve merge conflicts * add row check for softmax * add test * Add test to test case eval --- ggml/src/ggml-webgpu/ggml-webgpu.cpp | 3 ++- ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl | 4 ++++ tests/test-backend-ops.cpp | 3 +++ 3 files changed, 9 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-webgpu/ggml-webgpu.cpp b/ggml/src/ggml-webgpu/ggml-webgpu.cpp index 74e6581b65a6..8bf62e1ca85d 100644 --- a/ggml/src/ggml-webgpu/ggml-webgpu.cpp +++ b/ggml/src/ggml-webgpu/ggml-webgpu.cpp @@ -3237,7 +3237,8 @@ static webgpu_encoded_op ggml_webgpu_soft_max(webgpu_context & ctx, ggml_webgpu_u32_from_f32(max_bias), ggml_webgpu_u32_from_f32(n_head_log2), ggml_webgpu_u32_from_f32(m0), - ggml_webgpu_u32_from_f32(m1) + ggml_webgpu_u32_from_f32(m1), + (uint32_t) ggml_nrows(dst) }; std::vector entries = { ggml_webgpu_make_bind_group_entry( diff --git a/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl b/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl index 8f92a04c1b15..86d4828aaa2a 100644 --- a/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl +++ b/ggml/src/ggml-webgpu/wgsl-shaders/soft_max.wgsl @@ -40,6 +40,7 @@ struct Params { n_head_log2: f32, m0: f32, m1: f32, + nrows: u32, }; #define SRC_BINDING 0 @@ -128,6 +129,9 @@ fn main(@builtin(workgroup_id) wid: vec3, @builtin(local_invocation_id) lid: vec3) { var i = wid.x + wid.y * num_wg.x; + if (i >= params.nrows) { + return; + } let i3 = i / (params.ne2 * params.ne1); i = i % (params.ne2 * params.ne1); let i2 = i / params.ne1; diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 2d50c607cab3..a7380dcb1d58 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -13170,6 +13170,7 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {4, 1, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {4, 1023, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {643251, 3, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); + test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 65537, 1, 1})); for (float max_bias : {0.0f, 8.0f}) { for (float scale : {1.0f, 0.1f}) { @@ -14515,6 +14516,8 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {256, 256, 20, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {64, 64, 20, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {77, 64, 20, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f)); + test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {16, 65537, 1, 1})); + for (int64_t n : {256, 1024}) { test_cases.emplace_back(new test_count_equal(GGML_TYPE_F32, {4, n, 1, 1})); From 6fb428332ecef16ac82c4e8cf961ac287bb3217b Mon Sep 17 00:00:00 2001 From: Plasmatix Ultra Date: Tue, 24 Nov 2026 03:38:47 -0800 Subject: [PATCH 098/401] CUDA: NVFP4 dequant, pack 8 blocks per CTA (#32875) Launch dequantize_block_nvfp4 with dim3(32, 8) so each CTA covers 8 NVFP4 blocks (256 values), as the K-quants do. Assisted-by: Claude Code Co-authored-by: plasmatixultra --- ggml/src/ggml-cuda/convert.cu | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/convert.cu b/ggml/src/ggml-cuda/convert.cu index a8f5047a2302..601c63232178 100644 --- a/ggml/src/ggml-cuda/convert.cu +++ b/ggml/src/ggml-cuda/convert.cu @@ -385,7 +385,7 @@ static __global__ void dequantize_block_nvfp4( const void * __restrict__ vx, dst_t * __restrict__ yy, const int64_t ne) { - const int64_t i = blockIdx.x; + const int64_t i = (int64_t) blockIdx.x*blockDim.y + threadIdx.y; const int tid = threadIdx.x; const int64_t base = i * QK_NVFP4; @@ -417,7 +417,7 @@ static void dequantize_row_nvfp4_cuda( cudaStream_t stream) { GGML_ASSERT(k % QK_NVFP4 == 0); const int nb = k / QK_NVFP4; - dequantize_block_nvfp4<<>>(vx, y, k); + dequantize_block_nvfp4<<<(nb + 7)/8, dim3(32, 8), 0, stream>>>(vx, y, k); } template static __global__ void convert_unary( From 2a487782f2f218bc6c01e1f366a7e73f002faf08 Mon Sep 17 00:00:00 2001 From: IsNot <209144869@qq.com> Date: Tue, 24 Nov 2026 19:41:21 +0800 Subject: [PATCH 099/401] vocab : speed up BPE tokenization (#32859) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * vocab : avoid string allocations in BPE tokenization * whitespace-- --------- Co-authored-by: Sigbjørn Skjæret --- src/llama-vocab.cpp | 53 +++++++++++++++++++-------------------------- src/llama-vocab.h | 3 ++- 2 files changed, 24 insertions(+), 32 deletions(-) diff --git a/src/llama-vocab.cpp b/src/llama-vocab.cpp index 20357e8ef192..c97fa906c8e7 100644 --- a/src/llama-vocab.cpp +++ b/src/llama-vocab.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -274,7 +275,6 @@ struct llm_bigram_bpe { using queue = llama_priority_queue; llm_symbol::index left; llm_symbol::index right; - std::string text; int rank; size_t size; }; @@ -755,14 +755,10 @@ struct llm_tokenizer_bpe_session { auto & left_symbol = symbols[bigram.left]; auto & right_symbol = symbols[bigram.right]; - if (left_symbol.n == 0 || right_symbol.n == 0) { + if (left_symbol.n == 0 || right_symbol.n == 0 || + left_symbol.n + right_symbol.n != bigram.size) { continue; } - std::string left_token = std::string(left_symbol.text, left_symbol.n); - std::string right_token = std::string(right_symbol.text, right_symbol.n); - if (left_token + right_token != bigram.text) { - continue; // Skip this bigram if it's outdated - } // merge the right sym into the left one left_symbol.n += right_symbol.n; @@ -835,12 +831,9 @@ struct llm_tokenizer_bpe_session { if (left == -1 || right == -1) { return; } - std::string left_token = std::string(symbols[left].text, symbols[left].n); - std::string right_token = std::string(symbols[right].text, symbols[right].n); - - int rank_found = -1; - - rank_found = vocab.find_bpe_rank(left_token, right_token); + int rank_found = vocab.find_bpe_rank( + std::string_view(symbols[left].text, symbols[left].n), + std::string_view(symbols[right].text, symbols[right].n)); if (rank_found < 0) { return; @@ -850,8 +843,7 @@ struct llm_tokenizer_bpe_session { bigram.left = left; bigram.right = right; - bigram.text = left_token + right_token; - bigram.size = left_token.size() + right_token.size(); + bigram.size = symbols[left].n + symbols[right].n; bigram.rank = rank_found; work_queue.push(bigram); @@ -2153,13 +2145,15 @@ struct llama_vocab::impl { std::vector cache_special_tokens; std::vector cache_token_to_piece; // llama_token_to_piece(special = true); + using bpe_rank_key = std::pair; struct pair_hash { - size_t operator()(const std::pair & p) const { - return std::hash{}(p.first) ^ //create some hash for pair - (std::hash{}(p.second) << 1); + size_t operator()(const bpe_rank_key & p) const { + return std::hash{}(p.first) ^ + (std::hash{}(p.second) << 1); } }; - std::unordered_map, int, pair_hash> bpe_ranks; + std::deque bpe_rank_strs; // stable backing storage for bpe_ranks keys + std::unordered_map bpe_ranks; // set of all tokens that cause "end of generation" std::set special_eog_ids; @@ -2173,6 +2167,8 @@ struct llama_vocab::impl { impl(const llama_vocab & vocab) : vocab(vocab) { } + impl(const impl &) = delete; + ~impl() = default; void load(llama_model_loader & ml, const LLM_KV & kv); @@ -2261,17 +2257,12 @@ bool llama_vocab::impl::load_bpe_ranks(const gguf_context * ctx, const LLM_KV & bpe_ranks.reserve(n_merges); for (int i = 0; i < n_merges; i++) { const char * word = gguf_get_arr_str(ctx, merges_keyidx, i); - std::string first; - std::string second; const char * sep = *word ? strchr(word + 1, ' ') : nullptr; - if (sep) { - first.assign(word, sep - word); - second.assign(sep + 1); - } - - bpe_ranks.emplace(std::make_pair(std::move(first), std::move(second)), i); + auto & left = bpe_rank_strs.emplace_back(word, sep ? sep - word : 0); + auto & right = bpe_rank_strs.emplace_back(sep ? sep + 1 : ""); + bpe_ranks.emplace(bpe_rank_key(left, right), i); } return true; } @@ -4613,9 +4604,9 @@ int llama_vocab::max_token_len() const { return pimpl->max_token_len; } -int llama_vocab::find_bpe_rank(const std::string & token_left, const std::string & token_right) const { - GGML_ASSERT(token_left.find(' ') == std::string::npos); - GGML_ASSERT(token_right.find(' ') == std::string::npos); +int llama_vocab::find_bpe_rank(std::string_view token_left, std::string_view token_right) const { + GGML_ASSERT(token_left.find(' ') == std::string_view::npos); + GGML_ASSERT(token_right.find(' ') == std::string_view::npos); auto it = pimpl->bpe_ranks.find(std::make_pair(token_left, token_right)); if (it == pimpl->bpe_ranks.end()) { @@ -4633,7 +4624,7 @@ std::vector llama_vocab::get_bpe_merges() const { std::vector result(max_rank + 1); for (const auto & pair : pimpl->bpe_ranks) { - result[pair.second] = pair.first.first + " " + pair.first.second; + result[pair.second] = std::string(pair.first.first) + " " + std::string(pair.first.second); } return result; diff --git a/src/llama-vocab.h b/src/llama-vocab.h index 9345275f55d6..357ce931e30e 100644 --- a/src/llama-vocab.h +++ b/src/llama-vocab.h @@ -3,6 +3,7 @@ #include "llama.h" #include +#include #include #include @@ -174,7 +175,7 @@ struct llama_vocab { int max_token_len() const; - int find_bpe_rank(const std::string & token_left, const std::string & token_right) const; + int find_bpe_rank(std::string_view token_left, std::string_view token_right) const; std::vector get_bpe_merges() const; std::vector get_precompiled_charsmap() const; From 4c92c5bfb7cab395af9fc0fe0939e34ae5083345 Mon Sep 17 00:00:00 2001 From: Eddie Zhou Date: Tue, 24 Nov 2026 05:04:00 -0700 Subject: [PATCH 100/401] CUDA: reduce all cooperative softmax partials when nsm > 256 (#32897) * CUDA: reduce all cooperative softmax partials when nsm > 256 Fixes #32852 * CUDA: drop the remaining cooperative softmax grid size assert --- ggml/src/ggml-cuda/softmax.cu | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/ggml/src/ggml-cuda/softmax.cu b/ggml/src/ggml-cuda/softmax.cu index b9182af54932..18929fcd9d59 100644 --- a/ggml/src/ggml-cuda/softmax.cu +++ b/ggml/src/ggml-cuda/softmax.cu @@ -176,11 +176,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ } g.sync(); - assert(gridDim.x < blockDim.x); - if (tid < gridDim.x) { - local_max = tmp_maxs[tid]; - } else { - local_max = -INFINITY; + local_max = -INFINITY; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + local_max = fmaxf(local_max, tmp_maxs[i]); } local_max = block_reduce(local_max, shared_vals_max); @@ -202,10 +200,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ } g.sync(); - if (tid < gridDim.x) { - tmp_expf = tmp_sums[tid]; - } else { - tmp_expf = 0.0f; + tmp_expf = 0.0f; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + tmp_expf += tmp_sums[i]; } tmp_expf = block_reduce(tmp_expf, shared_vals_sum); @@ -247,11 +244,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ g.sync(); // Compute compute global max from CTA-level maxs - assert(gridDim.x < blockDim.x); // currently we only support this case - if (tid < gridDim.x) { - local_max = tmp_maxs[tid]; - } else { - local_max = -INFINITY; + local_max = -INFINITY; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + local_max = fmaxf(local_max, tmp_maxs[i]); } local_max = block_reduce(local_max, shared_vals_max); @@ -285,10 +280,9 @@ static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __ g.sync(); // Compute global sum from CTA-level sums - if (tid < gridDim.x) { - tmp_expf = tmp_sums[tid]; - } else { - tmp_expf = 0.0f; + tmp_expf = 0.0f; + for (int i = tid; i < (int) gridDim.x; i += blockDim.x) { + tmp_expf += tmp_sums[i]; } tmp_expf = block_reduce(tmp_expf, shared_vals_sum); From e683365a74d5a09b184b3faf3dee240129439b80 Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 20:47:28 +0800 Subject: [PATCH 101/401] model : inkling2 clip with ggml_l2_norm (#32940) Assisted-by: Claude Opus 5.5 --- src/models/inkling2.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/models/inkling2.cpp b/src/models/inkling2.cpp index 45477a69e35e..4a685fd166b6 100644 --- a/src/models/inkling2.cpp +++ b/src/models/inkling2.cpp @@ -167,12 +167,8 @@ ggml_tensor * llama_model_inkling2::graph::clip(ggml_tensor * cur, ggml_tensor * cur = ggml_mul(ctx0, cur, scale); } - ggml_tensor * norm = ggml_sqrt(ctx0, ggml_sum_rows(ctx0, ggml_sqr(ctx0, cur))); - norm = ggml_scale_bias(ctx0, norm, 1.0f, 1e-6f); - - ggml_tensor * factor = ggml_div(ctx0, ggml_fill(ctx0, norm, threshold), norm); - - return ggml_mul(ctx0, cur, ggml_clamp(ctx0, factor, 0.0f, 1.0f)); + // x*min(1, t/|x|) = t*x/max(|x|, t), and l2_norm(x, eps) = x/max(|x|, eps) + return ggml_scale(ctx0, ggml_l2_norm(ctx0, cur, threshold), threshold); } // attention over the depth: mix the earlier block outputs and cur with learned queries From 9578bd3fe48b793cf193c2e4615ec2f24a2ea92a Mon Sep 17 00:00:00 2001 From: Aman Gupta Date: Tue, 24 Nov 2026 20:48:02 +0800 Subject: [PATCH 102/401] CUDA: ignore strides of size-1 dims in bin_bcast (#32854) After collapsing contiguous dims, the stride of a trailing dim of size 1 becomes the size of the whole tensor. Its index is always 0, but the uint32 stride asserts still fire once the tensor has more than 2^32 elements, e.g. the per-head relative-position mask add of inkling2 at n_kv > ~87k with -ub 2048. Fixes #32804 Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-cuda/binbcast.cu | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ggml/src/ggml-cuda/binbcast.cu b/ggml/src/ggml-cuda/binbcast.cu index f7c3a7322f28..7e1c5c300057 100644 --- a/ggml/src/ggml-cuda/binbcast.cu +++ b/ggml/src/ggml-cuda/binbcast.cu @@ -256,6 +256,18 @@ static void launch_bin_bcast_pack(const ggml_tensor * src0, const ggml_tensor * size_t s02 = nb02 / sizeof(src0_t); size_t s03 = nb03 / sizeof(src0_t); + // the index of a dim of size 1 is always 0, so its stride is never applied, + // but after collapsing contiguous dims it can be the whole tensor size and exceed 32 bits + if (cne0[1] == 1) { s01 = 0; } + if (cne0[2] == 1) { s02 = 0; } + if (cne0[3] == 1) { s03 = 0; } + if (cne1[1] == 1) { s11 = 0; } + if (cne1[2] == 1) { s12 = 0; } + if (cne1[3] == 1) { s13 = 0; } + if (ne1 == 1) { s1 = 0; } + if (ne2 == 1) { s2 = 0; } + if (ne3 == 1) { s3 = 0; } + GGML_ASSERT(ne0 <= std::numeric_limits::max()); GGML_ASSERT(ne1 <= std::numeric_limits::max()); GGML_ASSERT(ne2 <= std::numeric_limits::max()); From 26f5048d5c288cec7ccacc4131ccfafaedbc52a7 Mon Sep 17 00:00:00 2001 From: Sebastian Kuzminsky Date: Tue, 24 Nov 2026 06:07:00 -0700 Subject: [PATCH 103/401] fix building in symlinked directories (#32903) * fix building in symlinked directories My checkout is in a symlinked directory, so that the cmake CWD differs from its realpath: ``` $ echo $PWD /home/[READACTED]/llama.cpp $ realpath $PWD /data/home/[READACTED]/llama.cpp ``` The build here fails with this error: ``` CMake Error: Unable to read from file: ../../../../../../../../data/home/[READACTED]/llama.cpp/build/ui/apps/chat/dist/_app/immutable/assets/0.Cc4cGcci.css because: Can't lstat ../../../../../../../../data/home/[READACTED]/llama.cpp/build/ui/apps/chat/dist/_app/immutable/assets/0.Cc4cGcci.css CMake Error at /home/[REDACTED]/llama.cpp/scripts/ui-assets.cmake:229 (file): file failed to compress: /home/[REDACTED]/llama.cpp/build/ui/apps/chat/ui-gzip/_gzip/_app/immutable/assets/0.Cc4cGcci.css Call Stack (most recent call first): /home/[REDACTED]/llama.cpp/scripts/ui-assets.cmake:629 (emit_files) ``` This is because the cmake `emit_files` function uses relative paths and is inconsistent about its use of realpath. This commit fixes the build in my environment by switching from relative to absolute paths for the archive member files, so that the distinction between realpath and non-realpath doesn't mess things up. * refactor: Apply suggestion --------- Co-authored-by: Aleksander Grygier --- scripts/ui-assets.cmake | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/scripts/ui-assets.cmake b/scripts/ui-assets.cmake index 8079c1c09651..62f58e423af6 100644 --- a/scripts/ui-assets.cmake +++ b/scripts/ui-assets.cmake @@ -225,7 +225,10 @@ function(emit_files dist_dir) set(gzip_dir "${gzip_root}/_gzip") file(REMOVE_RECURSE "${gzip_root}") foreach(f IN LISTS assets) - get_filename_component(asset_path "${dist_dir}/${f}" REALPATH) + get_filename_component(asset_path "${dist_dir}/${f}" ABSOLUTE) + if(IS_SYMLINK "${asset_path}") + get_filename_component(asset_path "${asset_path}" REALPATH) + endif() get_filename_component(dst_dir "${gzip_dir}/${f}" DIRECTORY) file(MAKE_DIRECTORY "${dst_dir}") file(ARCHIVE_CREATE From 40fe9164f43b4e7b4bf2a261813eed768c367468 Mon Sep 17 00:00:00 2001 From: Noah <99681487+NoahOksuz@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:13:59 +0000 Subject: [PATCH 104/401] server : retry prompt cache restore after clearing idle slots (#30997) With a unified KV cache, a RAM-cached prompt can fail to restore because another idle slot still holds the cells it needs. Save and clear the other idle slots and retry the restore once in update_prompt_cache(). Builds on #32828, which keeps the cache entry intact when a restore fails. Fixes #30961. --- tools/server/server-context.cpp | 57 +++++++++++++------ .../tests/unit/test_kv_keep_only_active.py | 38 +++++++++++++ 2 files changed, 77 insertions(+), 18 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 932d08bc71dd..2f927d74fe19 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1824,6 +1824,29 @@ struct server_context_impl { return res; } + // save idle slots (except id_slot_keep) to the prompt cache; with a unified KV cache, also clear them + void cache_idle_slots(int32_t id_slot_keep = -1) { + if (!params_base.cache_idle_slots) { + return; + } + + for (auto & slot : slots) { + if (slot.id != id_slot_keep && !slot.is_processing()) { + SLT_TRC(slot, "%s", "saving idle slot to prompt cache\n"); + + if (slot.prompt_save(*prompt_cache)) { + SLT_DBG(slot, "%s", "__TEST_TAG_CACHE_IDLE_SLOT__\n"); + prompt_cache->update(); + } + + if (params_base.kv_unified) { + // [TAG_IDLE_SLOT_CLEAR] + slot.prompt_clear(); + } + } + } + } + // call only when the task is sure to launch on the slot void update_prompt_cache(server_slot & slot, const server_task & task) { SRV_TRC("%s", "updating prompt cache\n"); @@ -1832,8 +1855,22 @@ struct server_context_impl { slot.prompt_save(*prompt_cache); - if (!slot.prompt_load(*prompt_cache, task.tokens, get_task_lora(task))) { + const auto lora = get_task_lora(task); + + if (!slot.prompt_load(*prompt_cache, task.tokens, lora)) { slot.prompt_clear(); + + // with a unified KV cache, the restore can fail because idle slots still hold the cells it needs + // the cache entry is kept on failure, so free those slots and retry once + if (params_base.kv_unified && params_base.cache_idle_slots) { + cache_idle_slots(slot.id); + + SLT_INF(slot, "%s", "retrying prompt restore after clearing idle slots\n"); + + if (!slot.prompt_load(*prompt_cache, task.tokens, lora)) { + slot.prompt_clear(); + } + } } prompt_cache->update(); @@ -3022,23 +3059,7 @@ struct server_context_impl { break; // drop the task } - if (params_base.cache_idle_slots) { - for (auto & slot : slots) { - if (!slot.is_processing()) { - SLT_TRC(slot, "%s", "saving idle slot to prompt cache\n"); - - if (slot.prompt_save(*prompt_cache)) { - SLT_DBG(slot, "%s", "__TEST_TAG_CACHE_IDLE_SLOT__\n"); - prompt_cache->update(); - } - - if (params_base.kv_unified) { - // [TAG_IDLE_SLOT_CLEAR] - slot.prompt_clear(); - } - } - } - } + cache_idle_slots(); } break; case SERVER_TASK_TYPE_CANCEL: { diff --git a/tools/server/tests/unit/test_kv_keep_only_active.py b/tools/server/tests/unit/test_kv_keep_only_active.py index 44c05fab0cbc..d8838f9e053a 100644 --- a/tools/server/tests/unit/test_kv_keep_only_active.py +++ b/tools/server/tests/unit/test_kv_keep_only_active.py @@ -89,6 +89,44 @@ def test_clear_and_restore(): assert "__TEST_TAG_CACHE_IDLE_SLOT__" not in log.drain() +@pytest.mark.parametrize("n_slots,n_ctx,cache_ram,n_tokens_a,n_tokens_b", [ + (2, 512, 100, 350, 300), + (3, 512, 100, 350, 300), + # Both prompts fit in KV, but their states do not fit together in RAM. + (2, 2048, 1, 1200, 700), +]) +def test_restore_under_cache_pressure(n_slots, n_ctx, cache_ram, n_tokens_a, n_tokens_b): + global server + server.n_slots = n_slots + server.n_ctx = n_ctx + server.cache_ram = cache_ram + server.override_kv = f"llama.context_length=int:{n_ctx}" + server.start() + + res = server.make_request("POST", "/tokenize", data={"content": "Hello world"}) + assert res.status_code == 200 + tokens = res.body["tokens"] + prompt_a = [tokens[0]] * n_tokens_a + prompt_b = [tokens[-1]] * n_tokens_b + + for prompt, n_cached in [ + (prompt_a, 0), + (prompt_a + [tokens[0]] * 10, n_tokens_a), + (prompt_b, 0), + (prompt_a + [tokens[0]] * 20, n_tokens_a + 10), + (prompt_b + [tokens[-1]] * 10, n_tokens_b), + (prompt_a + [tokens[0]] * 30, n_tokens_a + 20), + ]: + res = server.make_request("POST", "/completion", data={ + "prompt": prompt, + "n_predict": 1, + "cache_prompt": True, + }) + assert res.status_code == 200 + assert res.body["timings"]["cache_n"] >= n_cached + assert res.body["timings"]["prompt_n"] <= len(prompt) - n_cached + + def test_disabled_with_flag(): global server server.no_cache_idle_slots = True From 97bbf98fdfeb311e50e313fc807d3af1a1ff32d4 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Tue, 24 Nov 2026 15:00:46 +0100 Subject: [PATCH 105/401] ui: make Llama Chat a plain chat unless llama-server offers agent features (#32949) Llama Chat showed its tools, MCP and agentic settings and ran the agentic loop for every server. Now it does so only for a llama-server that offers its built-in tools or its proxy, which --agent turns on together; the app reads this from /props and /tools. Without them it is a plain chat: a message and its reply, with reasoning when the model gives it. The chat store sends the classic request, the tools store has no tools and the MCP store connects to no server, so the tools menu, the working folder, the MCP entry and page, and the Tools and Agentic settings are gone. Tool calls in earlier conversations still display. The Show MCP setting moves from General to the Agentic settings, with the rest of what agent mode adds. VITE_PUBLIC_AGENTIC=false builds an app that is a plain chat for every server, and leaves Llama Harness's loop out of the bundle: the harness gets a ./trace entry with the phrasing alone, and Vite resolves the package to a small stub that re-exports it. A CI job builds the variant and checks the loop is not in it. Assisted-by: Claude (Opus 5.5 Medium) --- .github/workflows/ui.yml | 32 +++++++ ui/apps/chat/.env.example | 2 + ui/apps/chat/.storybook/preview.ts | 4 + ui/apps/chat/README.md | 4 + ui/apps/chat/package.json | 1 + .../ChatFormActionAddButton.svelte | 7 +- .../ChatFormActionAddDropdown.svelte | 11 ++- .../app/dialogs/DialogSearch.svelte | 5 +- .../SidebarNavigation.svelte | 9 +- .../SidebarNavigationFooter.svelte | 5 +- .../settings/SettingsChat/SettingsChat.svelte | 22 ++--- .../chat/src/lib/constants/app.constants.ts | 9 ++ .../constants/attachment-menu.constants.ts | 5 +- .../src/lib/constants/settings.constants.ts | 25 ++++-- .../chat/src/lib/constants/ui.constants.ts | 7 ++ .../src/lib/stores/agentic-mode.svelte.ts | 35 ++++++++ .../lib/stores/agentic/harness-chat-only.ts | 10 +++ .../chat/src/lib/stores/chat/index.svelte.ts | 6 +- .../chat/src/lib/stores/mcp/index.svelte.ts | 4 + ui/apps/chat/src/lib/stores/tools.svelte.ts | 11 ++- .../chat/src/routes/mcp-servers/+page.svelte | 9 +- ui/apps/chat/src/routes/mcp-servers/+page.ts | 9 +- .../form/ChatScreenForm.a11y.stories.svelte | 6 +- .../chat/form/ChatScreenForm.stories.svelte | 4 +- .../chat/tests/unit/chat-only-build.test.ts | 87 +++++++++++++++++++ ui/apps/chat/tsconfig.json | 3 +- ui/apps/chat/vite.config.ts | 15 +++- ui/apps/chat/vitest-setup-client.ts | 4 + ui/lib/harness/package.json | 4 + 29 files changed, 311 insertions(+), 44 deletions(-) create mode 100644 ui/apps/chat/src/lib/stores/agentic-mode.svelte.ts create mode 100644 ui/apps/chat/src/lib/stores/agentic/harness-chat-only.ts create mode 100644 ui/apps/chat/tests/unit/chat-only-build.test.ts diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index bba032416bfb..3547bf4c61e5 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -212,6 +212,38 @@ jobs: run: npm run prepack working-directory: ui/lib/harness + chat-only-build: + name: Chat-only build + runs-on: ubuntu-24.04 + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }} + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Install dependencies + run: npm ci + working-directory: ui/apps/chat + + - name: Build without the agentic loop + run: npm run build + working-directory: ui/apps/chat + env: + VITE_PUBLIC_AGENTIC: "false" + + - name: Check the harness loop is not in the bundle + run: | + if grep -rlq "Tool execution was interrupted by a new user message" dist; then + echo "The chat-only bundle contains Llama Harness's loop" && exit 1 + fi + working-directory: ui/apps/chat + e2e-tests: name: E2E Tests needs: ui-build diff --git a/ui/apps/chat/.env.example b/ui/apps/chat/.env.example index 9760b0dd43fb..269e65278648 100644 --- a/ui/apps/chat/.env.example +++ b/ui/apps/chat/.env.example @@ -1,4 +1,6 @@ VITE_PUBLIC_APP_NAME='Llama Chat' +# 'false' builds a chat-only app: no tools, no MCP, no agentic loop +# VITE_PUBLIC_AGENTIC='false' VITE_DEBUG='true' VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033' diff --git a/ui/apps/chat/.storybook/preview.ts b/ui/apps/chat/.storybook/preview.ts index 22f04dd88609..47c884fd0f99 100644 --- a/ui/apps/chat/.storybook/preview.ts +++ b/ui/apps/chat/.storybook/preview.ts @@ -1,5 +1,6 @@ import '../src/app.css'; import { MEDIA_QUERIES } from '#lib/constants/pwa.constants.ts'; +import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; // the docs pages' styles, shared with the library's Storybook import '../../../lib/ui/.storybook/docs.css'; import { applyColorScheme } from './color-scheme'; @@ -7,6 +8,9 @@ import ModeWatcherDecorator from './decorators/ModeWatcherDecorator.svelte'; import TooltipProviderDecorator from './decorators/TooltipProviderDecorator.svelte'; import type { Preview } from '@storybook/sveltekit'; +// the stories show the app as with a llama-server started with --agent +agenticMode.serverHasTools = true; + applyColorScheme(); window.matchMedia(MEDIA_QUERIES.PREFERS_DARK).addEventListener('change', applyColorScheme); diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index 891fe6b2a422..6ba2e8957d10 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -154,6 +154,10 @@ llama-server serves the UI with `Cross-Origin-Embedder-Policy: require-corp` and llama-server embeds it: when llama-server is built, `scripts/ui-assets.cmake` takes `ui/apps/chat/dist` if it exists, runs `npm run build` if `LLAMA_BUILD_UI` is on, or downloads the release's prebuilt `dist.tar.gz` from Hugging Face, and compiles every file into the binary. The same `dist` is what `npx @ggml-org/llama-chat` serves. +**Plain chat and agent mode.** Llama Chat is a plain chat, a message and its reply with reasoning when the model gives it, unless llama-server offers the agentic features: its built-in tools or its proxy, which `llama-server --agent` turns on together. The app reads this from `/props` and `/tools`. With them it shows the tools menu, the working folder, MCP and the Tools and Agentic settings, and runs the agentic loop; without them it shows none of these and sends the classic request. Tool calls in earlier conversations still display. + +**Chat-only build.** `VITE_PUBLIC_AGENTIC=false npm run build` builds an app that is a plain chat for every server, and `npm run dev:chat-only` runs the dev server the same way. Llama Harness's loop is left out of its bundle. + ```text ui/apps/chat/ ├── src/ diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json index bc3f0d3315d1..76146f41e5b0 100644 --- a/ui/apps/chat/package.json +++ b/ui/apps/chat/package.json @@ -43,6 +43,7 @@ "build": "npm run build-pwa-assets && vite build", "build-pwa-assets": "pwa-assets-generator --root . --config pwa-assets.config.ts && pwa-assets-generator --root . --config pwa-assets-dark.config.ts && node scripts/make-icons-circular.js", "dev": "bash scripts/dev.sh", + "dev:chat-only": "VITE_PUBLIC_AGENTIC=false bash scripts/dev.sh", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte index e25bcb56f72c..11c8a19544dd 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddButton.svelte @@ -2,7 +2,8 @@ import { Button } from '@ggml-org/llama-ui/ui/button'; import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip'; import { Plus } from '@lucide/svelte'; - import { ATTACHMENT_TOOLTIP_TEXT, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; + import { attachmentTooltipText, ICON_CLASS_DEFAULT } from '#lib/constants/index.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; interface Props { disabled?: boolean; @@ -21,13 +22,13 @@ type="button" variant="ghost" > - {ATTACHMENT_TOOLTIP_TEXT} + {attachmentTooltipText(agenticMode.enabled)} -

{ATTACHMENT_TOOLTIP_TEXT}

+

{attachmentTooltipText(agenticMode.enabled)}

diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte index 78153bfbdfbe..d86d663f3808 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDropdown.svelte @@ -9,13 +9,14 @@ ATTACHMENT_FILE_ITEMS, ATTACHMENT_MENU_TEXT, ATTACHMENT_MODALITY_TEXT, - ATTACHMENT_TOOLTIP_TEXT, + attachmentTooltipText, ICON_CLASS_DEFAULT, MODALITY_ICONS } from '#lib/constants/index.ts'; import { getChatFormActionsContext } from '#lib/contexts/index.ts'; import { AttachmentAction, AttachmentItemEnabledWhen, ModelModality } from '#lib/enums/index.ts'; import { useAttachmentMenu } from '#lib/hooks/use-attachment-menu.svelte.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; import type { Component } from 'svelte'; interface Props { @@ -84,7 +85,7 @@ )} disabled={chatFormActions.disabled} > - {ATTACHMENT_TOOLTIP_TEXT} + {attachmentTooltipText(agenticMode.enabled)} @@ -92,7 +93,7 @@ -

{ATTACHMENT_TOOLTIP_TEXT}

+

{attachmentTooltipText(agenticMode.enabled)}

@@ -160,7 +161,9 @@ {/if} - + {#if agenticMode.enabled} + + {/if}
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte index 9a241af2835b..80d0cb5fdc6f 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte @@ -22,7 +22,7 @@ ICON_CLASS_SM, ICON_CLASS_XS, SIDEBAR_ACTIONS_ITEMS, - SIDEBAR_FOOTER_ITEMS + sidebarFooterItems } from '#lib/constants/index.ts'; import { KeyboardKey, SidebarAction } from '#lib/enums/index.ts'; import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts'; @@ -32,6 +32,7 @@ HuggingFaceService } from '#lib/services/index.ts'; import { RouterService } from '#lib/services/router.service.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; import { conversationsStore, deviceStore, @@ -248,7 +249,7 @@ const actionEntries = $derived.by((): SearchEntry[] => // every sidebar action the sidebar shows but Search itself, which is what opened this // dialog, and the models manager on a phone, which picks its models in the selector - [...SIDEBAR_ACTIONS_ITEMS, ...SIDEBAR_FOOTER_ITEMS] + [...SIDEBAR_ACTIONS_ITEMS, ...sidebarFooterItems(agenticMode.enabled)] .filter( (item) => item.action && diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte index 4ca101874ce6..ebbc539f6418 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigation.svelte @@ -22,18 +22,19 @@ SIDEBAR_COLLAPSE_WIDTH, SIDEBAR_COLLAPSED_WIDTH, SIDEBAR_CONTENT_FADE_MS, - SIDEBAR_FOOTER_ITEMS, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, SIDEBAR_OVERSTRETCH_PX, SIDEBAR_REVEAL_ACTION_DELAY_MS, SIDEBAR_SETTLE_MS, - SIDEBAR_TOGGLE_MS + SIDEBAR_TOGGLE_MS, + sidebarFooterItems } from '#lib/constants/index.ts'; import { SidebarAction, TooltipSide } from '#lib/enums/index.ts'; import { useKeyboardShortcuts } from '#lib/hooks/use-keyboard-shortcuts.svelte.ts'; import { useMarqueeSelection } from '#lib/hooks/use-marquee-selection.svelte.ts'; import { RouterService } from '#lib/services/router.service.ts'; + import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; import { chatStore, conversationsStore, @@ -668,7 +669,9 @@ diff --git a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte index b236dc3db653..714d0f64627d 100644 --- a/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte +++ b/ui/apps/chat/src/lib/components/app/navigation/SidebarNavigation/SidebarNavigationFooter.svelte @@ -1,7 +1,8 @@ diff --git a/ui/apps/chat/src/routes/mcp-servers/+page.ts b/ui/apps/chat/src/routes/mcp-servers/+page.ts index 3c3deac5178a..76161de8783a 100644 --- a/ui/apps/chat/src/routes/mcp-servers/+page.ts +++ b/ui/apps/chat/src/routes/mcp-servers/+page.ts @@ -1,4 +1,11 @@ import type { PageLoad } from './$types'; +import { redirect } from '@sveltejs/kit'; +import { AGENTIC_ENABLED, ROUTES } from '#lib/constants/index.ts'; import { loadAppRoute } from '#lib/stores/init.ts'; -export const load: PageLoad = ({ fetch }) => loadAppRoute(fetch); +export const load: PageLoad = ({ fetch }) => { + // a chat-only build has no MCP + if (!AGENTIC_ENABLED) redirect(307, ROUTES.START); + + return loadAppRoute(fetch); +}; diff --git a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte index b1058822af45..ad443f61ccdf 100644 --- a/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte +++ b/ui/apps/chat/tests/stories/chat/form/ChatScreenForm.a11y.stories.svelte @@ -1,7 +1,7 @@ {#if showChip} - + onclick={onOpen} + type="button" + > + + +
{/if} - - {/if} +
+ {#if showWorkingDirectory} + + + {/if} + + {#if systemMessageChip} + + {/if} +
+ import { Card } from '@ggml-org/llama-ui/ui/card'; + import { MessageSquareText, X } from '@lucide/svelte'; + import { ActionIcon, DialogSystemMessageEdit } from '#lib/components/app/index.ts'; + import { chatStore } from '#lib/stores/index.ts'; + + interface Props { + class?: string; + content: string; + disabled?: boolean; + } + + let { class: className = '', content, disabled = false }: Props = $props(); + + let isOpen = $state(false); + + +
+
+ + + Custom system message +
+ + + + {#if !disabled} +
+ chatStore.removeSystemPrompt()} + stopPropagationOnClick + tooltip="Remove" + /> +
+ {/if} +
+ + chatStore.saveSystemPrompt(next)} +/> diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte new file mode 100644 index 000000000000..d797ce2086c5 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte @@ -0,0 +1,40 @@ + + +{#if hasContent} +
+ +
+ + chatStore.saveSystemPrompt(next)} + /> +{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte index 21bd62201f34..93dea8c1fd24 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte @@ -1,8 +1,9 @@ + + + + + + + Custom system message + + + + The starting message that defines how the model behaves in this conversation. + + + + + />
{/if} -
+ +
{#if showWorkingDirectory} { - if (!isOpen) return; + if (!isOpen || inline) return; setTimeout(() => searchInputRef?.focus(), FOCUS_DELAY_MS); }); @@ -160,32 +167,14 @@ return; } - try { - // Generous limit: ranking is client-side, only the top - // MAX_RESULTS_SHOWN are shown. - // A plain query navigates home as if typed after `~/`; a query - // starting from a root or `~` navigates the absolute tree. - const res = await runGlobSearchWithChildren( - toHomeRelativeQuery(trimmed, homeBase), - homeBase ?? HOME_TILDE, - SEARCH.MAX_DEPTH, - SEARCH.LIMIT, - signal, - { type: GlobSearchType.DIR } - ); - + // Every round of results starts with its first folder highlighted. A stale + // search must not touch the list: the next one is already running. + const show = (res: GlobSearchChildResult) => { if (!isCurrent()) return; - if (res.error) { - queryResults = []; - nav.reset(-1); - searchError = res.error; - - return; - } - searchScope = res.exactDir ?? res.args.path; queryResults = res.entries.map((e) => e.path).slice(0, SEARCH.MAX_RESULTS_SHOWN); + searchError = res.error ?? null; if (queryResults.length > 0) { nav.reset(0); @@ -193,8 +182,10 @@ } else { nav.reset(-1); } + }; - searchError = null; + try { + show(await runFolderSearch(trimmed, homeBase, signal, show)); } catch (err) { if (!isCurrent() || signal.aborted) return; @@ -261,25 +252,60 @@ closePicker(); } - function handleKeydown(event: KeyboardEvent) { - if (event.key === KeyboardKey.ENTER) { + /** True when the key was the picker's: the chat input then leaves it alone. */ + function handlePickerKeydown(event: KeyboardEvent): boolean { + // a key that confirms or moves within an IME composition belongs to the text + if (isIMEComposing(event)) return false; + + // Enter picks a suggestion, never the typed text: before the results arrive it does + // nothing. Only without file search, where nothing is suggested, does it take the path + // as typed + if (event.key === KeyboardKey.ENTER && !event.shiftKey) { event.preventDefault(); if (nav.hoveredIndex >= 0 && queryResults[nav.hoveredIndex]) { commit(queryResults[nav.hoveredIndex]); - } else if (queryResults.length === 0) { + } else if (!fileSearchEnabled) { handleSubmit(); } - } else if (event.key === KeyboardKey.ARROW_DOWN) { - if (queryResults.length > 0) { - event.preventDefault(); - nav.move(1); - } - } else if (event.key === KeyboardKey.ARROW_UP) { - if (queryResults.length > 0) { - event.preventDefault(); - nav.move(-1); - } + + return true; + } + + if ( + (event.key === KeyboardKey.ARROW_DOWN || event.key === KeyboardKey.ARROW_UP) && + queryResults.length > 0 + ) { + event.preventDefault(); + nav.move(event.key === KeyboardKey.ARROW_DOWN ? 1 : -1); + + return true; + } + + if (inline && event.key === KeyboardKey.ESCAPE) { + event.preventDefault(); + closePicker(); + + return true; + } + + return false; + } + + /** The chat input's keys while the path is typed on its `/cwd` line. */ + export function handleKeydown(event: KeyboardEvent): boolean { + if (!isOpen || !inline) return false; + + return handlePickerKeydown(event); + } + + // Inline, the chat input is the picker's field: pressing in the form (to move the caret, + // say) keeps the picker open + function handleInteractOutside(event: PointerEvent) { + const target = event.target; + + if (inline && target instanceof Node && customAnchor?.closest('form')?.contains(target)) { + event.preventDefault(); } } @@ -380,14 +406,27 @@ {#snippet picker(inDrawer: boolean)} -
- + +
+ {#if inline} + {#if fileSearchEnabled && !query.trim()} +
+ Type a folder name or path after /cwd +
+ {/if} + {:else} + + {/if} {#if !fileSearchEnabled}
{searchUnavailableMessage}
@@ -460,7 +499,7 @@ {#if deviceStore.isMobile} - + Working directory @@ -484,16 +523,20 @@ Open working directory picker + event.preventDefault()} + onInteractOutside={handleInteractOutside} onOpenAutoFocus={(event) => event.preventDefault()} - onkeydown={handleKeydown} + onkeydown={handlePickerKeydown} preventScroll={false} side="top" sideOffset={12} + trapFocus={!inline} > {@render picker(false)} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte index bc368ac74a14..659f9f62dc01 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormCurrentWorkingDirectory/ChatFormCurrentWorkingDirectoryResultsList.svelte @@ -2,7 +2,7 @@ import { cn } from '@ggml-org/llama-ui/utils'; import { Folder } from '@lucide/svelte'; import { UI_DATA_ATTRS } from '#lib/constants/index.ts'; - import { highlightMatch } from '#lib/utils/index.ts'; + import { hasPointerMoved, highlightMatch } from '#lib/utils/index.ts'; import { fly } from 'svelte/transition'; // Fly-in transition for the results list. @@ -53,7 +53,9 @@ )} data-highlighted={index === hoveredIndex ? '' : undefined} onclick={() => onCommit?.(path)} - onmouseenter={() => onHover?.(index)} + onmousemove={(event) => { + if (hasPointerMoved(event)) onHover?.(index); + }} > diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte index 03a76e61b5ea..180cb1fbc308 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormPickers/ChatFormPicker/ChatFormPickerListItem.svelte @@ -1,12 +1,14 @@
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte new file mode 100644 index 000000000000..2508bdf8b940 --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTaskRow.svelte @@ -0,0 +1,113 @@ + + +
+
+ + {task.description || task.command} + + + +
+ + + {#snippet titleSnippet()} + + {/snippet} + +
+
+ task {task.id} · started + {formatRelativeTime(task.started_at * MS_PER_SECOND)} +
+ + {#if log.skipped > 0} +
+ {BACKGROUND_TASK_SKIPPED_LABEL(log.skipped)} +
+ {/if} + +
{log.text || BACKGROUND_TASK_NO_OUTPUT_LABEL}
+
+
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte new file mode 100644 index 000000000000..06217388d86c --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormBackgroundTasks/ChatFormBackgroundTasks.svelte @@ -0,0 +1,77 @@ + + + (hidden = document.hidden)} /> + +{#if store.available && count > 0} + (store.dialogOpen = true)}> + + + {BACKGROUND_TASKS_RUNNING_LABEL(count)} + +{/if} + + + + + {BACKGROUND_TASKS_DIALOG_TITLE} + + {#if count > 1} + + {/if} + + + + + + + {BACKGROUND_TASKS_DIALOG_DESCRIPTION} + +
+ {#each store.tasks as task (task.id)} + + {:else} +

{BACKGROUND_TASKS_EMPTY_LABEL}

+ {/each} +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte index d797ce2086c5..fe7ebc656c80 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormSystemMessageChip.svelte @@ -1,4 +1,5 @@ -{#snippet promptLine()} - {#if cwd} - {wdDisplay} - {/if} - - $ - - {#if highlightedCommandHtml} - {@html highlightedCommandHtml} - {:else} - {execShellMeta?.command} - {/if} - - {#if commandStreaming} - - {/if} -{/snippet} -
- {@render promptLine()} +
{#if (ctx.isPending && !commandStreaming) || (isLive && !section.toolResult)} @@ -334,40 +350,24 @@ {/snippet}
- diff --git a/ui/apps/chat/src/lib/components/app/content/index.ts b/ui/apps/chat/src/lib/components/app/content/index.ts index c3d69b6d69cf..7b4e7c6bd9b1 100644 --- a/ui/apps/chat/src/lib/components/app/content/index.ts +++ b/ui/apps/chat/src/lib/components/app/content/index.ts @@ -126,6 +126,15 @@ export { default as CollapsibleContentBlock } from './CollapsibleContentBlock.sv */ export { default as CollapsibleTerminalBlock } from './CollapsibleTerminalBlock.svelte'; +/** + * **ShellPromptLine** - A shell command as a terminal prompt shows it + * + * The working directory (home abbreviated), a dim `$` and the command, optionally + * highlighted and with a typing cursor. Shared by the shell tool call and the + * background tasks list so both read the same. + */ +export { default as ShellPromptLine } from './ShellPromptLine.svelte'; + /** * **MermaidPreview** - Pan and zoom viewer for a diagram's svg * diff --git a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts index 2f6efb94cba3..532fa147e044 100644 --- a/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts +++ b/ui/apps/chat/src/lib/constants/api-endpoints.constants.ts @@ -24,6 +24,14 @@ export const API_TOOLS = { LIST: '/tools' }; +// the background tasks of a conversation: `POST` moves a running command to the background, +// `DELETE` stops one, and both answer with the task they changed +export const API_TOOLS_TASKS = { + EVENTS: '/tools/tasks/events', + OUTPUT: '/tools/tasks/output', + TASKS: '/tools/tasks' +}; + // resumable stream routes, the conv::model identity travels as the conv_id query param // because model names can contain slashes that a path segment cannot carry // resume retry cadence while the owning model is still loading (server answers 503) diff --git a/ui/apps/chat/src/lib/constants/background-tasks.constants.ts b/ui/apps/chat/src/lib/constants/background-tasks.constants.ts new file mode 100644 index 000000000000..61aa63b55df8 --- /dev/null +++ b/ui/apps/chat/src/lib/constants/background-tasks.constants.ts @@ -0,0 +1,37 @@ +// how long the task event stream waits before it reads again after it went away, doubling +// each time up to the maximum +export const BACKGROUND_TASKS_RETRY_MS = 1000; +export const BACKGROUND_TASKS_RETRY_MAX_MS = 15_000; + +// how much of a task's output the chat keeps, the same as the server does: the front is +// dropped past it +export const BACKGROUND_TASK_LOG_MAX_LENGTH = 256 * 1024; + +/** The background tasks dialog's title, and what it says while the conversation runs none */ +export const BACKGROUND_TASKS_DIALOG_TITLE = 'Background tasks'; +export const BACKGROUND_TASKS_EMPTY_LABEL = 'Nothing is running in the background.'; +export const BACKGROUND_TASKS_DIALOG_DESCRIPTION = + 'Commands llama-server keeps running for this conversation, with their output'; + +/** What an open task row shows before the task printed anything */ +export const BACKGROUND_TASK_NO_OUTPUT_LABEL = 'No output yet'; + +/** Stopping a task, from its row or all of them at once */ +export const BACKGROUND_TASK_STOP_LABEL = 'Stop'; +export const BACKGROUND_TASK_STOP_ARIA_LABEL = 'Stop task'; +export const BACKGROUND_TASK_STOP_FAILED = 'Could not stop the task'; +export const BACKGROUND_TASKS_STOP_ALL_LABEL = 'Stop all'; + +/** Above an output only the end of was kept */ +export const BACKGROUND_TASK_SKIPPED_LABEL = (bytes: number): string => + `[${bytes} earlier bytes dropped]`; + +/** The button under a running shell call that lets it go on as a background task */ +export const BACKGROUND_TASK_DETACH_LABEL = 'Move to background'; +export const BACKGROUND_TASK_DETACH_TITLE = + 'Keep it running as a background task and let the agent go on'; +export const BACKGROUND_TASK_DETACH_FAILED = 'Could not move the command to the background'; + +/** The chip's label: how many tasks the conversation runs */ +export const BACKGROUND_TASKS_RUNNING_LABEL = (count: number): string => + `${count} background ${count === 1 ? 'task' : 'tasks'}`; diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts index b01f3f57f652..bc482b5962b9 100644 --- a/ui/apps/chat/src/lib/constants/index.ts +++ b/ui/apps/chat/src/lib/constants/index.ts @@ -4,6 +4,7 @@ export * from './agentic.constants'; export * from './api-endpoints.constants'; export * from './app.constants'; +export * from './background-tasks.constants'; export * from './backend.constants'; export * from './chat-tabs.constants'; export * from './database.constants'; diff --git a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts index dce125262e3e..f0970379ee0c 100644 --- a/ui/apps/chat/src/lib/constants/tool-ui.constants.ts +++ b/ui/apps/chat/src/lib/constants/tool-ui.constants.ts @@ -8,6 +8,7 @@ // ChatMessageToolCallBlockSearchResults for prior art). import Braces from '@lucide/svelte/icons/braces'; +import CircleDashed from '@lucide/svelte/icons/circle-dashed'; import Clock from '@lucide/svelte/icons/clock'; import Eye from '@lucide/svelte/icons/eye'; import FilePen from '@lucide/svelte/icons/file-pen'; @@ -38,6 +39,11 @@ export const TOOL_UI: Readonly> = { label: 'Search chats', source: ToolSource.BROWSER }, + [BuiltInTool.SERVER_BACKGROUND_TASK]: { + icon: CircleDashed, + label: 'Background task', + source: ToolSource.SERVER + }, [BuiltInTool.SERVER_EDIT_FILE]: { icon: FilePen, label: 'Edit file', source: ToolSource.SERVER }, [BuiltInTool.SERVER_EXEC_SHELL_COMMAND]: { icon: Terminal, diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index 088d0d0c738e..3e52bc46bee2 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -121,6 +121,8 @@ export { export { KeyboardKey } from './keyboard.enums'; export { + BackgroundTaskStatus, + BackgroundTasksServerEvent, BuiltInTool, GlobSearchType, SearchChatsMessageSelection, diff --git a/ui/apps/chat/src/lib/enums/tools.enums.ts b/ui/apps/chat/src/lib/enums/tools.enums.ts index 2bda6872284b..7381b3b81ee0 100644 --- a/ui/apps/chat/src/lib/enums/tools.enums.ts +++ b/ui/apps/chat/src/lib/enums/tools.enums.ts @@ -46,6 +46,7 @@ export enum BuiltInTool { BROWSER_READ_MEDIA = 'read_media', BROWSER_RUN_JAVASCRIPT = 'run_javascript', BROWSER_SEARCH_CHATS = 'search_chats', + SERVER_BACKGROUND_TASK = 'background_task', SERVER_EDIT_FILE = 'edit_file', SERVER_EXEC_SHELL_COMMAND = 'exec_shell_command', SERVER_FILE_GLOB_SEARCH = 'file_glob_search', @@ -67,3 +68,18 @@ export enum SearchChatsOrder { ASC = 'asc', DESC = 'desc' } + +/** What a background task is doing, as llama-server names it */ +export enum BackgroundTaskStatus { + EXITED = 'exited', + RUNNING = 'running', + STOPPED = 'stopped' +} + +/** The events llama-server sends on `GET /tools/tasks/events` */ +export enum BackgroundTasksServerEvent { + SNAPSHOT = 'snapshot', + TASK_EXITED = 'task_exited', + TASK_OUTPUT = 'task_output', + TASK_STARTED = 'task_started' +} diff --git a/ui/apps/chat/src/lib/services/background-tasks.service.ts b/ui/apps/chat/src/lib/services/background-tasks.service.ts new file mode 100644 index 000000000000..7fc675513b52 --- /dev/null +++ b/ui/apps/chat/src/lib/services/background-tasks.service.ts @@ -0,0 +1,87 @@ +/** + * BackgroundTasksService - The commands llama-server keeps running for a conversation + * + * `exec_shell_command` runs every command as a task. A task outlives its call once it moves to + * the background - the model asks for that when it starts the command, the user asks for it while + * the command runs - and it then belongs to the conversation the call carried in its + * `X-Conversation-Id` header, which `ToolsService` sends. Every route is scoped to the + * conversation the request names, so every call here names one. The server side, and what each + * route answers, is documented in `tools/server/README-dev.md`. + * + * No state: the tasks of the conversation the chat is on live in `backgroundTasksStore`. + */ + +import { API_TOOLS_TASKS } from '#lib/constants/index.ts'; +import type { + BackgroundTask, + BackgroundTaskOutput, + BackgroundTasksEvent +} from '#lib/types/index.ts'; +import { apiFetch } from '#lib/utils/api-fetch.ts'; +import { getAuthHeaders } from '#lib/utils/api-headers.ts'; +import { serverUrl } from '#lib/utils/server-config.ts'; +import { parseSseJsonStream } from '#lib/utils/sse.ts'; + +/** The query of a route that works on one task of one conversation */ +function taskParams(conversationId: string, id: number): URLSearchParams { + return new URLSearchParams({ conv_id: conversationId, id: String(id) }); +} + +export class BackgroundTasksService { + /** Move a running command to the background: its call returns at once, the command goes on */ + static detach(conversationId: string, execId: number): Promise { + return apiFetch(API_TOOLS_TASKS.TASKS, { + body: JSON.stringify({ conv_id: conversationId, from_exec_id: execId }), + method: 'POST' + }); + } + + /** + * The tasks of a conversation: a `snapshot` of them, then an event every time one starts, + * prints or ends. The stream stays open while the page keeps reading it, so a caller reads + * it again when this generator returns or throws. + */ + static async *events( + conversationId: string, + signal?: AbortSignal + ): AsyncGenerator { + const params = new URLSearchParams({ conv_ids: conversationId }); + const response = await fetch(`${serverUrl(API_TOOLS_TASKS.EVENTS)}?${params}`, { + headers: { Accept: 'text/event-stream', ...getAuthHeaders() }, + signal + }); + + if (!response.ok || !response.body) { + throw new Error(`background tasks answered ${response.status}`); + } + + for await (const { data } of parseSseJsonStream(response, signal)) { + yield data; + } + } + + /** What a task printed since `from`; `skipped` says how much the server had dropped by then */ + static output( + conversationId: string, + id: number, + from: number, + signal?: AbortSignal + ): Promise { + const params = taskParams(conversationId, id); + + params.set('from', String(from)); + + return apiFetch(`${API_TOOLS_TASKS.OUTPUT}?${params}`, { + authOnly: true, + signal + }); + } + + /** Stop a task, with everything it started */ + static stop(conversationId: string, id: number): Promise { + return apiFetch(`${API_TOOLS_TASKS.TASKS}?${taskParams(conversationId, id)}`, { + authOnly: true, + method: 'DELETE' + }); + } +} diff --git a/ui/apps/chat/src/lib/services/tools.service.ts b/ui/apps/chat/src/lib/services/tools.service.ts index 2f0dd8fa82bb..ada76941ffe6 100644 --- a/ui/apps/chat/src/lib/services/tools.service.ts +++ b/ui/apps/chat/src/lib/services/tools.service.ts @@ -20,16 +20,20 @@ export class ToolsService { * @param cwd - Working directory for the tool call, sent as the * x-tool-cwd request header. The server resolves relative paths * against it; the model cannot override it. + * @param conversationId - The conversation the call belongs to, sent as the + * X-Conversation-Id header: a command it starts can then move to the + * background as a task of that conversation. */ static async executeTool( toolName: string, params: Record, signal?: AbortSignal, - cwd?: string + cwd?: string, + conversationId?: string ): Promise { const result = await apiFetch>(API_TOOLS.EXECUTE, { body: JSON.stringify({ params, tool: toolName }), - headers: cwd ? { [HEADERS.X_TOOL_CWD_HEADER]: cwd } : undefined, + headers: toolHeaders(cwd, conversationId), method: 'POST', signal }); @@ -131,12 +135,10 @@ export class ToolsService { toolName: string, params: Record, signal?: AbortSignal, - cwd?: string + cwd?: string, + conversationId?: string ): AsyncGenerator { - const headers = getJsonHeaders(); - - if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd; - + const headers = { ...getJsonHeaders(), ...toolHeaders(cwd, conversationId) }; const response = await fetch(serverUrl(API_TOOLS.EXECUTE), { body: JSON.stringify({ params, stream: true, tool: toolName }), headers, @@ -159,7 +161,11 @@ export class ToolsService { const event = next.value.data; - if (event.chunk !== undefined) { + if (event.exec_id !== undefined) { + yield { chunk: null, done: false, execId: event.exec_id }; + } + + if (event.chunk) { yield { chunk: event.chunk, done: false }; } @@ -182,6 +188,8 @@ export interface ToolStreamEvent { chunk: string | null; done: boolean; error?: string; + /** The server's id of the command an `exec_shell_command` call runs, sent first */ + execId?: number; } /** Wire shape of one SSE event from `POST /tools?stream=true`. */ @@ -189,6 +197,18 @@ interface ToolServerEvent { chunk?: string; done?: boolean; error?: string; + exec_id?: number; +} + +/** The headers that tell the server where a tool call runs and which conversation it is for */ +function toolHeaders(cwd?: string, conversationId?: string): Record { + const headers: Record = {}; + + if (cwd) headers[HEADERS.X_TOOL_CWD_HEADER] = cwd; + + if (conversationId) headers[HEADERS.X_CONVERSATION_ID_HEADER] = conversationId; + + return headers; } async function formatNonOkResponse(response: Response): Promise { diff --git a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts index 78524ba3391e..7d4b4497883a 100644 --- a/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/agentic/index.svelte.ts @@ -46,6 +46,7 @@ import { SearchChatsService } from '#lib/services/search-chats.service.ts'; import { ToolsService } from '#lib/services/tools.service.ts'; // direct imports between stores, not via the barrel, to avoid circular deps import { AgenticGates } from '#lib/stores/agentic/gates.svelte.ts'; +import { backgroundTasksStore } from '#lib/stores/background-tasks.svelte.ts'; import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; import { mcpStore } from '#lib/stores/mcp/index.svelte.ts'; import { modelsStore } from '#lib/stores/models/index.svelte.ts'; @@ -458,21 +459,39 @@ class AgenticStore { let accumulated = ''; let isError = false; - for await (const ev of ToolsService.streamTool(toolName, args, signal, cwd)) { - if (ev.chunk !== null) { - accumulated += ev.chunk; - context.update(accumulated); - } + // the command can move to the background from its row while it runs, as a task of + // this conversation + try { + for await (const ev of ToolsService.streamTool( + toolName, + args, + signal, + cwd, + conversationId + )) { + if (ev.execId !== undefined) { + backgroundTasksStore.attach(conversationId, toolCall.id, ev.execId); + } - if (ev.done) { - if (ev.error) { - accumulated = accumulated ? `${accumulated}\nError: ${ev.error}` : `Error: ${ev.error}`; + if (ev.chunk !== null) { + accumulated += ev.chunk; context.update(accumulated); - isError = true; } - break; + if (ev.done) { + if (ev.error) { + accumulated = accumulated + ? `${accumulated}\nError: ${ev.error}` + : `Error: ${ev.error}`; + context.update(accumulated); + isError = true; + } + + break; + } } + } finally { + backgroundTasksStore.forget(toolCall.id); } return { content: accumulated, isError }; @@ -482,7 +501,7 @@ class AgenticStore { const args = this.parseToolArguments(toolCall.function.arguments); const cwd = conversationsStore.activeConversation?.cwd; - return ToolsService.executeTool(toolName, args, signal, cwd); + return ToolsService.executeTool(toolName, args, signal, cwd, conversationId); } if (toolSource === ToolSource.BROWSER) { diff --git a/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts b/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts new file mode 100644 index 000000000000..8509347b874e --- /dev/null +++ b/ui/apps/chat/src/lib/stores/background-tasks.svelte.ts @@ -0,0 +1,262 @@ +/** + * backgroundTasksStore - The commands the agent left running in this conversation + * + * llama-server runs every `exec_shell_command` as a task, and a task moved to the background + * belongs to the conversation that started it. This store follows the running tasks of the + * conversation the chat is on over the server's event stream, reads what they print, moves a + * command that is still running to the background, and stops one. The chat form lists them; a + * command still attached to its call is detached from its own row in the trace. + * + * The server owns the list and the processes: this only reads the stream, and a conversation + * keeps its tasks when the user goes back to it. + */ + +import { + BACKGROUND_TASK_DETACH_FAILED, + BACKGROUND_TASK_STOP_FAILED, + BACKGROUND_TASKS_RETRY_MAX_MS, + BACKGROUND_TASKS_RETRY_MS +} from '#lib/constants/index.ts'; +import { BackgroundTasksServerEvent, BackgroundTaskStatus, BuiltInTool } from '#lib/enums/index.ts'; +import { BackgroundTasksService } from '#lib/services/background-tasks.service.ts'; +import { agenticMode } from '#lib/stores/agentic-mode.svelte.ts'; +import { toolsStore } from '#lib/stores/tools.svelte.ts'; +import type { BackgroundTask, BackgroundTaskLog, BackgroundTasksEvent } from '#lib/types/index.ts'; +import { appendTaskOutput, emptyTaskLog, sleep } from '#lib/utils/index.ts'; +import { untrack } from 'svelte'; +import { toast } from 'svelte-sonner'; + +class BackgroundTasksStore { + dialogOpen = $state(false); + + // a command still attached to the call that started it: its tool call, and the server's id of it + private attached = $state>({}); + + // the running tasks of the followed conversation, by id + private byId = $state>({}); + + // the conversation whose tasks are kept, empty until the chat is on one + private followed = ''; + + // what has been read of each task's output + private logs = $state>({}); + + // rows open on screen: only their tasks are read when the server says there is new output + private open = new Set(); + + // a read of a task in flight, so two events do not read it twice + private reading = new Set(); + + // tasks that printed again while a read was in flight: read once more when it lands + private stale = new Set(); + + /** The server runs commands, and keeps the ones that outlive their call */ + get available(): boolean { + return agenticMode.enabled && toolsStore.hasServerTool(BuiltInTool.SERVER_BACKGROUND_TASK); + } + + /** The conversation's running tasks, the newest first */ + get tasks(): BackgroundTask[] { + return Object.values(this.byId).sort((a, b) => b.started_at - a.started_at || b.id - a.id); + } + + /** A call whose command is running and can still be moved to the background */ + attach(conversationId: string, toolCallId: string, execId: number): void { + this.attached[toolCallId] = { conversationId, execId }; + } + + /** + * Moves the command of a running call to the background: its call returns at once and the + * command keeps running as a task of the conversation. + */ + async detach(toolCallId: string): Promise { + const call = this.attached[toolCallId]; + + if (!call) return; + + try { + const task = await BackgroundTasksService.detach(call.conversationId, call.execId); + + this.forget(toolCallId); + this.keep(call.conversationId, task); + } catch (error) { + // a command that ended on its own a moment before has left `attached`: nothing to say + if (this.attached[toolCallId]) { + toast.error(BACKGROUND_TASK_DETACH_FAILED, { + description: error instanceof Error ? error.message : undefined + }); + } + } + } + + /** The command a running call is still attached to, by the id of that call */ + execIdOf(toolCallId?: string): number | undefined { + return toolCallId ? this.attached[toolCallId]?.execId : undefined; + } + + /** Its call is over: the command either ended with it or is a task the list shows */ + forget(toolCallId: string): void { + delete this.attached[toolCallId]; + } + + /** What the chat has read of a task's output */ + log(taskId: number): BackgroundTaskLog { + return this.logs[taskId] ?? emptyTaskLog(); + } + + /** Stops a task, with everything it started */ + async stop(taskId: number): Promise { + const conversationId = this.followed; + + if (!this.byId[taskId]) return; + + try { + this.keep(conversationId, await BackgroundTasksService.stop(conversationId, taskId)); + } catch (error) { + // a task that ended on its own a moment before has left the list: nothing to say + if (conversationId === this.followed && this.byId[taskId]) { + toast.error(BACKGROUND_TASK_STOP_FAILED, { + description: error instanceof Error ? error.message : undefined + }); + } + } + } + + async stopAll(): Promise { + await Promise.all(this.tasks.map((task) => this.stop(task.id))); + } + + /** + * Keeps the tasks of a conversation, and reads their event stream while `follow` is set; + * call it from an `$effect` and hand the effect the return value. The list starts empty + * when the chat moves to another conversation; a stream that stops and starts again on the + * same one (the tab was hidden, the server went away) keeps what was read. + */ + watch(conversationId: string, follow: boolean): void | (() => void) { + if (conversationId !== this.followed) this.reset(conversationId); + + if (!conversationId || !follow) return; + + const controller = new AbortController(); + + // the request reads settings for its headers: none of that is this effect's business + untrack(() => void this.follow(conversationId, controller.signal)); + + return () => controller.abort(); + } + + /** + * Reads a task's output while its row is open, and once at once to fill the row in; + * give the return value to an `$effect`. + */ + watchOutput(taskId: number): () => void { + this.open.add(taskId); + void this.read(taskId); + + return () => this.open.delete(taskId); + } + + /** One event of the task stream */ + private apply(conversationId: string, event: BackgroundTasksEvent): void { + switch (event.event) { + case BackgroundTasksServerEvent.SNAPSHOT: + this.byId = {}; + + for (const task of event.tasks) this.keep(conversationId, task); + + // the stream may have missed what the open rows printed while it was away + for (const taskId of this.open) void this.read(taskId); + + break; + case BackgroundTasksServerEvent.TASK_STARTED: + case BackgroundTasksServerEvent.TASK_EXITED: + this.keep(conversationId, event.task); + + break; + case BackgroundTasksServerEvent.TASK_OUTPUT: + if (this.open.has(event.id)) void this.read(event.id); + + break; + } + } + + // Reads the task stream of a conversation, again when it goes away, until it is aborted. + private async follow(conversationId: string, signal: AbortSignal): Promise { + let delay = BACKGROUND_TASKS_RETRY_MS; + + while (!signal.aborted) { + try { + for await (const event of BackgroundTasksService.events(conversationId, signal)) { + if (signal.aborted) return; + + delay = BACKGROUND_TASKS_RETRY_MS; + this.apply(conversationId, event); + } + } catch { + // the server went away: read again below + } + + if (signal.aborted) return; + + await sleep(delay); + delay = Math.min(delay * 2, BACKGROUND_TASKS_RETRY_MAX_MS); + } + } + + // A task as the server last answered it: listed while it runs, gone once it is done. An + // answer that lands after the chat moved to another conversation is not this list's. + private keep(conversationId: string, task: BackgroundTask): void { + if (conversationId !== this.followed) return; + + if (task.status === BackgroundTaskStatus.RUNNING) { + this.byId[task.id] = task; + } else { + delete this.byId[task.id]; + delete this.logs[task.id]; + } + } + + // What a running task printed since the last read + private async read(taskId: number): Promise { + const conversationId = this.followed; + + if (!this.byId[taskId]) return; + + if (this.reading.has(taskId)) { + this.stale.add(taskId); + + return; + } + + this.reading.add(taskId); + + try { + const read = await BackgroundTasksService.output( + conversationId, + taskId, + this.logs[taskId]?.offset ?? 0 + ); + + if (conversationId === this.followed) { + this.logs[taskId] = appendTaskOutput(this.logs[taskId], read); + } + } catch { + // the server went away, or the task left its list: keep what is known of it + } finally { + this.reading.delete(taskId); + } + + if (this.stale.delete(taskId)) await this.read(taskId); + } + + /** The chat moved to another conversation: start its list empty */ + private reset(conversationId: string): void { + this.followed = conversationId; + this.byId = {}; + this.logs = {}; + this.open.clear(); + this.stale.clear(); + } +} + +export const backgroundTasksStore = new BackgroundTasksStore(); diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts index 3ca69b1d928f..438810960527 100644 --- a/ui/apps/chat/src/lib/stores/index.ts +++ b/ui/apps/chat/src/lib/stores/index.ts @@ -34,6 +34,9 @@ export { agenticStore } from './agentic/index.svelte'; // CONVERSATION MEDIA (one slideshow of the thread's images, audio and video) export { mediaGalleryStore } from './media-gallery.svelte'; +// BACKGROUND TASKS (commands llama-server keeps running for a conversation, e.g. dev servers) +export { backgroundTasksStore } from './background-tasks.svelte'; + // CONVERSATIONS export { sidebarDragStore } from './sidebar-drag.svelte'; export { conversationsStore } from './conversations/index.svelte'; diff --git a/ui/apps/chat/src/lib/stores/tools.svelte.ts b/ui/apps/chat/src/lib/stores/tools.svelte.ts index 153e44389017..87ebfc836f56 100644 --- a/ui/apps/chat/src/lib/stores/tools.svelte.ts +++ b/ui/apps/chat/src/lib/stores/tools.svelte.ts @@ -360,6 +360,10 @@ class ToolsStore { }); } + hasServerTool(name: BuiltInTool): boolean { + return this._serverTools.some((def) => def.function.name === name); + } + /** * Load persisted disabled tools and fetch the builtin tool list. * Called by initStores() after migrations have run. @@ -524,10 +528,6 @@ class ToolsStore { } } - private hasServerTool(name: BuiltInTool): boolean { - return this._serverTools.some((def) => def.function.name === name); - } - private inferTypeFromDefault(value: unknown): string | undefined { if (typeof value === 'string') return 'string'; diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts index eb3ef07017d1..3c416a9600d6 100644 --- a/ui/apps/chat/src/lib/types/index.ts +++ b/ui/apps/chat/src/lib/types/index.ts @@ -242,6 +242,10 @@ export type { DesktopIconStripItem, MenuAction } from './navigation'; // Tools types export type { + BackgroundTask, + BackgroundTaskLog, + BackgroundTaskOutput, + BackgroundTasksEvent, EditFileEdit, EditFileMeta, EditFileTitleMeta, diff --git a/ui/apps/chat/src/lib/types/tools.d.ts b/ui/apps/chat/src/lib/types/tools.d.ts index 4f1ab120a1f2..4c5313065b40 100644 --- a/ui/apps/chat/src/lib/types/tools.d.ts +++ b/ui/apps/chat/src/lib/types/tools.d.ts @@ -1,5 +1,9 @@ import type { OpenAIToolDefinition } from './mcp'; -import type { ToolSource } from '#lib/enums/index.ts'; +import type { + BackgroundTasksServerEvent, + BackgroundTaskStatus, + ToolSource +} from '#lib/enums/index.ts'; import type { Component } from 'svelte'; /** @@ -81,3 +85,50 @@ export interface EditFileTitleMeta { editsApplied?: number; errorMessage?: string; } + +/** + * A command llama-server keeps running for one conversation after the tool call + * that started it returned, as its routes answer it (`tools/server/README-dev.md`). + * The server owns the list; Llama Chat only reads it. + */ +export interface BackgroundTask { + /** the server's id of the command: the call that started it and the task it became share it */ + id: number; + command: string; + /** the model's description of the call, may be empty */ + description: string; + /** the working directory the command runs in */ + cwd: string; + /** unix seconds */ + started_at: number; + status: BackgroundTaskStatus; +} + +/** One read of `GET /tools/tasks/output`: the task, and what it printed since the offset asked */ +export interface BackgroundTaskOutput extends BackgroundTask { + output: string; + /** where the read after this one starts */ + next: number; + /** bytes the server dropped between the offset asked and where `output` starts */ + skipped?: number; +} + +/** What the chat has read of a task's output, so a re-read only asks for the new bytes */ +export interface BackgroundTaskLog { + text: string; + /** the offset the next read starts at */ + offset: number; + /** what was dropped from the front, so the text does not start at the beginning */ + skipped: number; +} + +/** One event of `GET /tools/tasks/events` */ +export type BackgroundTasksEvent = + /** the conversation's tasks right now, sent first */ + | { event: BackgroundTasksServerEvent.SNAPSHOT; tasks: BackgroundTask[] } + | { + event: BackgroundTasksServerEvent.TASK_EXITED | BackgroundTasksServerEvent.TASK_STARTED; + task: BackgroundTask; + } + /** a task printed: the offset its output reaches now */ + | { event: BackgroundTasksServerEvent.TASK_OUTPUT; id: number; offset: number }; diff --git a/ui/apps/chat/src/lib/utils/background-tasks.ts b/ui/apps/chat/src/lib/utils/background-tasks.ts new file mode 100644 index 000000000000..cdad2657bec9 --- /dev/null +++ b/ui/apps/chat/src/lib/utils/background-tasks.ts @@ -0,0 +1,26 @@ +import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts'; +import type { BackgroundTaskLog, BackgroundTaskOutput } from '#lib/types/index.ts'; + +/** An output nothing has been read of yet */ +export function emptyTaskLog(): BackgroundTaskLog { + return { offset: 0, skipped: 0, text: '' }; +} + +/** + * A read added to what the chat has of a task's output. Only the end of a long output is + * kept: what is cut from the front counts as skipped, like what the server dropped. + */ +export function appendTaskOutput( + current: BackgroundTaskLog | undefined, + read: BackgroundTaskOutput +): BackgroundTaskLog { + const log = current ?? emptyTaskLog(); + const text = log.text + read.output; + const cut = Math.max(0, text.length - BACKGROUND_TASK_LOG_MAX_LENGTH); + + return { + offset: Math.max(log.offset, read.next), + skipped: log.skipped + (read.skipped ?? 0) + cut, + text: text.slice(cut) + }; +} diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index ed7d04d70b6b..68b48a588b40 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -223,6 +223,8 @@ export { // Data URL utilities export { createBase64DataUrl } from './data-url'; +export { sleep } from './sleep'; +export { appendTaskOutput, emptyTaskLog } from './background-tasks'; // Header utilities export { parseHeadersToArray, serializeHeaders } from './headers'; diff --git a/ui/apps/chat/src/lib/utils/sleep.ts b/ui/apps/chat/src/lib/utils/sleep.ts new file mode 100644 index 000000000000..254db906f50e --- /dev/null +++ b/ui/apps/chat/src/lib/utils/sleep.ts @@ -0,0 +1,4 @@ +/** Resolves after `ms` milliseconds */ +export function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts b/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts index 0503f8e2e679..09c12cca0f39 100644 --- a/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts +++ b/ui/apps/chat/tests/client/exec-shell-command-streaming.svelte.test.ts @@ -61,7 +61,7 @@ function promptText(container: Element): string { } function hasCursor(container: Element): boolean { - return container.querySelector('.exec-cursor') !== null; + return container.querySelector('.shell-cursor') !== null; } describe('exec_shell_command streaming title', () => { diff --git a/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte b/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte new file mode 100644 index 000000000000..d8b8c896c79a --- /dev/null +++ b/ui/apps/chat/tests/stories/chat/form/ChatFormBackgroundTaskRow.stories.svelte @@ -0,0 +1,49 @@ + + + + + + + + + + + + + diff --git a/ui/apps/chat/tests/unit/background-tasks.test.ts b/ui/apps/chat/tests/unit/background-tasks.test.ts new file mode 100644 index 000000000000..a5289c4c0c27 --- /dev/null +++ b/ui/apps/chat/tests/unit/background-tasks.test.ts @@ -0,0 +1,48 @@ +import { BACKGROUND_TASK_LOG_MAX_LENGTH } from '#lib/constants/index.ts'; +import { BackgroundTaskStatus } from '#lib/enums/index.ts'; +import type { BackgroundTaskOutput } from '#lib/types/index.ts'; +import { appendTaskOutput } from '#lib/utils/background-tasks.ts'; +import { describe, expect, it } from 'vitest'; + +const read = (overrides: Partial): BackgroundTaskOutput => ({ + command: 'npx -y http-server /tmp/hello-world -p 8780', + cwd: '/tmp', + description: 'Serve the hello world page', + id: 7, + next: 0, + output: '', + started_at: 1_800_000_000, + status: BackgroundTaskStatus.RUNNING, + ...overrides +}); + +describe('appendTaskOutput', () => { + it('adds what a task printed since the last read', () => { + const log = appendTaskOutput(undefined, read({ next: 6, output: 'hello ' })); + + expect(log).toEqual({ offset: 6, skipped: 0, text: 'hello ' }); + expect(appendTaskOutput(log, read({ next: 11, output: 'world' }))).toEqual({ + offset: 11, + skipped: 0, + text: 'hello world' + }); + }); + + it('counts what the server dropped before the read', () => { + expect(appendTaskOutput(undefined, read({ next: 500, output: 'end', skipped: 497 }))).toEqual({ + offset: 500, + skipped: 497, + text: 'end' + }); + }); + + it('keeps only the end of a long output', () => { + const extra = 10; + const output = 'a'.repeat(extra) + 'b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH); + const log = appendTaskOutput(undefined, read({ next: output.length, output })); + + expect(log.text).toBe('b'.repeat(BACKGROUND_TASK_LOG_MAX_LENGTH)); + expect(log.skipped).toBe(extra); + expect(log.offset).toBe(output.length); + }); +}); diff --git a/ui/lib/ui/src/lib/components/ui/button/button.svelte b/ui/lib/ui/src/lib/components/ui/button/button.svelte index ae5708010dda..0d4f6b6d8bd3 100644 --- a/ui/lib/ui/src/lib/components/ui/button/button.svelte +++ b/ui/lib/ui/src/lib/components/ui/button/button.svelte @@ -17,13 +17,17 @@ 'icon-lg': 'size-(--height-control-lg)', 'icon-sm': 'size-5 rounded-sm', lg: 'h-control-lg rounded-lg px-6 has-[>svg]:px-4', - sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5' + sm: 'h-control-sm gap-1.5 rounded-md px-3 has-[>svg]:px-2.5', + // a compact action inside a row or a block: caption text, no fixed height + xs: 'gap-1.5 rounded-md px-2 py-1 text-caption [&_svg:not([class*=size-])]:size-icon-xs' }, variant: { default: 'matte-key-solid [--key-edge:var(--button-primary-edge)] bg-(--action-primary) text-(--fg-on-action) hover:bg-(--action-primary-hover)', destructive: 'matte-key-solid [--key-edge:var(--button-danger-edge)] [--key-sheen-solid:var(--button-danger-sheen)] bg-(--action-danger) hover:bg-(--action-danger-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-(--fg-on-danger)!', + 'danger-secondary': + 'bg-(--action-danger-secondary) text-(--fg-danger) hover:bg-(--action-danger-secondary-hover) focus-visible:bg-(--action-danger-secondary-hover) focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40', ghost: 'hover:text-(--fg-default) hover:bg-(--action-ghost-hover) hover:shadow-(--button-shadow) backdrop-blur-sm', outline: diff --git a/ui/lib/ui/src/lib/components/ui/chip/chip.svelte b/ui/lib/ui/src/lib/components/ui/chip/chip.svelte new file mode 100644 index 000000000000..95cce745bca2 --- /dev/null +++ b/ui/lib/ui/src/lib/components/ui/chip/chip.svelte @@ -0,0 +1,32 @@ + + + + + diff --git a/ui/lib/ui/src/lib/components/ui/chip/index.ts b/ui/lib/ui/src/lib/components/ui/chip/index.ts new file mode 100644 index 000000000000..408c0c2fc123 --- /dev/null +++ b/ui/lib/ui/src/lib/components/ui/chip/index.ts @@ -0,0 +1,2 @@ +export { default as Chip } from './chip.svelte'; +export { chipVariants } from './chip.svelte'; diff --git a/ui/lib/ui/src/lib/styles/tokens/semantic.css b/ui/lib/ui/src/lib/styles/tokens/semantic.css index 842e7085912f..b467071e630d 100644 --- a/ui/lib/ui/src/lib/styles/tokens/semantic.css +++ b/ui/lib/ui/src/lib/styles/tokens/semantic.css @@ -75,6 +75,9 @@ /* one red for every danger state: the danger action is the status fill itself, the alerts' red */ --action-danger: var(--fill-danger); --action-danger-hover: color-mix(in oklch, var(--action-danger) 90%, transparent); + /* the quiet danger action: red text on a faint wash of the same red, stronger on hover */ + --action-danger-secondary: color-mix(in oklch, var(--fill-danger) 8%, transparent); + --action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 16%, transparent); --action-quiet: color-mix(in oklch, var(--neutral-100) 30%, transparent); --action-quiet-hover: var(--neutral-100); --action-ghost-hover: color-mix(in oklch, var(--neutral-500) 10%, transparent); @@ -174,6 +177,8 @@ /* the same red as every danger state, as matte glass: the status fill, frosted and translucent over the page */ --action-danger: color-mix(in oklch, var(--fill-danger) 58%, transparent); --action-danger-hover: color-mix(in oklch, var(--fill-danger) 68%, transparent); + --action-danger-secondary: color-mix(in oklch, var(--fill-danger) 12%, transparent); + --action-danger-secondary-hover: color-mix(in oklch, var(--fill-danger) 22%, transparent); --action-quiet: color-mix(in oklch, var(--neutral-400) 15%, transparent); --action-quiet-hover: color-mix(in oklch, var(--neutral-400) 25%, transparent); --action-ghost-hover: color-mix(in oklch, var(--neutral-400) 10%, transparent); diff --git a/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte index bbabfd5a03e8..30d8df9a0360 100644 --- a/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte +++ b/ui/lib/ui/tests/stories/components/actions/Button.stories.svelte @@ -20,9 +20,10 @@ 'tertiary', 'outline', 'ghost', - 'destructive' + 'destructive', + 'danger-secondary' ]; - const sizes: NonNullable[] = ['sm', 'default', 'lg']; + const sizes: NonNullable[] = ['xs', 'sm', 'default', 'lg']; @@ -48,6 +49,8 @@ + +
diff --git a/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte b/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte new file mode 100644 index 000000000000..4e58062fb01f --- /dev/null +++ b/ui/lib/ui/tests/stories/components/actions/Chip.stories.svelte @@ -0,0 +1,33 @@ + + + + + + 1 background task + + + + + A custom system message that runs long + + + + + Custom system message + + + From 04586184cedb8802623b81e025355f4fa1b0050f Mon Sep 17 00:00:00 2001 From: Mustafa Camurcu Date: Tue, 1 Dec 2026 06:42:58 -0800 Subject: [PATCH 314/401] vulkan: read IQ1/IQ2/IQ3 grid tables from a storage buffer (#32915) Upload the grid tables once per device and copy them to shared memory from a storage buffer instead of from GLSL constant arrays, avoiding divergent constant loads in init_iq_shmem. Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-vulkan/ggml-vulkan-types.h | 9 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 59 +- .../src/ggml-vulkan/vulkan-shaders/types.glsl | 1032 +---------------- 3 files changed, 102 insertions(+), 998 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index fb2dfecd6d35..47383d50afe3 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -234,6 +234,13 @@ static bool is_pow2(uint32_t x) { return x > 1 && (x & (x-1)) == 0; } #define MAX_PARAMETER_COUNT 12 +// binding of the IQ1/IQ2/IQ3 grid tables (see vk_iq_grids), after the regular parameters. +// It is written once per descriptor set and never changes. +#define IQ_GRID_BINDING MAX_PARAMETER_COUNT + +// bindings in the descriptor set layout shared by all pipelines +#define NUM_DESCRIPTOR_BINDINGS (MAX_PARAMETER_COUNT + 1) + #define MAX_FUSED_ADDS (MAX_PARAMETER_COUNT - 3) #define GGML_VK_GDN_CM_V 64u @@ -1070,6 +1077,8 @@ struct vk_device_struct { vk::Fence fence; vk_buffer sync_staging; + vk_buffer iq_grid_buf; + ggml_backend_buffer_type buffer_type; bool disable_fusion; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index ca6bcb2963da..1cdb392c4c63 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1,5 +1,9 @@ #include "ggml-vulkan-common.h" +#define GGML_COMMON_DECL_CPP +#define GGML_COMMON_IMPL_CPP +#include "ggml-common.h" + static vk_device_architecture get_device_architecture(const vk::PhysicalDevice& device) { vk::PhysicalDeviceProperties props = device.getProperties(); @@ -576,6 +580,45 @@ static bool ggml_vk_roll_bk_loop(const uint32_t * code, size_t word_count, std:: return true; } +// Grid tables of the IQ1/IQ2/IQ3 types, read by the shaders at IQ_GRID_BINDING. +// The offsets must match the IQ*_GRID_OFFSET values in types.glsl (bytes). +struct vk_iq_grids { + uint32_t iq1s[NGRID_IQ1S/2]; // 2 bits per value (v & 3), two grid entries per uint32 + uint32_t iq1s_gpu[NGRID_IQ1S]; // 4 bits per value (v + 1), values 0-3 in the low nibbles + uint64_t iq2xxs[256]; + uint64_t iq2xs[512]; + uint64_t iq2s[1024]; + uint32_t iq3xxs[256]; + uint32_t iq3s[512]; +}; +static_assert(offsetof(vk_iq_grids, iq1s_gpu) == 4096); +static_assert(offsetof(vk_iq_grids, iq2xxs) == 12288); +static_assert(offsetof(vk_iq_grids, iq2xs) == 14336); +static_assert(offsetof(vk_iq_grids, iq2s) == 18432); +static_assert(offsetof(vk_iq_grids, iq3xxs) == 26624); +static_assert(offsetof(vk_iq_grids, iq3s) == 27648); + +static void ggml_vk_init_iq_grids(vk_device & device) { + auto grids = std::make_unique(); // zero-initialized + for (int i = 0; i < NGRID_IQ1S; ++i) { + const int8_t * g = (const int8_t *) &iq1s_grid[i]; + uint32_t gpu = 0; + for (int j = 0; j < 8; ++j) { + grids->iq1s[i / 2] |= (uint32_t)(g[j] & 3) << (16 * (i % 2) + 2 * j); + gpu |= (uint32_t)(g[j] + 1) << (8 * (j % 4) + 4 * (j / 4)); + } + grids->iq1s_gpu[i] = gpu; + } + memcpy(grids->iq2xxs, iq2xxs_grid, sizeof(grids->iq2xxs)); + memcpy(grids->iq2xs, iq2xs_grid, sizeof(grids->iq2xs)); + memcpy(grids->iq2s, iq2s_grid, sizeof(grids->iq2s)); + memcpy(grids->iq3xxs, iq3xxs_grid, sizeof(grids->iq3xxs)); + memcpy(grids->iq3s, iq3s_grid, sizeof(grids->iq3s)); + + device->iq_grid_buf = ggml_vk_create_buffer_device(device, sizeof(vk_iq_grids)); + ggml_vk_buffer_write(device->iq_grid_buf, 0, grids.get(), sizeof(vk_iq_grids)); +} + static void ggml_vk_create_pipeline_func(vk_device& device, vk_pipeline& pipeline, size_t spv_size, const void* spv_data, const std::string entrypoint, uint32_t parameter_count, std::array wg_denoms, std::vector specialization_constants, bool disable_robustness, bool require_full_subgroups, uint32_t required_subgroup_size) { @@ -877,7 +920,7 @@ void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) { pool_remaining = VK_DEVICE_DESCRIPTOR_POOL_SIZE; if (pool_idx >= ctx->descriptor_pools.size()) { - vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, MAX_PARAMETER_COUNT * VK_DEVICE_DESCRIPTOR_POOL_SIZE); + vk::DescriptorPoolSize descriptor_pool_size(vk::DescriptorType::eStorageBuffer, NUM_DESCRIPTOR_BINDINGS * VK_DEVICE_DESCRIPTOR_POOL_SIZE); vk::DescriptorPoolCreateInfo descriptor_pool_create_info({}, VK_DEVICE_DESCRIPTOR_POOL_SIZE, descriptor_pool_size); ctx->descriptor_pools.push_back(device->device.createDescriptorPool(descriptor_pool_create_info)); } @@ -888,6 +931,15 @@ void ggml_pipeline_allocate_descriptor_sets(ggml_backend_vk_context * ctx) { } vk::DescriptorSetAllocateInfo descriptor_set_alloc_info(ctx->descriptor_pools[pool_idx], alloc_count, layouts.data()); std::vector sets = device->device.allocateDescriptorSets(descriptor_set_alloc_info); + + // the IQ grid tables live at the same binding in every set; shaders that don't use them ignore it + const vk::DescriptorBufferInfo iq_grid_info{ device->iq_grid_buf->buffer, 0, VK_WHOLE_SIZE }; + std::vector iq_grid_writes; + for (const vk::DescriptorSet & set : sets) { + iq_grid_writes.push_back({ set, IQ_GRID_BINDING, 0, 1, vk::DescriptorType::eStorageBuffer, nullptr, &iq_grid_info }); + } + device->device.updateDescriptorSets(iq_grid_writes, {}); + ctx->descriptor_sets.insert(ctx->descriptor_sets.end(), sets.begin(), sets.end()); pool_idx++; @@ -5677,7 +5729,7 @@ vk_device ggml_vk_get_device(size_t idx) { std::vector dsl_binding; std::vector dsl_binding_flags; - for (uint32_t i = 0; i < MAX_PARAMETER_COUNT; i++) { + for (uint32_t i = 0; i < NUM_DESCRIPTOR_BINDINGS; i++) { dsl_binding.push_back({i, vk::DescriptorType::eStorageBuffer, 1, vk::ShaderStageFlagBits::eCompute}); dsl_binding_flags.push_back({}); } @@ -5719,6 +5771,8 @@ vk_device ggml_vk_get_device(size_t idx) { device->fence = device->device.createFence({}); + ggml_vk_init_iq_grids(device); + device->buffer_type = { /* .iface = */ ggml_backend_vk_buffer_type_interface, /* .device = */ ggml_backend_reg_dev_get(ggml_backend_vk_reg(), idx), @@ -18417,6 +18471,7 @@ vk_device_struct::~vk_device_struct() { device.destroyFence(fence); ggml_vk_destroy_buffer(sync_staging); + ggml_vk_destroy_buffer(iq_grid_buf); if (compute_queue) compute_queue->cmd_pool.destroy(device); if (transfer_queue) transfer_queue->cmd_pool.destroy(device); diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl b/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl index 39772acbaeb7..a5dd7fdc4730 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl +++ b/ggml/src/ggml-vulkan/vulkan-shaders/types.glsl @@ -567,438 +567,60 @@ struct block_iq1_m_packed64 { #define A_TYPE_PACKED32 block_iq1_m_packed32 #endif +// IQ1/IQ2/IQ3 grid tables are read from a storage buffer and copied to shared memory by init_iq_shmem. +// The binding and offsets must match IQ_GRID_BINDING and vk_iq_grids in ggml-vulkan. +#define IQ_GRID_BINDING 12 +// Offsets are in bytes; divide by the element size when indexing. +#define IQ1S_GRID_OFFSET 0 +#define IQ1S_GRID_GPU_OFFSET 4096 +#define IQ2XXS_GRID_OFFSET 12288 +#define IQ2XS_GRID_OFFSET 14336 +#define IQ2S_GRID_OFFSET 18432 +#define IQ3XXS_GRID_OFFSET 26624 +#define IQ3S_GRID_OFFSET 27648 + #if defined(DATA_A_IQ1_S) || defined(DATA_A_IQ1_M) #define IQ1S_DELTA 0.125f #define IQ1M_DELTA 0.125f -// Packed IQ1S grid where every 2 vec8 are encoded on 32 bits (2 bits per coordinate). -const uint[1024] iq1s_grid_const = { - 0xfffdffff, 0xfff7fff0, 0xffccfff5, 0xffdfffc0, 0xffd7ffdd, 0xff30ffd5, 0xff03ff0c, 0xff10ff01, - 0xff7dff7f, 0xff75ff77, 0xff5fff40, 0xff57ff5d, 0xfcf3ff55, 0xfcccfcf0, 0xfcc1fcc3, 0xfcc5fcc4, - 0xfc3cfcd0, 0xfc34fc31, 0xfc00fc0d, 0xfc1cfc05, 0xfc11fc13, 0xfc70fc17, 0xfc43fc4c, 0xfc50fc41, - 0xfdfdfdff, 0xfdf5fdf7, 0xfddffdc0, 0xfdd7fddd, 0xfd30fdd5, 0xfd04fd0c, 0xfd14fd13, 0xfd7dfd7f, - 0xfd75fd77, 0xfd40fd4c, 0xfd5ffd44, 0xfd57fd5d, 0xf3ccfd55, 0xf3c1f3c3, 0xf33cf3d0, 0xf300f334, - 0xf313f305, 0xf34cf310, 0xf350f344, 0xf0f3f0fc, 0xf0f1f0f0, 0xf0c7f0c0, 0xf0d4f0c5, 0xf030f03f, - 0xf00ff035, 0xf003f00c, 0xf001f000, 0xf01ff004, 0xf010f01d, 0xf015f017, 0xf04cf07c, 0xf047f040, - 0xf05cf045, 0xf050f053, 0xf054f051, 0xf1c4f1c3, 0xf133f13c, 0xf10df10f, 0xf107f100, 0xf11cf11f, - 0xf114f111, 0xf14cf170, 0xf144f143, 0xf7fdf7ff, 0xf7f5f7f7, 0xf7dff7c0, 0xf7d7f7dd, 0xf730f7d5, - 0xf701f70c, 0xf77ff710, 0xf777f77d, 0xf740f775, 0xf75df75f, 0xf755f757, 0xf4ccf4f0, 0xf4c4f4c3, - 0xf4d0f4d3, 0xf40ff43c, 0xf400f40c, 0xf413f41c, 0xf44cf414, 0xf441f443, 0xf450f444, 0xf5fdf5ff, - 0xf5f5f5f7, 0xf5dff5c0, 0xf5d7f5dd, 0xf530f5d5, 0xf504f50c, 0xf510f51c, 0xf57df57f, 0xf577f570, - 0xf540f575, 0xf55df55f, 0xf555f557, 0xcfcccfcf, 0xcfc4cfc3, 0xcfd0cfd3, 0xcf33cf3c, 0xcf00cf0f, - 0xcf1ccf07, 0xcf10cf13, 0xcf4ccf14, 0xcf41cf43, 0xcf50cf5c, 0xccf3ccfc, 0xccf4ccf1, 0xcccdcccf, - 0xccc7ccc0, 0xccd3ccdc, 0xcc30ccd4, 0xcc0fcc35, 0xcc0dcc0c, 0xcc00cc03, 0xcc04cc01, 0xcc10cc1f, - 0xcc4dcc73, 0xcc5ccc40, 0xcdcccc53, 0xcdc1cdc3, 0xcd3fcdd0, 0xcd34cd31, 0xcd00cd0d, 0xcd05cd07, - 0xcd11cd13, 0xcd4ccd70, 0xcd41cd43, 0xc3fccd50, 0xc3f4c3f1, 0xc3c0c3c3, 0xc3c4c3c7, 0xc3d1c3dc, - 0xc330c33c, 0xc337c331, 0xc30cc335, 0xc300c303, 0xc304c301, 0xc310c31d, 0xc373c317, 0xc34fc374, - 0xc340c343, 0xc344c347, 0xc35cc345, 0xc350c353, 0xc0fdc354, 0xc0f5c0f0, 0xc0c3c0cc, 0xc0c1c0c0, - 0xc0dfc0c4, 0xc0d0c0dd, 0xc0d5c0d7, 0xc033c03c, 0xc031c030, 0xc00dc00c, 0xc000c003, 0xc004c001, - 0xc01cc005, 0xc010c013, 0xc014c011, 0xc07dc07f, 0xc070c073, 0xc075c077, 0xc04cc04f, 0xc040c043, - 0xc044c041, 0xc05fc045, 0xc050c05d, 0xc1f3c1fc, 0xc1f1c1f0, 0xc1c1c1c0, 0xc1c5c1c7, 0xc1d1c1dc, - 0xc13dc13f, 0xc130c133, 0xc135c137, 0xc100c10c, 0xc107c101, 0xc11cc104, 0xc110c113, 0xc114c117, - 0xc171c115, 0xc14dc175, 0xc153c140, 0xc7ccc154, 0xc7d0c7c1, 0xc733c73c, 0xc734c731, 0xc700c70f, - 0xc705c707, 0xc71cc71f, 0xc711c713, 0xc770c714, 0xc743c74c, 0xc4cfc750, 0xc4c0c4cd, 0xc4dcc4c5, - 0xc43dc4d0, 0xc430c433, 0xc40cc437, 0xc400c403, 0xc404c401, 0xc41fc405, 0xc415c410, 0xc44cc474, - 0xc440c44d, 0xc45cc447, 0xc454c451, 0xc5c1c5f4, 0xc5d1c5d3, 0xc531c533, 0xc50fc534, 0xc500c50d, - 0xc51cc507, 0xc514c511, 0xc54cc570, 0xc545c541, 0xdffddfff, 0xdff5dff7, 0xdfdfdfc0, 0xdfd0dfdd, - 0xdfd5dfd7, 0xdf0cdf30, 0xdf1cdf04, 0xdf7fdf10, 0xdf77df7d, 0xdf40df75, 0xdf5ddf5f, 0xdf57df50, - 0xdcf0df55, 0xdcc3dccc, 0xdcd0dcc4, 0xdc33dc3d, 0xdc00dc34, 0xdc05dc07, 0xdc13dc1c, 0xdc11dc10, - 0xdc4fdc70, 0xdc44dc41, 0xddfcdc50, 0xddf5ddf7, 0xddc0ddcc, 0xdddddddf, 0xddd5ddd7, 0xdd0cdd30, - 0xdd04dd01, 0xdd7cdd10, 0xdd75dd77, 0xdd40dd4c, 0xdd5ddd5f, 0xdd55dd57, 0xd3c3d3f0, 0xd3c4d3c1, - 0xd333d3d0, 0xd331d330, 0xd30dd334, 0xd307d300, 0xd311d305, 0xd34cd370, 0xd344d343, 0xd350d35c, - 0xd0c0d0f4, 0xd0d4d0dc, 0xd030d03f, 0xd00cd037, 0xd000d003, 0xd01dd004, 0xd017d010, 0xd04fd074, - 0xd040d043, 0xd045d047, 0xd053d05c, 0xd054d051, 0xd1cfd1f0, 0xd1c4d1cd, 0xd13cd1d0, 0xd100d134, - 0xd11cd11f, 0xd173d114, 0xd14fd171, 0xd7ffd145, 0xd7f7d7fd, 0xd7c0d7f5, 0xd7ddd7df, 0xd7d5d7d7, - 0xd70cd730, 0xd710d703, 0xd77dd77f, 0xd775d777, 0xd75dd75f, 0xd755d757, 0xd4ccd4f4, 0xd4c4d4c3, - 0xd431d4d0, 0xd40dd434, 0xd41cd400, 0xd411d413, 0xd470d414, 0xd441d44f, 0xd453d444, 0xd5ffd450, - 0xd5f7d5fd, 0xd5dfd5f5, 0xd5d7d5dd, 0xd530d5d5, 0xd501d50c, 0xd510d504, 0xd57dd57f, 0xd575d577, - 0xd55fd540, 0xd557d55d, 0x3ff0d555, 0x3fc13fcc, 0x3f343fd0, 0x3f003f0d, 0x3f053f07, 0x3f133f1c, - 0x3f433f11, 0x3f5c3f44, 0x3cff3f51, 0x3cf33cfc, 0x3cf43cf1, 0x3cc03ccd, 0x3cc73cc1, 0x3cdc3cc5, - 0x3cd43cd1, 0x3c373c30, 0x3c0c3c35, 0x3c003c03, 0x3c043c01, 0x3c103c05, 0x3c153c17, 0x3c733c7c, - 0x3c4f3c71, 0x3c403c4d, 0x3c5c3c5f, 0x3df03c5d, 0x3dc33dcc, 0x3dd03dc1, 0x3d0d3d3c, 0x3d053d00, - 0x3d143d13, 0x3d433d74, 0x33fc3d50, 0x33c433c0, 0x333033d4, 0x33353337, 0x3303330c, 0x33013300, - 0x331d331c, 0x33173310, 0x337c3315, 0x33743371, 0x334d334f, 0x335f3340, 0x3354335c, 0x30fd30fc, - 0x30f530f0, 0x30c330cc, 0x30c130c0, 0x30df30c4, 0x30d530d0, 0x3033303c, 0x30313030, 0x300f3034, - 0x3003300c, 0x30013000, 0x30043007, 0x3013301c, 0x30113010, 0x307d3014, 0x30703073, 0x304c3077, - 0x30403043, 0x30443041, 0x30503045, 0x30553057, 0x31f031fc, 0x31c331f4, 0x31c731c0, 0x31dc31c5, - 0x31d431d3, 0x313d313f, 0x31373130, 0x310c310f, 0x3100310d, 0x31043101, 0x3110311d, 0x317c3117, - 0x31753170, 0x31403143, 0x3153315c, 0x37f03151, 0x37c037cc, 0x37d037c5, 0x3734373d, 0x3700370f, - 0x371c3707, 0x37113713, 0x37703714, 0x3743374c, 0x37443741, 0x34fc3750, 0x34f134f0, 0x34cf34f5, - 0x34c034c3, 0x34dc34c7, 0x34d134d3, 0x3430343f, 0x340c3435, 0x3403340d, 0x34013400, 0x341f3404, - 0x3410341d, 0x34153411, 0x34743471, 0x3440344d, 0x34473441, 0x3453345c, 0x34543451, 0x353335c1, - 0x35343531, 0x35073500, 0x35133505, 0x35433514, 0x0ffc3550, 0x0ff00ff3, 0x0ff40ff1, 0x0fc00fcd, - 0x0fdc0fc5, 0x0fd40fd3, 0x0f300f3f, 0x0f0c0f37, 0x0f000f03, 0x0f040f01, 0x0f170f10, 0x0f740f71, - 0x0f470f40, 0x0f5c0f5f, 0x0f540f51, 0x0cf70cf0, 0x0cf50cf4, 0x0cc30ccc, 0x0cc10cc0, 0x0cc40cc7, - 0x0cd00cdf, 0x0cd70cd1, 0x0c3c0cd5, 0x0c300c33, 0x0c340c31, 0x0c0c0c0f, 0x0c030c0d, 0x0c010c00, - 0x0c040c07, 0x0c1c0c05, 0x0c100c13, 0x0c140c11, 0x0c700c7d, 0x0c430c4c, 0x0c410c40, 0x0c5f0c44, - 0x0c550c50, 0x0df10dfc, 0x0dc00dcd, 0x0ddc0dc5, 0x0d3d0dd3, 0x0d350d30, 0x0d030d0c, 0x0d010d00, - 0x0d1d0d04, 0x0d700d10, 0x0d4d0d4f, 0x0d440d40, 0x0d530d45, 0x03f003f3, 0x03c303cc, 0x03c103c0, - 0x03c403c7, 0x03d003dc, 0x03d503d7, 0x0333033c, 0x03310330, 0x03350334, 0x030c030f, 0x03000303, - 0x03070301, 0x03050304, 0x031d031c, 0x03100313, 0x03140311, 0x0377037f, 0x034c0375, 0x03400343, - 0x03440341, 0x0353035c, 0x03550350, 0x00fd00fc, 0x00f000f3, 0x00f400f1, 0x00cc00cf, 0x00c300cd, - 0x00c100c0, 0x00c500c4, 0x00d300dc, 0x00d100d0, 0x003f00d4, 0x003d003c, 0x00300033, 0x00370031, - 0x000f0034, 0x000d000c, 0x00000003, 0x00070001, 0x00050004, 0x001c001f, 0x00100013, 0x00170011, - 0x00150014, 0x0073007c, 0x00740070, 0x004f0075, 0x0043004c, 0x00410040, 0x00440047, 0x0053005c, - 0x00510050, 0x01ff0054, 0x01fd01fc, 0x01f101f3, 0x01f401f7, 0x01c301cc, 0x01c701c0, 0x01df01c4, - 0x01dd01dc, 0x01d001d3, 0x01d701d1, 0x013c01d4, 0x01310130, 0x01340137, 0x010f0135, 0x010d010c, - 0x01000103, 0x01070101, 0x01050104, 0x0113011c, 0x01140110, 0x0170017d, 0x01770171, 0x01750174, - 0x0140014c, 0x015d0145, 0x01510150, 0x01540157, 0x07f007f3, 0x07f407f1, 0x07c007cf, 0x07dc07c7, - 0x073007d5, 0x07350737, 0x0703070c, 0x07010700, 0x07040707, 0x071d071f, 0x07100713, 0x0774077d, - 0x074d074f, 0x07470740, 0x0754075c, 0x04fd04fc, 0x04f504f0, 0x04c304cc, 0x04c104c0, 0x04d004c4, - 0x0433043c, 0x04310430, 0x040f0434, 0x040d040c, 0x04000403, 0x04070401, 0x04050404, 0x0413041c, - 0x04110410, 0x047c0414, 0x04740470, 0x0443044c, 0x04410440, 0x04440447, 0x05f30450, 0x05c005f7, - 0x05df05c5, 0x05d105d0, 0x053005d4, 0x05340537, 0x0500050c, 0x05070501, 0x051d0504, 0x05170510, - 0x057c0515, 0x054d0575, 0x05410540, 0x05450547, 0x1ff0055c, 0x1fc11fc3, 0x1fd01fc4, 0x1f0f1f33, - 0x1f011f00, 0x1f051f07, 0x1f131f1c, 0x1f141f11, 0x1f411f7c, 0x1cfc1f50, 0x1cf11cf3, 0x1ccd1cf4, - 0x1cdc1cc0, 0x1cd11cdd, 0x1c301cd4, 0x1c0c1c34, 0x1c011c00, 0x1c101c04, 0x1c151c11, 0x1c751c73, - 0x1c401c4d, 0x1c511c5c, 0x1dcc1c54, 0x1dc41dc1, 0x1d3c1d3f, 0x1d001d31, 0x1d071d01, 0x1d701d1f, - 0x1d411d4c, 0x13cc1d50, 0x13c013cd, 0x13c513c1, 0x13d113dc, 0x133f13d4, 0x1330133d, 0x13351337, - 0x1303130c, 0x13011300, 0x13051304, 0x131d131f, 0x13731310, 0x13741370, 0x134d134f, 0x13401343, - 0x13471341, 0x135c1345, 0x13541353, 0x10f710f0, 0x10cc10f5, 0x10c110c0, 0x103310c4, 0x10311030, - 0x100f1034, 0x1003100c, 0x10011000, 0x101c1004, 0x10101013, 0x10141011, 0x10741071, 0x104c1075, - 0x10411040, 0x10451044, 0x1050105d, 0x10571051, 0x11f411fd, 0x11df11c0, 0x11d711d1, 0x113f11d4, - 0x11371130, 0x110c1135, 0x11001103, 0x11071101, 0x111f1105, 0x11171110, 0x117d117f, 0x11751170, - 0x11411143, 0x11441147, 0x1153115f, 0x11551151, 0x17c417c1, 0x173c17d0, 0x1700170d, 0x171c1705, - 0x17701714, 0x1747174c, 0x14fc1751, 0x14cf14f3, 0x14dc14c0, 0x14d114d3, 0x143f14d4, 0x1430143c, - 0x14371431, 0x1403140c, 0x14011400, 0x141f1404, 0x14151410, 0x1473147d, 0x14401475, 0x1453145c, - 0x14541450, 0x15c115cc, 0x153c15c7, 0x15341533, 0x1500150f, 0x15051507, 0x15101513, 0x15711514, - 0x15471543, 0x15511545, 0x7ffd7fff, 0x7ff57ff7, 0x7fdd7fdf, 0x7fd57fd7, 0x7f0f7f30, 0x7f037f0c, - 0x7f047f01, 0x7f7f7f10, 0x7f777f7d, 0x7f407f75, 0x7f5d7f5f, 0x7f557f57, 0x7ccc7cf0, 0x7cc17cc3, - 0x7cd07cc4, 0x7c337c3c, 0x7c0f7c34, 0x7c007c0d, 0x7c077c01, 0x7c137c04, 0x7c147c11, 0x7c747c70, - 0x7c417c43, 0x7c507c44, 0x7dfd7dff, 0x7df57df7, 0x7ddf7dc0, 0x7dd77ddd, 0x7d0c7dd5, 0x7d047d03, - 0x7d7f7d10, 0x7d777d7d, 0x7d407d75, 0x7d5d7d5f, 0x7d557d57, 0x73c473c3, 0x7333733c, 0x7300730c, - 0x731c7305, 0x73147313, 0x73447343, 0x70f470fc, 0x70c070cd, 0x70d170c5, 0x703f70d4, 0x7030703c, - 0x700c7037, 0x70007003, 0x70047001, 0x70107005, 0x70177011, 0x707c7015, 0x70717073, 0x704f7074, - 0x7040704d, 0x70517047, 0x71c171cc, 0x71d071c4, 0x7133713c, 0x71357134, 0x7100710f, 0x71057104, - 0x7111711c, 0x71707115, 0x7145714c, 0x77ff7153, 0x77f777fd, 0x77c077f5, 0x77dd77df, 0x77d577d7, - 0x7730773c, 0x7703770c, 0x77107704, 0x777f7714, 0x7777777d, 0x77407775, 0x775d775f, 0x77557757, - 0x74f174f0, 0x74c374cc, 0x74d074c1, 0x7433743c, 0x74347431, 0x740d740f, 0x74057400, 0x7413741c, - 0x74417470, 0x74507444, 0x75fd75ff, 0x75f575f7, 0x75df75c0, 0x75d775dd, 0x753075d5, 0x7503750c, - 0x757f7501, 0x7577757d, 0x75407575, 0x755d755f, 0x75557557, 0x4fcc4ff0, 0x4fc74fc1, 0x4fd04fc4, - 0x4f314f3c, 0x4f004f34, 0x4f054f07, 0x4f154f14, 0x4f4c4f70, 0x4f414f43, 0x4f504f44, 0x4cf34cfc, - 0x4cf44cf1, 0x4cc04ccf, 0x4cc54cc7, 0x4cd34cdc, 0x4cd44cd1, 0x4c304c3f, 0x4c0c4c0f, 0x4c004c03, - 0x4c044c01, 0x4c104c1d, 0x4c714c73, 0x4c404c4d, 0x4c5c4c47, 0x4c514c53, 0x4df04c54, 0x4dc34dcc, - 0x4dd04dc4, 0x4d314d33, 0x4d0f4d34, 0x4d004d0d, 0x4d114d07, 0x4d704d14, 0x4d414d43, 0x43fc4d54, - 0x43f143f3, 0x43c043cf, 0x43d143c7, 0x4335433f, 0x4303430c, 0x43014300, 0x43044307, 0x431c431f, - 0x4310431d, 0x43714373, 0x4343434d, 0x43474340, 0x4354435c, 0x40f040ff, 0x40f540f7, 0x40cc40cf, - 0x40c040c3, 0x40c440c1, 0x40d040dc, 0x40d540d4, 0x4033403c, 0x40314030, 0x400f4034, 0x400d400c, - 0x40004003, 0x40074001, 0x40054004, 0x4013401c, 0x40114010, 0x407c4014, 0x40774070, 0x404d404c, - 0x40404043, 0x40444041, 0x405f4045, 0x4050405d, 0x40554057, 0x41f341fc, 0x41c041cf, 0x41df41c4, - 0x41d441d1, 0x41374130, 0x410c4134, 0x4100410d, 0x41044101, 0x41174110, 0x4173417d, 0x41754174, - 0x4143414d, 0x41534140, 0x41544151, 0x47c147f0, 0x47d047c4, 0x4731473c, 0x470d470f, 0x47014700, - 0x47134705, 0x47704710, 0x4741474c, 0x47504744, 0x44f144f3, 0x44cf44f4, 0x44c044cd, 0x44c544c7, - 0x44dc44df, 0x44d144d3, 0x443d443f, 0x44374430, 0x440c4435, 0x44004403, 0x44044401, 0x4410441d, - 0x44154411, 0x4473447c, 0x444d444f, 0x44454440, 0x4451445c, 0x45c045f0, 0x453345d0, 0x45344531, - 0x4500450f, 0x451c4507, 0x454c4570, 0x45404543, 0x5fff4541, 0x5ff75ffd, 0x5fc05ff5, 0x5fdd5fdf, - 0x5fd55fd7, 0x5f0c5f30, 0x5f015f03, 0x5f7f5f04, 0x5f775f7d, 0x5f405f75, 0x5f5d5f5f, 0x5f555f57, - 0x5cf45cf0, 0x5cc35ccc, 0x5cc45cc1, 0x5c315cc5, 0x5c0c5c34, 0x5c075c00, 0x5c1c5c05, 0x5c705c13, - 0x5c4d5c4f, 0x5c445c41, 0x5df75dfd, 0x5dcf5df5, 0x5ddd5dc4, 0x5dd55dd7, 0x5d0c5d30, 0x5d045d01, - 0x5d7f5d10, 0x5d775d7d, 0x5d405d75, 0x5d5d5d5f, 0x5d555d57, 0x53d053c4, 0x5333533c, 0x5303530f, - 0x53075300, 0x531c5305, 0x53115310, 0x53145317, 0x50f15370, 0x50cf50f4, 0x50c050cd, 0x50d150c7, - 0x503d50d4, 0x500c5030, 0x50005003, 0x50045001, 0x50155010, 0x5073507c, 0x50715070, 0x504d5074, - 0x50475040, 0x51cc51f0, 0x51c551c1, 0x51d051dc, 0x51315133, 0x510d5135, 0x51015100, 0x511f5107, - 0x5171511d, 0x5140514f, 0x51445141, 0x5153515c, 0x57ff5151, 0x57f757fd, 0x57df57f5, 0x57d757dd, - 0x570c57d5, 0x57015703, 0x577f5704, 0x5777577d, 0x57405775, 0x575d575f, 0x57555757, 0x54c354f0, - 0x54dc54c4, 0x543c54d0, 0x5400540f, 0x541c5405, 0x54145411, 0x5441544f, 0x55fd55ff, 0x55f555f7, - 0x55dd55df, 0x55d555d7, 0x5503550c, 0x557f5501, 0x5577557d, 0x55405575, 0x555d555f, 0x55555557 -}; +layout (binding = IQ_GRID_BINDING) readonly buffer IQGrid { uint32_t iq_grid[]; }; -#if defined(NEEDS_IQ1S_GRID_GPU) -// Same content as iq1s_grid_const except each 2-bit value is expanded to 4-bit -// and has 1 added to it (allows packed values to be extracted with & 0x0F0F0F0F -// and 0xF0F0F0F0). This is only used by the q8_1/int-dot vector path. -const uint32_t[2048] iq1s_grid_gpu_const = { - 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000, - 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101, - 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200, - 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212, - 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011, - 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111, - 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220, - 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022, - 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220, - 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101, - 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110, - 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111, - 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010, - 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210, - 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221, - 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021, - 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002, - 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101, - 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101, - 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211, - 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110, - 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022, - 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121, - 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220, - 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001, - 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101, - 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102, - 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012, - 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010, - 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111, - 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122, - 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222, - 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001, - 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102, - 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101, - 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000, - 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101, - 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112, - 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110, - 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211, - 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012, - 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111, - 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120, - 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122, - 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121, - 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221, - 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001, - 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101, - 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101, - 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011, - 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111, - 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011, - 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122, - 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121, - 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222, - 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101, - 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000, - 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200, - 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110, - 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112, - 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222, - 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021, - 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121, - 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201, - 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200, - 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101, - 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011, - 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010, - 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211, - 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121, - 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000, - 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202, - 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202, - 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211, - 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112, - 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020, - 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121, - 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222, - 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102, - 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100, - 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110, - 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011, - 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111, - 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110, - 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121, - 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222, - 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201, - 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102, - 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201, - 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012, - 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010, - 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010, - 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110, - 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011, - 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212, - 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021, - 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021, - 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021, - 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101, - 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101, - 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100, - 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010, - 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111, - 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010, - 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111, - 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120, - 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120, - 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101, - 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001, - 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201, - 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210, - 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211, - 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111, - 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112, - 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211, - 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010, - 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021, - 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122, - 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221, - 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102, - 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100, - 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101, - 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101, - 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101, - 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012, - 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110, - 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112, - 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210, - 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210, - 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210, - 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010, - 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110, - 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122, - 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020, - 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021, - 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022, - 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120, - 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222, - 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221, - 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001, - 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102, - 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201, - 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012, - 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111, - 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012, - 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110, - 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110, - 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121, - 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221, - 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220, - 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222, - 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000, - 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201, - 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012, - 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011, - 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212, - 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221, - 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121, - 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202, - 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202, - 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002, - 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101, - 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210, - 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112, - 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011, - 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011, - 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210, - 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020, - 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220, - 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222, - 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222, - 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001, - 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010, - 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111, - 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010, - 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110, - 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221, - 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122, - 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202, - 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100, - 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101, - 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112, - 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111, - 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211, - 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222, - 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221, - 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022, - 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101, - 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211, - 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111, - 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111, - 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010, - 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121, - 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222, - 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000, - 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202, - 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000, - 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202, - 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110, - 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110, - 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222, - 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120, - 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022, - 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101, - 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202, - 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110, - 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110, - 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111, - 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111, - 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120, - 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121, - 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001, - 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202, - 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001, - 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200, - 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011, - 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212, - 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012, - 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110, - 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012, - 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111, - 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020, - 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121, - 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222, - 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102, - 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102, - 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101, - 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212, - 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210, - 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111, - 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212, - 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221, - 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121, - 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002, - 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000, - 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202, - 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112, - 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111, - 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020, - 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221, - 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022, - 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100, - 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201, - 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112, - 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211, - 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012, - 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121, - 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020, - 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120, - 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200, - 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200, - 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110, - 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011, - 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222, - 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020, - 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222, -}; -#endif +#define IQ1S_GRID_SIZE 2048 +// The buffer packs two 16-bit grid entries per uint32, so it needs no 16-bit storage buffer support +#define IQ1S_GRID_PACKED_LEN (IQ1S_GRID_SIZE / 2) -shared uint16_t iq1s_grid[2048]; +shared uint16_t iq1s_grid[IQ1S_GRID_SIZE]; #if defined(NEEDS_IQ1S_GRID_GPU) -shared uint32_t iq1s_grid_gpu[2048]; +shared uint32_t iq1s_grid_gpu[IQ1S_GRID_SIZE]; #endif -#if defined(DATA_A_IQ1_S) || defined(DATA_A_IQ1_M) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync - [[unroll]] for (uint i = 0; i < iq1s_grid_const.length(); i += wgsize.x) { + [[unroll]] for (uint i = 0; i < IQ1S_GRID_PACKED_LEN; i += wgsize.x) { uint idx = i + gl_LocalInvocationIndex.x; - if (iq1s_grid_const.length() % wgsize.x == 0 || idx < iq1s_grid_const.length()) { - u16vec2 g = unpack16(iq1s_grid_const[idx]); + if (IQ1S_GRID_PACKED_LEN % wgsize.x == 0 || idx < IQ1S_GRID_PACKED_LEN) { + u16vec2 g = unpack16(iq_grid[IQ1S_GRID_OFFSET / 4 + idx]); // bytes to uint32 index iq1s_grid[2*idx+0] = g.x; iq1s_grid[2*idx+1] = g.y; } } #if defined(NEEDS_IQ1S_GRID_GPU) - [[unroll]] for (uint i = 0; i < iq1s_grid_gpu_const.length(); i += wgsize.x) { + [[unroll]] for (uint i = 0; i < iq1s_grid_gpu.length(); i += wgsize.x) { uint idx = i + gl_LocalInvocationIndex.x; - if (iq1s_grid_gpu_const.length() % wgsize.x == 0 || idx < iq1s_grid_gpu_const.length()) { - iq1s_grid_gpu[idx] = iq1s_grid_gpu_const[idx]; + if (iq1s_grid_gpu.length() % wgsize.x == 0 || idx < iq1s_grid_gpu.length()) { + iq1s_grid_gpu[idx] = iq_grid[IQ1S_GRID_GPU_OFFSET / 4 + idx]; // bytes to uint32 index } } #endif barrier(); } #endif -#endif #if defined(DATA_A_IQ2_XXS) || defined(DATA_A_IQ2_XS) || defined(DATA_A_IQ2_S) +layout (binding = IQ_GRID_BINDING) readonly buffer IQGrid { uvec2 iq_grid[]; }; + #if defined(DATA_A_IQ2_S) shared uvec2 iq2s_grid[1024]; #elif defined(DATA_A_IQ2_XS) @@ -1023,96 +645,24 @@ struct block_iq2_xxs_packed16 uint16_t qs[QUANT_K_IQ2_XXS/8]; }; -#if defined(DATA_A_IQ2_XXS) - -const uvec2[256] iq2xxs_grid_const = { - uvec2(0x08080808, 0x08080808), uvec2(0x0808082b, 0x08080808), uvec2(0x08081919, 0x08080808), uvec2(0x08082b08, 0x08080808), - uvec2(0x08082b2b, 0x08080808), uvec2(0x08190819, 0x08080808), uvec2(0x08191908, 0x08080808), uvec2(0x082b0808, 0x08080808), - uvec2(0x082b082b, 0x08080808), uvec2(0x082b2b08, 0x08080808), uvec2(0x082b2b2b, 0x08080808), uvec2(0x19080819, 0x08080808), - uvec2(0x19081908, 0x08080808), uvec2(0x19190808, 0x08080808), uvec2(0x19192b08, 0x08080808), uvec2(0x192b0819, 0x08080808), - uvec2(0x192b1908, 0x08080808), uvec2(0x2b080808, 0x08080808), uvec2(0x2b08082b, 0x08080808), uvec2(0x2b082b2b, 0x08080808), - uvec2(0x2b2b082b, 0x08080808), uvec2(0x08080819, 0x08080819), uvec2(0x08081908, 0x08080819), uvec2(0x08190808, 0x08080819), - uvec2(0x08191919, 0x08080819), uvec2(0x19080808, 0x08080819), uvec2(0x2b081908, 0x08080819), uvec2(0x2b192b08, 0x08080819), - uvec2(0x08080808, 0x0808082b), uvec2(0x0808082b, 0x0808082b), uvec2(0x082b082b, 0x0808082b), uvec2(0x2b08082b, 0x0808082b), - uvec2(0x08080819, 0x08081908), uvec2(0x08081908, 0x08081908), uvec2(0x08190808, 0x08081908), uvec2(0x082b0819, 0x08081908), - uvec2(0x082b1908, 0x08081908), uvec2(0x19080808, 0x08081908), uvec2(0x1908082b, 0x08081908), uvec2(0x19082b08, 0x08081908), - uvec2(0x192b0808, 0x08081908), uvec2(0x2b080819, 0x08081908), uvec2(0x2b081908, 0x08081908), uvec2(0x2b190808, 0x08081908), - uvec2(0x2b2b1908, 0x08081908), uvec2(0x08080808, 0x08081919), uvec2(0x0808082b, 0x08081919), uvec2(0x08082b08, 0x08081919), - uvec2(0x082b0808, 0x08081919), uvec2(0x1908192b, 0x08081919), uvec2(0x192b2b19, 0x08081919), uvec2(0x2b080808, 0x08081919), - uvec2(0x2b190819, 0x08081919), uvec2(0x08082b19, 0x0808192b), uvec2(0x08190808, 0x0808192b), uvec2(0x19080808, 0x0808192b), - uvec2(0x2b081908, 0x0808192b), uvec2(0x2b2b1908, 0x0808192b), uvec2(0x08080808, 0x08082b08), uvec2(0x08081919, 0x08082b08), - uvec2(0x08082b08, 0x08082b08), uvec2(0x08191908, 0x08082b08), uvec2(0x082b2b08, 0x08082b08), uvec2(0x19080819, 0x08082b08), - uvec2(0x19081908, 0x08082b08), uvec2(0x19190808, 0x08082b08), uvec2(0x1919082b, 0x08082b08), uvec2(0x2b082b08, 0x08082b08), - uvec2(0x08081908, 0x08082b19), uvec2(0x19080808, 0x08082b19), uvec2(0x0808082b, 0x08082b2b), uvec2(0x08191908, 0x08082b2b), - uvec2(0x08080819, 0x08190808), uvec2(0x08081908, 0x08190808), uvec2(0x08190808, 0x08190808), uvec2(0x082b0819, 0x08190808), - uvec2(0x19080808, 0x08190808), uvec2(0x192b0808, 0x08190808), uvec2(0x2b081908, 0x08190808), uvec2(0x2b190808, 0x08190808), - uvec2(0x2b191919, 0x08190808), uvec2(0x08080808, 0x08190819), uvec2(0x08082b08, 0x08190819), uvec2(0x082b0808, 0x08190819), - uvec2(0x19190808, 0x08190819), uvec2(0x19192b2b, 0x08190819), uvec2(0x2b080808, 0x08190819), uvec2(0x082b1908, 0x0819082b), - uvec2(0x19081919, 0x0819082b), uvec2(0x08080808, 0x08191908), uvec2(0x08082b08, 0x08191908), uvec2(0x082b0808, 0x08191908), - uvec2(0x082b1919, 0x08191908), uvec2(0x19082b19, 0x08191908), uvec2(0x2b080808, 0x08191908), uvec2(0x08192b08, 0x08191919), - uvec2(0x192b082b, 0x08191919), uvec2(0x08080808, 0x0819192b), uvec2(0x0819192b, 0x0819192b), uvec2(0x08080819, 0x08192b08), - uvec2(0x08081908, 0x08192b08), uvec2(0x08190808, 0x08192b08), uvec2(0x19080808, 0x08192b08), uvec2(0x2b080819, 0x08192b08), - uvec2(0x08080808, 0x08192b19), uvec2(0x08081919, 0x08192b19), uvec2(0x2b2b0808, 0x08192b19), uvec2(0x19190819, 0x08192b2b), - uvec2(0x08080808, 0x082b0808), uvec2(0x0808082b, 0x082b0808), uvec2(0x08082b2b, 0x082b0808), uvec2(0x19081908, 0x082b0808), - uvec2(0x192b0819, 0x082b0808), uvec2(0x2b080808, 0x082b0808), uvec2(0x2b08082b, 0x082b0808), uvec2(0x082b2b19, 0x082b0819), - uvec2(0x19082b08, 0x082b0819), uvec2(0x08080808, 0x082b082b), uvec2(0x0808082b, 0x082b082b), uvec2(0x08080819, 0x082b1908), - uvec2(0x08081908, 0x082b1908), uvec2(0x08190808, 0x082b1908), uvec2(0x19080808, 0x082b1908), uvec2(0x1919192b, 0x082b1908), - uvec2(0x08080808, 0x082b1919), uvec2(0x19080819, 0x082b1919), uvec2(0x192b1908, 0x082b1919), uvec2(0x2b190808, 0x082b192b), - uvec2(0x08082b08, 0x082b2b08), uvec2(0x082b0808, 0x082b2b08), uvec2(0x2b191908, 0x082b2b08), uvec2(0x19081908, 0x082b2b2b), - uvec2(0x08080819, 0x19080808), uvec2(0x08081908, 0x19080808), uvec2(0x08190808, 0x19080808), uvec2(0x08192b08, 0x19080808), - uvec2(0x082b0819, 0x19080808), uvec2(0x082b1908, 0x19080808), uvec2(0x19080808, 0x19080808), uvec2(0x19082b08, 0x19080808), - uvec2(0x1919192b, 0x19080808), uvec2(0x192b0808, 0x19080808), uvec2(0x2b080819, 0x19080808), uvec2(0x2b081908, 0x19080808), - uvec2(0x2b190808, 0x19080808), uvec2(0x08080808, 0x19080819), uvec2(0x082b0808, 0x19080819), uvec2(0x192b0819, 0x19080819), - uvec2(0x2b080808, 0x19080819), uvec2(0x2b081919, 0x19080819), uvec2(0x08080819, 0x1908082b), uvec2(0x08190808, 0x1908082b), - uvec2(0x19082b08, 0x1908082b), uvec2(0x1919192b, 0x1908082b), uvec2(0x192b2b08, 0x1908082b), uvec2(0x08080808, 0x19081908), - uvec2(0x08082b08, 0x19081908), uvec2(0x082b0808, 0x19081908), uvec2(0x2b080808, 0x19081908), uvec2(0x2b192b19, 0x19081908), - uvec2(0x0819082b, 0x19081919), uvec2(0x082b1908, 0x19081919), uvec2(0x08080808, 0x1908192b), uvec2(0x08080819, 0x19082b08), - uvec2(0x08081908, 0x19082b08), uvec2(0x08190808, 0x19082b08), uvec2(0x19080808, 0x19082b08), uvec2(0x19081919, 0x19082b08), - uvec2(0x08080808, 0x19082b19), uvec2(0x19192b08, 0x19082b19), uvec2(0x192b0819, 0x19082b19), uvec2(0x2b08082b, 0x19082b19), - uvec2(0x19081919, 0x19082b2b), uvec2(0x2b190808, 0x19082b2b), uvec2(0x08080808, 0x19190808), uvec2(0x08082b08, 0x19190808), - uvec2(0x08190819, 0x19190808), uvec2(0x08192b19, 0x19190808), uvec2(0x082b0808, 0x19190808), uvec2(0x2b080808, 0x19190808), - uvec2(0x2b082b08, 0x19190808), uvec2(0x08081908, 0x19190819), uvec2(0x1908082b, 0x19190819), uvec2(0x2b2b1908, 0x19190819), - uvec2(0x2b190819, 0x1919082b), uvec2(0x2b190808, 0x19191908), uvec2(0x2b19082b, 0x19191908), uvec2(0x08082b2b, 0x19191919), - uvec2(0x08080819, 0x1919192b), uvec2(0x19191908, 0x1919192b), uvec2(0x08080808, 0x19192b08), uvec2(0x08190819, 0x19192b08), - uvec2(0x08192b19, 0x19192b08), uvec2(0x192b1908, 0x19192b08), uvec2(0x19080808, 0x19192b19), uvec2(0x08082b08, 0x19192b2b), - uvec2(0x08081908, 0x192b0808), uvec2(0x08190808, 0x192b0808), uvec2(0x19080808, 0x192b0808), uvec2(0x192b2b08, 0x192b0808), - uvec2(0x08080808, 0x192b0819), uvec2(0x19191919, 0x192b0819), uvec2(0x08192b08, 0x192b082b), uvec2(0x192b0808, 0x192b082b), - uvec2(0x08080808, 0x192b1908), uvec2(0x08081919, 0x192b1908), uvec2(0x08190808, 0x192b1919), uvec2(0x0819082b, 0x192b1919), - uvec2(0x2b081908, 0x192b1919), uvec2(0x1908082b, 0x192b2b08), uvec2(0x08080808, 0x2b080808), uvec2(0x0808082b, 0x2b080808), - uvec2(0x08082b2b, 0x2b080808), uvec2(0x19080819, 0x2b080808), uvec2(0x2b08082b, 0x2b080808), uvec2(0x08081908, 0x2b080819), - uvec2(0x08192b08, 0x2b080819), uvec2(0x19080808, 0x2b080819), uvec2(0x08190819, 0x2b08082b), uvec2(0x08080819, 0x2b081908), - uvec2(0x08081908, 0x2b081908), uvec2(0x08190808, 0x2b081908), uvec2(0x08191919, 0x2b081908), uvec2(0x19080808, 0x2b081908), - uvec2(0x192b0808, 0x2b081908), uvec2(0x08080808, 0x2b081919), uvec2(0x1908192b, 0x2b081919), uvec2(0x2b191908, 0x2b081919), - uvec2(0x08082b19, 0x2b08192b), uvec2(0x19080808, 0x2b08192b), uvec2(0x192b0808, 0x2b08192b), uvec2(0x0808082b, 0x2b082b08), - uvec2(0x08081908, 0x2b082b19), uvec2(0x08190819, 0x2b082b2b), uvec2(0x08081908, 0x2b190808), uvec2(0x08190808, 0x2b190808), - uvec2(0x082b1908, 0x2b190808), uvec2(0x19080808, 0x2b190808), uvec2(0x2b2b0819, 0x2b190808), uvec2(0x0819192b, 0x2b190819), - uvec2(0x2b080808, 0x2b190819), uvec2(0x19081919, 0x2b19082b), uvec2(0x08080808, 0x2b191908), uvec2(0x082b082b, 0x2b191908), - uvec2(0x19081908, 0x2b191908), uvec2(0x19190819, 0x2b191919), uvec2(0x2b080819, 0x2b192b08), uvec2(0x082b0808, 0x2b192b19), - uvec2(0x0808082b, 0x2b2b0808), uvec2(0x19190808, 0x2b2b0808), uvec2(0x2b081919, 0x2b2b0808), uvec2(0x08082b19, 0x2b2b0819), - uvec2(0x08080808, 0x2b2b082b), uvec2(0x08192b08, 0x2b2b1908), uvec2(0x19190808, 0x2b2b2b08), uvec2(0x08081908, 0x2b2b2b19) -}; - #if defined(DATA_A_IQ2_XXS) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq2xxs_grid.length(); i += wgsize.x) { - if (iq2xxs_grid_const.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xxs_grid_const.length()) { - iq2xxs_grid[i + gl_LocalInvocationIndex.x] = iq2xxs_grid_const[i + gl_LocalInvocationIndex.x]; + if (iq2xxs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xxs_grid.length()) { + iq2xxs_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ2XXS_GRID_OFFSET / 8 + i + gl_LocalInvocationIndex.x]; // bytes to uvec2 index } } barrier(); } -#endif -#if defined(DATA_A_IQ2_XXS) #define QUANT_K QUANT_K_IQ2_XXS #define QUANT_R QUANT_R_IQ2_XXS #define A_TYPE block_iq2_xxs #define A_TYPE_PACKED16 block_iq2_xxs_packed16 #endif -#endif #define QUANT_K_IQ2_XS 256 #define QUANT_R_IQ2_XS 1 @@ -1131,160 +681,24 @@ struct block_iq2_xs_packed16 uint16_t scales[QUANT_K_IQ2_XS/64]; }; -#if defined(DATA_A_IQ2_XS) - -const uvec2 iq2xs_grid_const[512] = { - uvec2(0x08080808, 0x08080808), uvec2(0x0808082b, 0x08080808), uvec2(0x08081919, 0x08080808), uvec2(0x08082b08, 0x08080808), - uvec2(0x08082b2b, 0x08080808), uvec2(0x08190819, 0x08080808), uvec2(0x08191908, 0x08080808), uvec2(0x0819192b, 0x08080808), - uvec2(0x08192b19, 0x08080808), uvec2(0x082b0808, 0x08080808), uvec2(0x082b082b, 0x08080808), uvec2(0x082b1919, 0x08080808), - uvec2(0x082b2b08, 0x08080808), uvec2(0x19080819, 0x08080808), uvec2(0x19081908, 0x08080808), uvec2(0x1908192b, 0x08080808), - uvec2(0x19082b19, 0x08080808), uvec2(0x19190808, 0x08080808), uvec2(0x1919082b, 0x08080808), uvec2(0x19191919, 0x08080808), - uvec2(0x19192b08, 0x08080808), uvec2(0x192b0819, 0x08080808), uvec2(0x192b1908, 0x08080808), uvec2(0x2b080808, 0x08080808), - uvec2(0x2b08082b, 0x08080808), uvec2(0x2b081919, 0x08080808), uvec2(0x2b082b08, 0x08080808), uvec2(0x2b190819, 0x08080808), - uvec2(0x2b191908, 0x08080808), uvec2(0x2b192b19, 0x08080808), uvec2(0x2b2b0808, 0x08080808), uvec2(0x08080819, 0x08080819), - uvec2(0x08081908, 0x08080819), uvec2(0x0808192b, 0x08080819), uvec2(0x08082b19, 0x08080819), uvec2(0x08190808, 0x08080819), - uvec2(0x0819082b, 0x08080819), uvec2(0x08191919, 0x08080819), uvec2(0x08192b08, 0x08080819), uvec2(0x08192b2b, 0x08080819), - uvec2(0x082b0819, 0x08080819), uvec2(0x082b1908, 0x08080819), uvec2(0x19080808, 0x08080819), uvec2(0x1908082b, 0x08080819), - uvec2(0x19081919, 0x08080819), uvec2(0x19082b08, 0x08080819), uvec2(0x19190819, 0x08080819), uvec2(0x19191908, 0x08080819), - uvec2(0x192b0808, 0x08080819), uvec2(0x192b2b08, 0x08080819), uvec2(0x2b080819, 0x08080819), uvec2(0x2b081908, 0x08080819), - uvec2(0x2b190808, 0x08080819), uvec2(0x08080808, 0x0808082b), uvec2(0x0808082b, 0x0808082b), uvec2(0x08081919, 0x0808082b), - uvec2(0x08082b08, 0x0808082b), uvec2(0x08190819, 0x0808082b), uvec2(0x08191908, 0x0808082b), uvec2(0x082b0808, 0x0808082b), - uvec2(0x19080819, 0x0808082b), uvec2(0x19081908, 0x0808082b), uvec2(0x19190808, 0x0808082b), uvec2(0x19191919, 0x0808082b), - uvec2(0x2b080808, 0x0808082b), uvec2(0x2b082b2b, 0x0808082b), uvec2(0x08080819, 0x08081908), uvec2(0x08081908, 0x08081908), - uvec2(0x0808192b, 0x08081908), uvec2(0x08082b19, 0x08081908), uvec2(0x08190808, 0x08081908), uvec2(0x0819082b, 0x08081908), - uvec2(0x08191919, 0x08081908), uvec2(0x08192b08, 0x08081908), uvec2(0x082b0819, 0x08081908), uvec2(0x082b1908, 0x08081908), - uvec2(0x19080808, 0x08081908), uvec2(0x1908082b, 0x08081908), uvec2(0x19081919, 0x08081908), uvec2(0x19082b08, 0x08081908), - uvec2(0x19190819, 0x08081908), uvec2(0x19191908, 0x08081908), uvec2(0x1919192b, 0x08081908), uvec2(0x192b0808, 0x08081908), - uvec2(0x2b080819, 0x08081908), uvec2(0x2b081908, 0x08081908), uvec2(0x2b190808, 0x08081908), uvec2(0x08080808, 0x08081919), - uvec2(0x0808082b, 0x08081919), uvec2(0x08081919, 0x08081919), uvec2(0x08082b08, 0x08081919), uvec2(0x08190819, 0x08081919), - uvec2(0x08191908, 0x08081919), uvec2(0x082b0808, 0x08081919), uvec2(0x19080819, 0x08081919), uvec2(0x19081908, 0x08081919), - uvec2(0x19190808, 0x08081919), uvec2(0x192b0819, 0x08081919), uvec2(0x2b080808, 0x08081919), uvec2(0x08080819, 0x0808192b), - uvec2(0x08081908, 0x0808192b), uvec2(0x08190808, 0x0808192b), uvec2(0x082b192b, 0x0808192b), uvec2(0x19080808, 0x0808192b), - uvec2(0x1908082b, 0x0808192b), uvec2(0x2b081908, 0x0808192b), uvec2(0x08080808, 0x08082b08), uvec2(0x0808082b, 0x08082b08), - uvec2(0x08081919, 0x08082b08), uvec2(0x08082b08, 0x08082b08), uvec2(0x08082b2b, 0x08082b08), uvec2(0x08190819, 0x08082b08), - uvec2(0x08191908, 0x08082b08), uvec2(0x082b0808, 0x08082b08), uvec2(0x082b1919, 0x08082b08), uvec2(0x19080819, 0x08082b08), - uvec2(0x19081908, 0x08082b08), uvec2(0x19190808, 0x08082b08), uvec2(0x19192b08, 0x08082b08), uvec2(0x2b080808, 0x08082b08), - uvec2(0x2b2b0808, 0x08082b08), uvec2(0x2b2b2b2b, 0x08082b08), uvec2(0x08080819, 0x08082b19), uvec2(0x08081908, 0x08082b19), - uvec2(0x08190808, 0x08082b19), uvec2(0x19080808, 0x08082b19), uvec2(0x2b080819, 0x08082b19), uvec2(0x2b082b19, 0x08082b19), - uvec2(0x08080808, 0x08082b2b), uvec2(0x082b0808, 0x08082b2b), uvec2(0x082b2b08, 0x08082b2b), uvec2(0x2b19192b, 0x08082b2b), - uvec2(0x2b2b0808, 0x08082b2b), uvec2(0x08080819, 0x08190808), uvec2(0x08081908, 0x08190808), uvec2(0x0808192b, 0x08190808), - uvec2(0x08082b19, 0x08190808), uvec2(0x08190808, 0x08190808), uvec2(0x0819082b, 0x08190808), uvec2(0x08191919, 0x08190808), - uvec2(0x08192b08, 0x08190808), uvec2(0x082b0819, 0x08190808), uvec2(0x082b1908, 0x08190808), uvec2(0x19080808, 0x08190808), - uvec2(0x1908082b, 0x08190808), uvec2(0x19081919, 0x08190808), uvec2(0x19082b08, 0x08190808), uvec2(0x19190819, 0x08190808), - uvec2(0x19191908, 0x08190808), uvec2(0x192b0808, 0x08190808), uvec2(0x192b2b2b, 0x08190808), uvec2(0x2b080819, 0x08190808), - uvec2(0x2b081908, 0x08190808), uvec2(0x2b190808, 0x08190808), uvec2(0x08080808, 0x08190819), uvec2(0x0808082b, 0x08190819), - uvec2(0x08081919, 0x08190819), uvec2(0x08082b08, 0x08190819), uvec2(0x08190819, 0x08190819), uvec2(0x08191908, 0x08190819), - uvec2(0x082b0808, 0x08190819), uvec2(0x19080819, 0x08190819), uvec2(0x19081908, 0x08190819), uvec2(0x19190808, 0x08190819), - uvec2(0x2b080808, 0x08190819), uvec2(0x2b191908, 0x08190819), uvec2(0x2b19192b, 0x08190819), uvec2(0x08080819, 0x0819082b), - uvec2(0x08081908, 0x0819082b), uvec2(0x0808192b, 0x0819082b), uvec2(0x08190808, 0x0819082b), uvec2(0x19080808, 0x0819082b), - uvec2(0x192b0808, 0x0819082b), uvec2(0x08080808, 0x08191908), uvec2(0x0808082b, 0x08191908), uvec2(0x08081919, 0x08191908), - uvec2(0x08082b08, 0x08191908), uvec2(0x08190819, 0x08191908), uvec2(0x08191908, 0x08191908), uvec2(0x082b0808, 0x08191908), - uvec2(0x19080819, 0x08191908), uvec2(0x19081908, 0x08191908), uvec2(0x19082b19, 0x08191908), uvec2(0x19190808, 0x08191908), - uvec2(0x192b1908, 0x08191908), uvec2(0x2b080808, 0x08191908), uvec2(0x08080819, 0x08191919), uvec2(0x08081908, 0x08191919), - uvec2(0x08190808, 0x08191919), uvec2(0x19080808, 0x08191919), uvec2(0x08080808, 0x0819192b), uvec2(0x08191908, 0x0819192b), - uvec2(0x19082b19, 0x0819192b), uvec2(0x08080819, 0x08192b08), uvec2(0x08081908, 0x08192b08), uvec2(0x08190808, 0x08192b08), - uvec2(0x0819082b, 0x08192b08), uvec2(0x19080808, 0x08192b08), uvec2(0x19191908, 0x08192b08), uvec2(0x2b08192b, 0x08192b08), - uvec2(0x08080808, 0x08192b19), uvec2(0x08081919, 0x08192b19), uvec2(0x192b192b, 0x08192b19), uvec2(0x19190819, 0x08192b2b), - uvec2(0x2b2b2b19, 0x08192b2b), uvec2(0x08080808, 0x082b0808), uvec2(0x0808082b, 0x082b0808), uvec2(0x08081919, 0x082b0808), - uvec2(0x08082b08, 0x082b0808), uvec2(0x08082b2b, 0x082b0808), uvec2(0x08190819, 0x082b0808), uvec2(0x08191908, 0x082b0808), - uvec2(0x082b0808, 0x082b0808), uvec2(0x19080819, 0x082b0808), uvec2(0x19081908, 0x082b0808), uvec2(0x19190808, 0x082b0808), - uvec2(0x2b080808, 0x082b0808), uvec2(0x2b2b0808, 0x082b0808), uvec2(0x08080819, 0x082b0819), uvec2(0x08081908, 0x082b0819), - uvec2(0x08190808, 0x082b0819), uvec2(0x19080808, 0x082b0819), uvec2(0x19082b08, 0x082b0819), uvec2(0x192b1919, 0x082b0819), - uvec2(0x08080808, 0x082b082b), uvec2(0x082b082b, 0x082b082b), uvec2(0x2b080808, 0x082b082b), uvec2(0x2b2b2b08, 0x082b082b), - uvec2(0x08080819, 0x082b1908), uvec2(0x08081908, 0x082b1908), uvec2(0x08190808, 0x082b1908), uvec2(0x082b2b19, 0x082b1908), - uvec2(0x19080808, 0x082b1908), uvec2(0x08080808, 0x082b1919), uvec2(0x19080819, 0x082b1919), uvec2(0x1919082b, 0x082b1919), - uvec2(0x2b192b19, 0x082b1919), uvec2(0x08080819, 0x082b192b), uvec2(0x08192b2b, 0x082b192b), uvec2(0x2b2b192b, 0x082b192b), - uvec2(0x08080808, 0x082b2b08), uvec2(0x08082b08, 0x082b2b08), uvec2(0x08082b2b, 0x082b2b08), uvec2(0x082b0808, 0x082b2b08), - uvec2(0x19191919, 0x082b2b08), uvec2(0x2b082b08, 0x082b2b08), uvec2(0x2b2b082b, 0x082b2b08), uvec2(0x192b2b08, 0x082b2b19), - uvec2(0x2b190808, 0x082b2b19), uvec2(0x08082b08, 0x082b2b2b), uvec2(0x082b0808, 0x082b2b2b), uvec2(0x2b08082b, 0x082b2b2b), - uvec2(0x2b082b08, 0x082b2b2b), uvec2(0x2b082b2b, 0x082b2b2b), uvec2(0x08080819, 0x19080808), uvec2(0x08081908, 0x19080808), - uvec2(0x0808192b, 0x19080808), uvec2(0x08082b19, 0x19080808), uvec2(0x08190808, 0x19080808), uvec2(0x0819082b, 0x19080808), - uvec2(0x08191919, 0x19080808), uvec2(0x08192b08, 0x19080808), uvec2(0x082b0819, 0x19080808), uvec2(0x082b1908, 0x19080808), - uvec2(0x19080808, 0x19080808), uvec2(0x1908082b, 0x19080808), uvec2(0x19081919, 0x19080808), uvec2(0x19082b08, 0x19080808), - uvec2(0x19082b2b, 0x19080808), uvec2(0x19190819, 0x19080808), uvec2(0x19191908, 0x19080808), uvec2(0x192b0808, 0x19080808), - uvec2(0x192b1919, 0x19080808), uvec2(0x2b080819, 0x19080808), uvec2(0x2b081908, 0x19080808), uvec2(0x2b190808, 0x19080808), - uvec2(0x08080808, 0x19080819), uvec2(0x0808082b, 0x19080819), uvec2(0x08081919, 0x19080819), uvec2(0x08082b08, 0x19080819), - uvec2(0x08190819, 0x19080819), uvec2(0x08191908, 0x19080819), uvec2(0x082b0808, 0x19080819), uvec2(0x19080819, 0x19080819), - uvec2(0x19081908, 0x19080819), uvec2(0x19190808, 0x19080819), uvec2(0x2b080808, 0x19080819), uvec2(0x2b081919, 0x19080819), - uvec2(0x2b2b082b, 0x19080819), uvec2(0x08080819, 0x1908082b), uvec2(0x08081908, 0x1908082b), uvec2(0x08190808, 0x1908082b), - uvec2(0x0819082b, 0x1908082b), uvec2(0x082b2b19, 0x1908082b), uvec2(0x19080808, 0x1908082b), uvec2(0x08080808, 0x19081908), - uvec2(0x0808082b, 0x19081908), uvec2(0x08081919, 0x19081908), uvec2(0x08082b08, 0x19081908), uvec2(0x08190819, 0x19081908), - uvec2(0x08191908, 0x19081908), uvec2(0x08192b19, 0x19081908), uvec2(0x082b0808, 0x19081908), uvec2(0x19080819, 0x19081908), - uvec2(0x19081908, 0x19081908), uvec2(0x19190808, 0x19081908), uvec2(0x2b080808, 0x19081908), uvec2(0x2b191908, 0x19081908), - uvec2(0x08080819, 0x19081919), uvec2(0x08081908, 0x19081919), uvec2(0x08190808, 0x19081919), uvec2(0x082b1908, 0x19081919), - uvec2(0x19080808, 0x19081919), uvec2(0x2b192b2b, 0x19081919), uvec2(0x08080808, 0x1908192b), uvec2(0x08082b2b, 0x1908192b), - uvec2(0x19081908, 0x1908192b), uvec2(0x19190808, 0x1908192b), uvec2(0x08080819, 0x19082b08), uvec2(0x08081908, 0x19082b08), - uvec2(0x08190808, 0x19082b08), uvec2(0x19080808, 0x19082b08), uvec2(0x19081919, 0x19082b08), uvec2(0x19191908, 0x19082b08), - uvec2(0x192b082b, 0x19082b08), uvec2(0x08080808, 0x19082b19), uvec2(0x08190819, 0x19082b19), uvec2(0x19081908, 0x19082b19), - uvec2(0x19190808, 0x19082b19), uvec2(0x192b2b19, 0x19082b19), uvec2(0x08081908, 0x19082b2b), uvec2(0x08080808, 0x19190808), - uvec2(0x0808082b, 0x19190808), uvec2(0x08081919, 0x19190808), uvec2(0x08082b08, 0x19190808), uvec2(0x08190819, 0x19190808), - uvec2(0x08191908, 0x19190808), uvec2(0x082b0808, 0x19190808), uvec2(0x082b2b08, 0x19190808), uvec2(0x19080819, 0x19190808), - uvec2(0x19081908, 0x19190808), uvec2(0x19190808, 0x19190808), uvec2(0x2b080808, 0x19190808), uvec2(0x08080819, 0x19190819), - uvec2(0x08081908, 0x19190819), uvec2(0x08190808, 0x19190819), uvec2(0x08191919, 0x19190819), uvec2(0x19080808, 0x19190819), - uvec2(0x1908082b, 0x19190819), uvec2(0x08080808, 0x1919082b), uvec2(0x19081908, 0x1919082b), uvec2(0x2b2b2b2b, 0x1919082b), - uvec2(0x08080819, 0x19191908), uvec2(0x08081908, 0x19191908), uvec2(0x08190808, 0x19191908), uvec2(0x082b0819, 0x19191908), - uvec2(0x19080808, 0x19191908), uvec2(0x192b0808, 0x19191908), uvec2(0x2b080819, 0x19191908), uvec2(0x2b2b0819, 0x19191908), - uvec2(0x08080808, 0x19191919), uvec2(0x08082b08, 0x19191919), uvec2(0x2b080808, 0x19191919), uvec2(0x2b082b08, 0x19191919), - uvec2(0x082b0819, 0x1919192b), uvec2(0x192b2b08, 0x1919192b), uvec2(0x2b2b0819, 0x1919192b), uvec2(0x08080808, 0x19192b08), - uvec2(0x08191908, 0x19192b08), uvec2(0x19080819, 0x19192b08), uvec2(0x19190808, 0x19192b08), uvec2(0x2b192b19, 0x19192b08), - uvec2(0x08192b2b, 0x19192b19), uvec2(0x19080808, 0x19192b19), uvec2(0x1908082b, 0x19192b19), uvec2(0x2b081919, 0x19192b2b), - uvec2(0x08080819, 0x192b0808), uvec2(0x08081908, 0x192b0808), uvec2(0x08190808, 0x192b0808), uvec2(0x19080808, 0x192b0808), - uvec2(0x19191908, 0x192b0808), uvec2(0x192b082b, 0x192b0808), uvec2(0x2b08192b, 0x192b0808), uvec2(0x2b2b2b19, 0x192b0808), - uvec2(0x08080808, 0x192b0819), uvec2(0x082b1908, 0x192b082b), uvec2(0x19082b2b, 0x192b082b), uvec2(0x2b19082b, 0x192b082b), - uvec2(0x08080808, 0x192b1908), uvec2(0x0819192b, 0x192b1908), uvec2(0x08190808, 0x192b1919), uvec2(0x19080808, 0x192b1919), - uvec2(0x19081919, 0x192b1919), uvec2(0x2b2b1908, 0x192b1919), uvec2(0x08080819, 0x192b2b08), uvec2(0x192b2b2b, 0x192b2b08), - uvec2(0x082b1919, 0x192b2b19), uvec2(0x0808192b, 0x192b2b2b), uvec2(0x19191908, 0x192b2b2b), uvec2(0x192b082b, 0x192b2b2b), - uvec2(0x08080808, 0x2b080808), uvec2(0x0808082b, 0x2b080808), uvec2(0x08081919, 0x2b080808), uvec2(0x08082b08, 0x2b080808), - uvec2(0x08190819, 0x2b080808), uvec2(0x08191908, 0x2b080808), uvec2(0x082b0808, 0x2b080808), uvec2(0x082b2b2b, 0x2b080808), - uvec2(0x19080819, 0x2b080808), uvec2(0x19081908, 0x2b080808), uvec2(0x19190808, 0x2b080808), uvec2(0x2b080808, 0x2b080808), - uvec2(0x2b08082b, 0x2b080808), uvec2(0x2b2b2b08, 0x2b080808), uvec2(0x2b2b2b2b, 0x2b080808), uvec2(0x08080819, 0x2b080819), - uvec2(0x08081908, 0x2b080819), uvec2(0x0808192b, 0x2b080819), uvec2(0x08190808, 0x2b080819), uvec2(0x19080808, 0x2b080819), - uvec2(0x19190819, 0x2b080819), uvec2(0x19192b19, 0x2b080819), uvec2(0x08080808, 0x2b08082b), uvec2(0x082b0808, 0x2b08082b), - uvec2(0x2b080808, 0x2b08082b), uvec2(0x2b08082b, 0x2b08082b), uvec2(0x2b2b0808, 0x2b08082b), uvec2(0x2b2b2b08, 0x2b08082b), - uvec2(0x08080819, 0x2b081908), uvec2(0x08081908, 0x2b081908), uvec2(0x08190808, 0x2b081908), uvec2(0x0819082b, 0x2b081908), - uvec2(0x08191919, 0x2b081908), uvec2(0x19080808, 0x2b081908), uvec2(0x192b0808, 0x2b081908), uvec2(0x2b082b19, 0x2b081908), - uvec2(0x08080808, 0x2b081919), uvec2(0x19081908, 0x2b081919), uvec2(0x2b2b1919, 0x2b081919), uvec2(0x08192b08, 0x2b08192b), - uvec2(0x192b2b2b, 0x2b08192b), uvec2(0x08080808, 0x2b082b08), uvec2(0x08082b08, 0x2b082b08), uvec2(0x082b1919, 0x2b082b08), - uvec2(0x19192b2b, 0x2b082b08), uvec2(0x2b080808, 0x2b082b08), uvec2(0x2b08082b, 0x2b082b08), uvec2(0x2b2b2b08, 0x2b082b08), - uvec2(0x0808192b, 0x2b082b19), uvec2(0x082b082b, 0x2b082b2b), uvec2(0x2b080808, 0x2b082b2b), uvec2(0x2b082b08, 0x2b082b2b), - uvec2(0x2b19192b, 0x2b082b2b), uvec2(0x2b2b2b08, 0x2b082b2b), uvec2(0x08080819, 0x2b190808), uvec2(0x08081908, 0x2b190808), - uvec2(0x08190808, 0x2b190808), uvec2(0x19080808, 0x2b190808), uvec2(0x1919192b, 0x2b190808), uvec2(0x2b081908, 0x2b190808), - uvec2(0x08080808, 0x2b190819), uvec2(0x082b082b, 0x2b190819), uvec2(0x192b1908, 0x2b190819), uvec2(0x1919192b, 0x2b19082b), - uvec2(0x2b082b19, 0x2b19082b), uvec2(0x08080808, 0x2b191908), uvec2(0x08081919, 0x2b191908), uvec2(0x19081908, 0x2b191908), - uvec2(0x19190808, 0x2b191908), uvec2(0x19192b08, 0x2b191908), uvec2(0x082b2b19, 0x2b191919), uvec2(0x2b190808, 0x2b191919), - uvec2(0x2b19082b, 0x2b191919), uvec2(0x19080819, 0x2b19192b), uvec2(0x19190819, 0x2b192b08), uvec2(0x2b2b192b, 0x2b192b08), - uvec2(0x19082b19, 0x2b192b19), uvec2(0x08191919, 0x2b192b2b), uvec2(0x192b0808, 0x2b192b2b), uvec2(0x08080808, 0x2b2b0808), - uvec2(0x0808082b, 0x2b2b0808), uvec2(0x08082b08, 0x2b2b0808), uvec2(0x08082b2b, 0x2b2b0808), uvec2(0x082b0808, 0x2b2b0808), - uvec2(0x082b2b2b, 0x2b2b0808), uvec2(0x2b2b0808, 0x2b2b0808), uvec2(0x19190819, 0x2b2b0819), uvec2(0x19192b19, 0x2b2b0819), - uvec2(0x2b2b192b, 0x2b2b0819), uvec2(0x08080808, 0x2b2b082b), uvec2(0x0808082b, 0x2b2b082b), uvec2(0x08082b08, 0x2b2b082b), - uvec2(0x082b2b2b, 0x2b2b082b), uvec2(0x2b080808, 0x2b2b082b), uvec2(0x2b2b0808, 0x2b2b082b), uvec2(0x19080808, 0x2b2b1908), - uvec2(0x2b191919, 0x2b2b1908), uvec2(0x192b1919, 0x2b2b192b), uvec2(0x2b192b08, 0x2b2b192b), uvec2(0x08082b2b, 0x2b2b2b08), - uvec2(0x082b0808, 0x2b2b2b08), uvec2(0x082b082b, 0x2b2b2b08), uvec2(0x082b2b08, 0x2b2b2b08), uvec2(0x2b2b0808, 0x2b2b2b08), - uvec2(0x2b2b2b08, 0x2b2b2b08), uvec2(0x08081908, 0x2b2b2b19), uvec2(0x2b081908, 0x2b2b2b19), uvec2(0x2b08192b, 0x2b2b2b19), - uvec2(0x082b2b08, 0x2b2b2b2b), uvec2(0x082b2b2b, 0x2b2b2b2b), uvec2(0x2b190819, 0x2b2b2b2b), uvec2(0x2b2b2b2b, 0x2b2b2b2b), -}; - #if defined(DATA_A_IQ2_XS) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq2xs_grid.length(); i += wgsize.x) { - if (iq2xs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xs_grid_const.length()) { - iq2xs_grid[i + gl_LocalInvocationIndex.x] = iq2xs_grid_const[i + gl_LocalInvocationIndex.x]; + if (iq2xs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2xs_grid.length()) { + iq2xs_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ2XS_GRID_OFFSET / 8 + i + gl_LocalInvocationIndex.x]; // bytes to uvec2 index } } barrier(); } -#endif -#if defined(DATA_A_IQ2_XS) #define QUANT_K QUANT_K_IQ2_XS #define QUANT_R QUANT_R_IQ2_XS #define A_TYPE block_iq2_xs #define A_TYPE_PACKED16 block_iq2_xs_packed16 #endif -#endif #define QUANT_K_IQ2_S 256 #define QUANT_R_IQ2_S 1 @@ -1305,290 +719,28 @@ struct block_iq2_s_packed16 uint16_t scales[QUANT_K_IQ2_S/64]; }; -#if defined(DATA_A_IQ2_S) - -const uvec2 iq2s_grid_const[1024] = { - uvec2(0x08080808, 0x08080808), uvec2(0x0808082b, 0x08080808), uvec2(0x08081919, 0x08080808), uvec2(0x08082b08, 0x08080808), - uvec2(0x08082b2b, 0x08080808), uvec2(0x08190819, 0x08080808), uvec2(0x08191908, 0x08080808), uvec2(0x0819192b, 0x08080808), - uvec2(0x08192b19, 0x08080808), uvec2(0x082b0808, 0x08080808), uvec2(0x082b082b, 0x08080808), uvec2(0x082b1919, 0x08080808), - uvec2(0x082b2b08, 0x08080808), uvec2(0x19080819, 0x08080808), uvec2(0x19081908, 0x08080808), uvec2(0x1908192b, 0x08080808), - uvec2(0x19082b19, 0x08080808), uvec2(0x19190808, 0x08080808), uvec2(0x1919082b, 0x08080808), uvec2(0x19191919, 0x08080808), - uvec2(0x19192b08, 0x08080808), uvec2(0x192b0819, 0x08080808), uvec2(0x192b1908, 0x08080808), uvec2(0x192b192b, 0x08080808), - uvec2(0x192b2b19, 0x08080808), uvec2(0x2b080808, 0x08080808), uvec2(0x2b08082b, 0x08080808), uvec2(0x2b081919, 0x08080808), - uvec2(0x2b082b08, 0x08080808), uvec2(0x2b190819, 0x08080808), uvec2(0x2b191908, 0x08080808), uvec2(0x2b2b0808, 0x08080808), - uvec2(0x2b2b1919, 0x08080808), uvec2(0x2b2b2b2b, 0x08080808), uvec2(0x08080819, 0x08080819), uvec2(0x08081908, 0x08080819), - uvec2(0x0808192b, 0x08080819), uvec2(0x08082b19, 0x08080819), uvec2(0x08190808, 0x08080819), uvec2(0x0819082b, 0x08080819), - uvec2(0x08191919, 0x08080819), uvec2(0x08192b08, 0x08080819), uvec2(0x082b0819, 0x08080819), uvec2(0x082b1908, 0x08080819), - uvec2(0x19080808, 0x08080819), uvec2(0x1908082b, 0x08080819), uvec2(0x19081919, 0x08080819), uvec2(0x19082b08, 0x08080819), - uvec2(0x19190819, 0x08080819), uvec2(0x19191908, 0x08080819), uvec2(0x1919192b, 0x08080819), uvec2(0x19192b19, 0x08080819), - uvec2(0x192b0808, 0x08080819), uvec2(0x192b1919, 0x08080819), uvec2(0x192b2b08, 0x08080819), uvec2(0x2b080819, 0x08080819), - uvec2(0x2b081908, 0x08080819), uvec2(0x2b190808, 0x08080819), uvec2(0x2b19082b, 0x08080819), uvec2(0x2b191919, 0x08080819), - uvec2(0x2b2b0819, 0x08080819), uvec2(0x2b2b1908, 0x08080819), uvec2(0x08080808, 0x0808082b), uvec2(0x0808082b, 0x0808082b), - uvec2(0x08081919, 0x0808082b), uvec2(0x08082b08, 0x0808082b), uvec2(0x08190819, 0x0808082b), uvec2(0x08191908, 0x0808082b), - uvec2(0x082b0808, 0x0808082b), uvec2(0x082b2b2b, 0x0808082b), uvec2(0x19080819, 0x0808082b), uvec2(0x19081908, 0x0808082b), - uvec2(0x1908192b, 0x0808082b), uvec2(0x19082b19, 0x0808082b), uvec2(0x19190808, 0x0808082b), uvec2(0x19191919, 0x0808082b), - uvec2(0x2b080808, 0x0808082b), uvec2(0x2b081919, 0x0808082b), uvec2(0x2b082b2b, 0x0808082b), uvec2(0x2b191908, 0x0808082b), - uvec2(0x2b2b082b, 0x0808082b), uvec2(0x08080819, 0x08081908), uvec2(0x08081908, 0x08081908), uvec2(0x0808192b, 0x08081908), - uvec2(0x08082b19, 0x08081908), uvec2(0x08190808, 0x08081908), uvec2(0x0819082b, 0x08081908), uvec2(0x08191919, 0x08081908), - uvec2(0x08192b08, 0x08081908), uvec2(0x082b0819, 0x08081908), uvec2(0x082b1908, 0x08081908), uvec2(0x082b192b, 0x08081908), - uvec2(0x082b2b19, 0x08081908), uvec2(0x19080808, 0x08081908), uvec2(0x1908082b, 0x08081908), uvec2(0x19081919, 0x08081908), - uvec2(0x19082b08, 0x08081908), uvec2(0x19082b2b, 0x08081908), uvec2(0x19190819, 0x08081908), uvec2(0x19191908, 0x08081908), - uvec2(0x1919192b, 0x08081908), uvec2(0x19192b19, 0x08081908), uvec2(0x192b0808, 0x08081908), uvec2(0x192b082b, 0x08081908), - uvec2(0x192b1919, 0x08081908), uvec2(0x2b080819, 0x08081908), uvec2(0x2b081908, 0x08081908), uvec2(0x2b08192b, 0x08081908), - uvec2(0x2b082b19, 0x08081908), uvec2(0x2b190808, 0x08081908), uvec2(0x2b191919, 0x08081908), uvec2(0x2b192b08, 0x08081908), - uvec2(0x2b2b0819, 0x08081908), uvec2(0x2b2b1908, 0x08081908), uvec2(0x08080808, 0x08081919), uvec2(0x0808082b, 0x08081919), - uvec2(0x08081919, 0x08081919), uvec2(0x08082b08, 0x08081919), uvec2(0x08082b2b, 0x08081919), uvec2(0x08190819, 0x08081919), - uvec2(0x08191908, 0x08081919), uvec2(0x0819192b, 0x08081919), uvec2(0x08192b19, 0x08081919), uvec2(0x082b0808, 0x08081919), - uvec2(0x082b1919, 0x08081919), uvec2(0x082b2b08, 0x08081919), uvec2(0x19080819, 0x08081919), uvec2(0x19081908, 0x08081919), - uvec2(0x1908192b, 0x08081919), uvec2(0x19082b19, 0x08081919), uvec2(0x19190808, 0x08081919), uvec2(0x1919082b, 0x08081919), - uvec2(0x19191919, 0x08081919), uvec2(0x19192b08, 0x08081919), uvec2(0x192b0819, 0x08081919), uvec2(0x192b1908, 0x08081919), - uvec2(0x2b080808, 0x08081919), uvec2(0x2b08082b, 0x08081919), uvec2(0x2b081919, 0x08081919), uvec2(0x2b082b08, 0x08081919), - uvec2(0x2b190819, 0x08081919), uvec2(0x2b191908, 0x08081919), uvec2(0x2b2b0808, 0x08081919), uvec2(0x08080819, 0x0808192b), - uvec2(0x08081908, 0x0808192b), uvec2(0x0808192b, 0x0808192b), uvec2(0x08082b19, 0x0808192b), uvec2(0x08190808, 0x0808192b), - uvec2(0x08191919, 0x0808192b), uvec2(0x19080808, 0x0808192b), uvec2(0x19081919, 0x0808192b), uvec2(0x19082b08, 0x0808192b), - uvec2(0x19190819, 0x0808192b), uvec2(0x19191908, 0x0808192b), uvec2(0x192b0808, 0x0808192b), uvec2(0x2b080819, 0x0808192b), - uvec2(0x2b081908, 0x0808192b), uvec2(0x2b190808, 0x0808192b), uvec2(0x08080808, 0x08082b08), uvec2(0x0808082b, 0x08082b08), - uvec2(0x08081919, 0x08082b08), uvec2(0x08082b08, 0x08082b08), uvec2(0x08190819, 0x08082b08), uvec2(0x08191908, 0x08082b08), - uvec2(0x0819192b, 0x08082b08), uvec2(0x08192b19, 0x08082b08), uvec2(0x082b0808, 0x08082b08), uvec2(0x082b1919, 0x08082b08), - uvec2(0x082b2b2b, 0x08082b08), uvec2(0x19080819, 0x08082b08), uvec2(0x19081908, 0x08082b08), uvec2(0x1908192b, 0x08082b08), - uvec2(0x19082b19, 0x08082b08), uvec2(0x19190808, 0x08082b08), uvec2(0x1919082b, 0x08082b08), uvec2(0x19191919, 0x08082b08), - uvec2(0x19192b08, 0x08082b08), uvec2(0x192b0819, 0x08082b08), uvec2(0x192b1908, 0x08082b08), uvec2(0x2b080808, 0x08082b08), - uvec2(0x2b081919, 0x08082b08), uvec2(0x2b191908, 0x08082b08), uvec2(0x2b2b2b2b, 0x08082b08), uvec2(0x08080819, 0x08082b19), - uvec2(0x08081908, 0x08082b19), uvec2(0x08190808, 0x08082b19), uvec2(0x0819082b, 0x08082b19), uvec2(0x08191919, 0x08082b19), - uvec2(0x08192b08, 0x08082b19), uvec2(0x082b0819, 0x08082b19), uvec2(0x19080808, 0x08082b19), uvec2(0x19081919, 0x08082b19), - uvec2(0x19082b08, 0x08082b19), uvec2(0x19190819, 0x08082b19), uvec2(0x19191908, 0x08082b19), uvec2(0x192b0808, 0x08082b19), - uvec2(0x2b080819, 0x08082b19), uvec2(0x2b190808, 0x08082b19), uvec2(0x08080808, 0x08082b2b), uvec2(0x08190819, 0x08082b2b), - uvec2(0x08191908, 0x08082b2b), uvec2(0x082b082b, 0x08082b2b), uvec2(0x082b2b08, 0x08082b2b), uvec2(0x082b2b2b, 0x08082b2b), - uvec2(0x19190808, 0x08082b2b), uvec2(0x2b192b19, 0x08082b2b), uvec2(0x08080819, 0x08190808), uvec2(0x08081908, 0x08190808), - uvec2(0x0808192b, 0x08190808), uvec2(0x08082b19, 0x08190808), uvec2(0x08190808, 0x08190808), uvec2(0x0819082b, 0x08190808), - uvec2(0x08191919, 0x08190808), uvec2(0x08192b08, 0x08190808), uvec2(0x082b0819, 0x08190808), uvec2(0x082b1908, 0x08190808), - uvec2(0x082b192b, 0x08190808), uvec2(0x19080808, 0x08190808), uvec2(0x1908082b, 0x08190808), uvec2(0x19081919, 0x08190808), - uvec2(0x19082b08, 0x08190808), uvec2(0x19190819, 0x08190808), uvec2(0x19191908, 0x08190808), uvec2(0x1919192b, 0x08190808), - uvec2(0x19192b19, 0x08190808), uvec2(0x192b0808, 0x08190808), uvec2(0x192b082b, 0x08190808), uvec2(0x192b1919, 0x08190808), - uvec2(0x192b2b08, 0x08190808), uvec2(0x2b080819, 0x08190808), uvec2(0x2b081908, 0x08190808), uvec2(0x2b08192b, 0x08190808), - uvec2(0x2b190808, 0x08190808), uvec2(0x2b191919, 0x08190808), uvec2(0x2b192b08, 0x08190808), uvec2(0x2b2b0819, 0x08190808), - uvec2(0x2b2b1908, 0x08190808), uvec2(0x08080808, 0x08190819), uvec2(0x0808082b, 0x08190819), uvec2(0x08081919, 0x08190819), - uvec2(0x08082b08, 0x08190819), uvec2(0x08082b2b, 0x08190819), uvec2(0x08190819, 0x08190819), uvec2(0x08191908, 0x08190819), - uvec2(0x0819192b, 0x08190819), uvec2(0x08192b19, 0x08190819), uvec2(0x082b0808, 0x08190819), uvec2(0x082b082b, 0x08190819), - uvec2(0x082b1919, 0x08190819), uvec2(0x082b2b08, 0x08190819), uvec2(0x19080819, 0x08190819), uvec2(0x19081908, 0x08190819), - uvec2(0x1908192b, 0x08190819), uvec2(0x19082b19, 0x08190819), uvec2(0x19190808, 0x08190819), uvec2(0x1919082b, 0x08190819), - uvec2(0x19191919, 0x08190819), uvec2(0x19192b08, 0x08190819), uvec2(0x192b0819, 0x08190819), uvec2(0x192b1908, 0x08190819), - uvec2(0x2b080808, 0x08190819), uvec2(0x2b08082b, 0x08190819), uvec2(0x2b081919, 0x08190819), uvec2(0x2b082b08, 0x08190819), - uvec2(0x2b190819, 0x08190819), uvec2(0x2b191908, 0x08190819), uvec2(0x08080819, 0x0819082b), uvec2(0x08081908, 0x0819082b), - uvec2(0x08082b19, 0x0819082b), uvec2(0x08190808, 0x0819082b), uvec2(0x08191919, 0x0819082b), uvec2(0x082b0819, 0x0819082b), - uvec2(0x082b1908, 0x0819082b), uvec2(0x19080808, 0x0819082b), uvec2(0x19081919, 0x0819082b), uvec2(0x19190819, 0x0819082b), - uvec2(0x19191908, 0x0819082b), uvec2(0x2b080819, 0x0819082b), uvec2(0x2b081908, 0x0819082b), uvec2(0x2b190808, 0x0819082b), - uvec2(0x08080808, 0x08191908), uvec2(0x0808082b, 0x08191908), uvec2(0x08081919, 0x08191908), uvec2(0x08082b08, 0x08191908), - uvec2(0x08190819, 0x08191908), uvec2(0x08191908, 0x08191908), uvec2(0x0819192b, 0x08191908), uvec2(0x08192b19, 0x08191908), - uvec2(0x082b0808, 0x08191908), uvec2(0x082b1919, 0x08191908), uvec2(0x082b2b08, 0x08191908), uvec2(0x19080819, 0x08191908), - uvec2(0x19081908, 0x08191908), uvec2(0x1908192b, 0x08191908), uvec2(0x19082b19, 0x08191908), uvec2(0x19190808, 0x08191908), - uvec2(0x1919082b, 0x08191908), uvec2(0x19191919, 0x08191908), uvec2(0x19192b08, 0x08191908), uvec2(0x192b0819, 0x08191908), - uvec2(0x192b1908, 0x08191908), uvec2(0x2b080808, 0x08191908), uvec2(0x2b08082b, 0x08191908), uvec2(0x2b081919, 0x08191908), - uvec2(0x2b082b08, 0x08191908), uvec2(0x2b190819, 0x08191908), uvec2(0x2b191908, 0x08191908), uvec2(0x2b2b0808, 0x08191908), - uvec2(0x08080819, 0x08191919), uvec2(0x08081908, 0x08191919), uvec2(0x0808192b, 0x08191919), uvec2(0x08082b19, 0x08191919), - uvec2(0x08190808, 0x08191919), uvec2(0x0819082b, 0x08191919), uvec2(0x08191919, 0x08191919), uvec2(0x08192b08, 0x08191919), - uvec2(0x082b0819, 0x08191919), uvec2(0x082b1908, 0x08191919), uvec2(0x19080808, 0x08191919), uvec2(0x1908082b, 0x08191919), - uvec2(0x19081919, 0x08191919), uvec2(0x19082b08, 0x08191919), uvec2(0x19190819, 0x08191919), uvec2(0x19191908, 0x08191919), - uvec2(0x192b0808, 0x08191919), uvec2(0x2b080819, 0x08191919), uvec2(0x2b081908, 0x08191919), uvec2(0x2b190808, 0x08191919), - uvec2(0x08080808, 0x0819192b), uvec2(0x08081919, 0x0819192b), uvec2(0x08082b08, 0x0819192b), uvec2(0x08190819, 0x0819192b), - uvec2(0x08191908, 0x0819192b), uvec2(0x082b0808, 0x0819192b), uvec2(0x19080819, 0x0819192b), uvec2(0x19081908, 0x0819192b), - uvec2(0x19190808, 0x0819192b), uvec2(0x2b080808, 0x0819192b), uvec2(0x2b2b2b2b, 0x0819192b), uvec2(0x08080819, 0x08192b08), - uvec2(0x08081908, 0x08192b08), uvec2(0x0808192b, 0x08192b08), uvec2(0x08082b19, 0x08192b08), uvec2(0x08190808, 0x08192b08), - uvec2(0x08191919, 0x08192b08), uvec2(0x08192b08, 0x08192b08), uvec2(0x082b0819, 0x08192b08), uvec2(0x19080808, 0x08192b08), - uvec2(0x1908082b, 0x08192b08), uvec2(0x19081919, 0x08192b08), uvec2(0x19082b08, 0x08192b08), uvec2(0x19190819, 0x08192b08), - uvec2(0x19191908, 0x08192b08), uvec2(0x192b0808, 0x08192b08), uvec2(0x2b080819, 0x08192b08), uvec2(0x2b081908, 0x08192b08), - uvec2(0x08080808, 0x08192b19), uvec2(0x0808082b, 0x08192b19), uvec2(0x08081919, 0x08192b19), uvec2(0x08082b08, 0x08192b19), - uvec2(0x08190819, 0x08192b19), uvec2(0x08191908, 0x08192b19), uvec2(0x082b0808, 0x08192b19), uvec2(0x19080819, 0x08192b19), - uvec2(0x19081908, 0x08192b19), uvec2(0x19190808, 0x08192b19), uvec2(0x192b2b19, 0x08192b19), uvec2(0x2b2b082b, 0x08192b19), - uvec2(0x08081908, 0x08192b2b), uvec2(0x08190808, 0x08192b2b), uvec2(0x19080808, 0x08192b2b), uvec2(0x1919192b, 0x08192b2b), - uvec2(0x08080808, 0x082b0808), uvec2(0x0808082b, 0x082b0808), uvec2(0x08081919, 0x082b0808), uvec2(0x08082b08, 0x082b0808), - uvec2(0x08190819, 0x082b0808), uvec2(0x08191908, 0x082b0808), uvec2(0x0819192b, 0x082b0808), uvec2(0x08192b19, 0x082b0808), - uvec2(0x082b0808, 0x082b0808), uvec2(0x082b1919, 0x082b0808), uvec2(0x082b2b2b, 0x082b0808), uvec2(0x19080819, 0x082b0808), - uvec2(0x19081908, 0x082b0808), uvec2(0x19190808, 0x082b0808), uvec2(0x1919082b, 0x082b0808), uvec2(0x19191919, 0x082b0808), - uvec2(0x192b1908, 0x082b0808), uvec2(0x2b080808, 0x082b0808), uvec2(0x2b082b2b, 0x082b0808), uvec2(0x2b191908, 0x082b0808), - uvec2(0x2b2b2b2b, 0x082b0808), uvec2(0x08080819, 0x082b0819), uvec2(0x08081908, 0x082b0819), uvec2(0x08190808, 0x082b0819), - uvec2(0x0819082b, 0x082b0819), uvec2(0x08191919, 0x082b0819), uvec2(0x082b0819, 0x082b0819), uvec2(0x19080808, 0x082b0819), - uvec2(0x1908082b, 0x082b0819), uvec2(0x19081919, 0x082b0819), uvec2(0x19190819, 0x082b0819), uvec2(0x19191908, 0x082b0819), - uvec2(0x192b0808, 0x082b0819), uvec2(0x2b080819, 0x082b0819), uvec2(0x2b081908, 0x082b0819), uvec2(0x2b190808, 0x082b0819), - uvec2(0x08080808, 0x082b082b), uvec2(0x08082b2b, 0x082b082b), uvec2(0x082b082b, 0x082b082b), uvec2(0x082b2b08, 0x082b082b), - uvec2(0x082b2b2b, 0x082b082b), uvec2(0x19081908, 0x082b082b), uvec2(0x19190808, 0x082b082b), uvec2(0x2b082b08, 0x082b082b), - uvec2(0x2b082b2b, 0x082b082b), uvec2(0x2b2b2b08, 0x082b082b), uvec2(0x08080819, 0x082b1908), uvec2(0x08081908, 0x082b1908), - uvec2(0x0808192b, 0x082b1908), uvec2(0x08082b19, 0x082b1908), uvec2(0x08190808, 0x082b1908), uvec2(0x08191919, 0x082b1908), - uvec2(0x08192b08, 0x082b1908), uvec2(0x082b0819, 0x082b1908), uvec2(0x082b1908, 0x082b1908), uvec2(0x19080808, 0x082b1908), - uvec2(0x1908082b, 0x082b1908), uvec2(0x19081919, 0x082b1908), uvec2(0x19082b08, 0x082b1908), uvec2(0x19190819, 0x082b1908), - uvec2(0x19191908, 0x082b1908), uvec2(0x192b0808, 0x082b1908), uvec2(0x2b080819, 0x082b1908), uvec2(0x2b081908, 0x082b1908), - uvec2(0x2b190808, 0x082b1908), uvec2(0x08080808, 0x082b1919), uvec2(0x08081919, 0x082b1919), uvec2(0x08082b08, 0x082b1919), - uvec2(0x08190819, 0x082b1919), uvec2(0x08191908, 0x082b1919), uvec2(0x082b0808, 0x082b1919), uvec2(0x19080819, 0x082b1919), - uvec2(0x19081908, 0x082b1919), uvec2(0x19190808, 0x082b1919), uvec2(0x192b192b, 0x082b1919), uvec2(0x2b080808, 0x082b1919), - uvec2(0x08080819, 0x082b192b), uvec2(0x08081908, 0x082b192b), uvec2(0x08190808, 0x082b192b), uvec2(0x19080808, 0x082b192b), - uvec2(0x19192b19, 0x082b192b), uvec2(0x08080808, 0x082b2b08), uvec2(0x08081919, 0x082b2b08), uvec2(0x08190819, 0x082b2b08), - uvec2(0x08191908, 0x082b2b08), uvec2(0x19080819, 0x082b2b08), uvec2(0x19081908, 0x082b2b08), uvec2(0x19190808, 0x082b2b08), - uvec2(0x2b082b2b, 0x082b2b08), uvec2(0x2b2b2b2b, 0x082b2b08), uvec2(0x08080819, 0x082b2b19), uvec2(0x08081908, 0x082b2b19), - uvec2(0x08190808, 0x082b2b19), uvec2(0x2b191919, 0x082b2b19), uvec2(0x08082b2b, 0x082b2b2b), uvec2(0x082b082b, 0x082b2b2b), - uvec2(0x192b1908, 0x082b2b2b), uvec2(0x2b082b08, 0x082b2b2b), uvec2(0x2b082b2b, 0x082b2b2b), uvec2(0x08080819, 0x19080808), - uvec2(0x08081908, 0x19080808), uvec2(0x0808192b, 0x19080808), uvec2(0x08082b19, 0x19080808), uvec2(0x08190808, 0x19080808), - uvec2(0x0819082b, 0x19080808), uvec2(0x08191919, 0x19080808), uvec2(0x08192b08, 0x19080808), uvec2(0x08192b2b, 0x19080808), - uvec2(0x082b0819, 0x19080808), uvec2(0x082b1908, 0x19080808), uvec2(0x082b192b, 0x19080808), uvec2(0x19080808, 0x19080808), - uvec2(0x1908082b, 0x19080808), uvec2(0x19081919, 0x19080808), uvec2(0x19082b08, 0x19080808), uvec2(0x19082b2b, 0x19080808), - uvec2(0x19190819, 0x19080808), uvec2(0x19191908, 0x19080808), uvec2(0x1919192b, 0x19080808), uvec2(0x19192b19, 0x19080808), - uvec2(0x192b0808, 0x19080808), uvec2(0x192b082b, 0x19080808), uvec2(0x192b1919, 0x19080808), uvec2(0x2b080819, 0x19080808), - uvec2(0x2b081908, 0x19080808), uvec2(0x2b190808, 0x19080808), uvec2(0x2b191919, 0x19080808), uvec2(0x2b192b08, 0x19080808), - uvec2(0x2b2b0819, 0x19080808), uvec2(0x2b2b1908, 0x19080808), uvec2(0x08080808, 0x19080819), uvec2(0x0808082b, 0x19080819), - uvec2(0x08081919, 0x19080819), uvec2(0x08082b08, 0x19080819), uvec2(0x08190819, 0x19080819), uvec2(0x08191908, 0x19080819), - uvec2(0x0819192b, 0x19080819), uvec2(0x08192b19, 0x19080819), uvec2(0x082b0808, 0x19080819), uvec2(0x082b082b, 0x19080819), - uvec2(0x082b1919, 0x19080819), uvec2(0x19080819, 0x19080819), uvec2(0x19081908, 0x19080819), uvec2(0x1908192b, 0x19080819), - uvec2(0x19082b19, 0x19080819), uvec2(0x19190808, 0x19080819), uvec2(0x1919082b, 0x19080819), uvec2(0x19191919, 0x19080819), - uvec2(0x19192b08, 0x19080819), uvec2(0x192b0819, 0x19080819), uvec2(0x192b1908, 0x19080819), uvec2(0x2b080808, 0x19080819), - uvec2(0x2b08082b, 0x19080819), uvec2(0x2b081919, 0x19080819), uvec2(0x2b082b08, 0x19080819), uvec2(0x2b190819, 0x19080819), - uvec2(0x2b191908, 0x19080819), uvec2(0x2b2b0808, 0x19080819), uvec2(0x08080819, 0x1908082b), uvec2(0x08081908, 0x1908082b), - uvec2(0x08190808, 0x1908082b), uvec2(0x0819082b, 0x1908082b), uvec2(0x08191919, 0x1908082b), uvec2(0x08192b08, 0x1908082b), - uvec2(0x082b1908, 0x1908082b), uvec2(0x19080808, 0x1908082b), uvec2(0x19081919, 0x1908082b), uvec2(0x19082b08, 0x1908082b), - uvec2(0x19190819, 0x1908082b), uvec2(0x19191908, 0x1908082b), uvec2(0x192b0808, 0x1908082b), uvec2(0x2b080819, 0x1908082b), - uvec2(0x2b081908, 0x1908082b), uvec2(0x08080808, 0x19081908), uvec2(0x0808082b, 0x19081908), uvec2(0x08081919, 0x19081908), - uvec2(0x08082b08, 0x19081908), uvec2(0x08082b2b, 0x19081908), uvec2(0x08190819, 0x19081908), uvec2(0x08191908, 0x19081908), - uvec2(0x0819192b, 0x19081908), uvec2(0x08192b19, 0x19081908), uvec2(0x082b0808, 0x19081908), uvec2(0x082b082b, 0x19081908), - uvec2(0x082b1919, 0x19081908), uvec2(0x082b2b08, 0x19081908), uvec2(0x19080819, 0x19081908), uvec2(0x19081908, 0x19081908), - uvec2(0x1908192b, 0x19081908), uvec2(0x19082b19, 0x19081908), uvec2(0x19190808, 0x19081908), uvec2(0x1919082b, 0x19081908), - uvec2(0x19191919, 0x19081908), uvec2(0x19192b08, 0x19081908), uvec2(0x192b0819, 0x19081908), uvec2(0x192b1908, 0x19081908), - uvec2(0x2b080808, 0x19081908), uvec2(0x2b08082b, 0x19081908), uvec2(0x2b081919, 0x19081908), uvec2(0x2b082b08, 0x19081908), - uvec2(0x2b190819, 0x19081908), uvec2(0x2b191908, 0x19081908), uvec2(0x2b2b0808, 0x19081908), uvec2(0x08080819, 0x19081919), - uvec2(0x08081908, 0x19081919), uvec2(0x0808192b, 0x19081919), uvec2(0x08082b19, 0x19081919), uvec2(0x08190808, 0x19081919), - uvec2(0x0819082b, 0x19081919), uvec2(0x08191919, 0x19081919), uvec2(0x08192b08, 0x19081919), uvec2(0x082b0819, 0x19081919), - uvec2(0x082b1908, 0x19081919), uvec2(0x19080808, 0x19081919), uvec2(0x1908082b, 0x19081919), uvec2(0x19081919, 0x19081919), - uvec2(0x19082b08, 0x19081919), uvec2(0x19190819, 0x19081919), uvec2(0x19191908, 0x19081919), uvec2(0x192b0808, 0x19081919), - uvec2(0x192b2b2b, 0x19081919), uvec2(0x2b080819, 0x19081919), uvec2(0x2b081908, 0x19081919), uvec2(0x2b190808, 0x19081919), - uvec2(0x08080808, 0x1908192b), uvec2(0x0808082b, 0x1908192b), uvec2(0x08081919, 0x1908192b), uvec2(0x08082b08, 0x1908192b), - uvec2(0x08190819, 0x1908192b), uvec2(0x08191908, 0x1908192b), uvec2(0x082b0808, 0x1908192b), uvec2(0x19080819, 0x1908192b), - uvec2(0x19081908, 0x1908192b), uvec2(0x19190808, 0x1908192b), uvec2(0x2b080808, 0x1908192b), uvec2(0x2b2b1919, 0x1908192b), - uvec2(0x08080819, 0x19082b08), uvec2(0x08081908, 0x19082b08), uvec2(0x08082b19, 0x19082b08), uvec2(0x08190808, 0x19082b08), - uvec2(0x0819082b, 0x19082b08), uvec2(0x08191919, 0x19082b08), uvec2(0x08192b08, 0x19082b08), uvec2(0x082b0819, 0x19082b08), - uvec2(0x082b1908, 0x19082b08), uvec2(0x19080808, 0x19082b08), uvec2(0x1908082b, 0x19082b08), uvec2(0x19081919, 0x19082b08), - uvec2(0x19082b08, 0x19082b08), uvec2(0x19190819, 0x19082b08), uvec2(0x19191908, 0x19082b08), uvec2(0x192b0808, 0x19082b08), - uvec2(0x2b081908, 0x19082b08), uvec2(0x2b190808, 0x19082b08), uvec2(0x08080808, 0x19082b19), uvec2(0x0808082b, 0x19082b19), - uvec2(0x08081919, 0x19082b19), uvec2(0x08082b08, 0x19082b19), uvec2(0x08190819, 0x19082b19), uvec2(0x08191908, 0x19082b19), - uvec2(0x082b0808, 0x19082b19), uvec2(0x19080819, 0x19082b19), uvec2(0x19081908, 0x19082b19), uvec2(0x19190808, 0x19082b19), - uvec2(0x2b080808, 0x19082b19), uvec2(0x2b19192b, 0x19082b19), uvec2(0x08080819, 0x19082b2b), uvec2(0x08081908, 0x19082b2b), - uvec2(0x08190808, 0x19082b2b), uvec2(0x19080808, 0x19082b2b), uvec2(0x08080808, 0x19190808), uvec2(0x0808082b, 0x19190808), - uvec2(0x08081919, 0x19190808), uvec2(0x08082b08, 0x19190808), uvec2(0x08190819, 0x19190808), uvec2(0x08191908, 0x19190808), - uvec2(0x0819192b, 0x19190808), uvec2(0x08192b19, 0x19190808), uvec2(0x082b0808, 0x19190808), uvec2(0x082b082b, 0x19190808), - uvec2(0x082b1919, 0x19190808), uvec2(0x082b2b08, 0x19190808), uvec2(0x19080819, 0x19190808), uvec2(0x19081908, 0x19190808), - uvec2(0x1908192b, 0x19190808), uvec2(0x19082b19, 0x19190808), uvec2(0x19190808, 0x19190808), uvec2(0x1919082b, 0x19190808), - uvec2(0x19191919, 0x19190808), uvec2(0x19192b08, 0x19190808), uvec2(0x192b0819, 0x19190808), uvec2(0x192b1908, 0x19190808), - uvec2(0x2b080808, 0x19190808), uvec2(0x2b08082b, 0x19190808), uvec2(0x2b081919, 0x19190808), uvec2(0x2b082b08, 0x19190808), - uvec2(0x2b190819, 0x19190808), uvec2(0x2b191908, 0x19190808), uvec2(0x08080819, 0x19190819), uvec2(0x08081908, 0x19190819), - uvec2(0x0808192b, 0x19190819), uvec2(0x08082b19, 0x19190819), uvec2(0x08190808, 0x19190819), uvec2(0x0819082b, 0x19190819), - uvec2(0x08191919, 0x19190819), uvec2(0x08192b08, 0x19190819), uvec2(0x082b0819, 0x19190819), uvec2(0x082b1908, 0x19190819), - uvec2(0x19080808, 0x19190819), uvec2(0x1908082b, 0x19190819), uvec2(0x19081919, 0x19190819), uvec2(0x19082b08, 0x19190819), - uvec2(0x19190819, 0x19190819), uvec2(0x19191908, 0x19190819), uvec2(0x192b0808, 0x19190819), uvec2(0x2b080819, 0x19190819), - uvec2(0x2b081908, 0x19190819), uvec2(0x2b190808, 0x19190819), uvec2(0x08080808, 0x1919082b), uvec2(0x08081919, 0x1919082b), - uvec2(0x08082b08, 0x1919082b), uvec2(0x08190819, 0x1919082b), uvec2(0x08191908, 0x1919082b), uvec2(0x082b0808, 0x1919082b), - uvec2(0x19080819, 0x1919082b), uvec2(0x19081908, 0x1919082b), uvec2(0x19190808, 0x1919082b), uvec2(0x192b2b19, 0x1919082b), - uvec2(0x2b080808, 0x1919082b), uvec2(0x08080819, 0x19191908), uvec2(0x08081908, 0x19191908), uvec2(0x0808192b, 0x19191908), - uvec2(0x08082b19, 0x19191908), uvec2(0x08190808, 0x19191908), uvec2(0x0819082b, 0x19191908), uvec2(0x08191919, 0x19191908), - uvec2(0x08192b08, 0x19191908), uvec2(0x082b0819, 0x19191908), uvec2(0x082b1908, 0x19191908), uvec2(0x19080808, 0x19191908), - uvec2(0x1908082b, 0x19191908), uvec2(0x19081919, 0x19191908), uvec2(0x19082b08, 0x19191908), uvec2(0x19190819, 0x19191908), - uvec2(0x19191908, 0x19191908), uvec2(0x192b0808, 0x19191908), uvec2(0x2b080819, 0x19191908), uvec2(0x2b081908, 0x19191908), - uvec2(0x2b190808, 0x19191908), uvec2(0x08080808, 0x19191919), uvec2(0x0808082b, 0x19191919), uvec2(0x08081919, 0x19191919), - uvec2(0x08082b08, 0x19191919), uvec2(0x08190819, 0x19191919), uvec2(0x08191908, 0x19191919), uvec2(0x082b0808, 0x19191919), - uvec2(0x19080819, 0x19191919), uvec2(0x19081908, 0x19191919), uvec2(0x19190808, 0x19191919), uvec2(0x2b080808, 0x19191919), - uvec2(0x08080819, 0x1919192b), uvec2(0x08081908, 0x1919192b), uvec2(0x08190808, 0x1919192b), uvec2(0x082b192b, 0x1919192b), - uvec2(0x19080808, 0x1919192b), uvec2(0x08080808, 0x19192b08), uvec2(0x0808082b, 0x19192b08), uvec2(0x08081919, 0x19192b08), - uvec2(0x08082b08, 0x19192b08), uvec2(0x08190819, 0x19192b08), uvec2(0x08191908, 0x19192b08), uvec2(0x082b0808, 0x19192b08), - uvec2(0x19080819, 0x19192b08), uvec2(0x19081908, 0x19192b08), uvec2(0x19190808, 0x19192b08), uvec2(0x19192b2b, 0x19192b08), - uvec2(0x2b080808, 0x19192b08), uvec2(0x08080819, 0x19192b19), uvec2(0x08081908, 0x19192b19), uvec2(0x08190808, 0x19192b19), - uvec2(0x19080808, 0x19192b19), uvec2(0x08080808, 0x19192b2b), uvec2(0x08192b19, 0x19192b2b), uvec2(0x2b081919, 0x19192b2b), - uvec2(0x2b2b2b08, 0x19192b2b), uvec2(0x08080819, 0x192b0808), uvec2(0x08081908, 0x192b0808), uvec2(0x0808192b, 0x192b0808), - uvec2(0x08190808, 0x192b0808), uvec2(0x0819082b, 0x192b0808), uvec2(0x08191919, 0x192b0808), uvec2(0x08192b08, 0x192b0808), - uvec2(0x082b0819, 0x192b0808), uvec2(0x082b1908, 0x192b0808), uvec2(0x19080808, 0x192b0808), uvec2(0x19081919, 0x192b0808), - uvec2(0x19082b08, 0x192b0808), uvec2(0x19190819, 0x192b0808), uvec2(0x19191908, 0x192b0808), uvec2(0x192b0808, 0x192b0808), - uvec2(0x2b081908, 0x192b0808), uvec2(0x2b190808, 0x192b0808), uvec2(0x08080808, 0x192b0819), uvec2(0x0808082b, 0x192b0819), - uvec2(0x08081919, 0x192b0819), uvec2(0x08082b08, 0x192b0819), uvec2(0x08190819, 0x192b0819), uvec2(0x08191908, 0x192b0819), - uvec2(0x082b0808, 0x192b0819), uvec2(0x19080819, 0x192b0819), uvec2(0x19081908, 0x192b0819), uvec2(0x19190808, 0x192b0819), - uvec2(0x2b080808, 0x192b0819), uvec2(0x2b192b19, 0x192b0819), uvec2(0x08081908, 0x192b082b), uvec2(0x08190808, 0x192b082b), - uvec2(0x19080808, 0x192b082b), uvec2(0x1919192b, 0x192b082b), uvec2(0x2b2b0819, 0x192b082b), uvec2(0x08080808, 0x192b1908), - uvec2(0x08081919, 0x192b1908), uvec2(0x08082b08, 0x192b1908), uvec2(0x08190819, 0x192b1908), uvec2(0x08191908, 0x192b1908), - uvec2(0x082b0808, 0x192b1908), uvec2(0x19080819, 0x192b1908), uvec2(0x19081908, 0x192b1908), uvec2(0x19190808, 0x192b1908), - uvec2(0x2b080808, 0x192b1908), uvec2(0x08080819, 0x192b1919), uvec2(0x08081908, 0x192b1919), uvec2(0x08190808, 0x192b1919), - uvec2(0x19080808, 0x192b1919), uvec2(0x19082b2b, 0x192b1919), uvec2(0x192b2b08, 0x192b1919), uvec2(0x2b19082b, 0x192b1919), - uvec2(0x08080808, 0x192b192b), uvec2(0x2b191908, 0x192b192b), uvec2(0x08080819, 0x192b2b08), uvec2(0x08081908, 0x192b2b08), - uvec2(0x08190808, 0x192b2b08), uvec2(0x192b1919, 0x192b2b08), uvec2(0x2b192b08, 0x192b2b08), uvec2(0x08080808, 0x192b2b19), - uvec2(0x082b2b2b, 0x192b2b19), uvec2(0x1908082b, 0x192b2b2b), uvec2(0x2b2b0819, 0x192b2b2b), uvec2(0x08080808, 0x2b080808), - uvec2(0x0808082b, 0x2b080808), uvec2(0x08081919, 0x2b080808), uvec2(0x08082b08, 0x2b080808), uvec2(0x08190819, 0x2b080808), - uvec2(0x08191908, 0x2b080808), uvec2(0x08192b19, 0x2b080808), uvec2(0x082b0808, 0x2b080808), uvec2(0x082b1919, 0x2b080808), - uvec2(0x19080819, 0x2b080808), uvec2(0x19081908, 0x2b080808), uvec2(0x19190808, 0x2b080808), uvec2(0x1919082b, 0x2b080808), - uvec2(0x19191919, 0x2b080808), uvec2(0x19192b08, 0x2b080808), uvec2(0x192b0819, 0x2b080808), uvec2(0x2b080808, 0x2b080808), - uvec2(0x2b081919, 0x2b080808), uvec2(0x2b190819, 0x2b080808), uvec2(0x2b191908, 0x2b080808), uvec2(0x08080819, 0x2b080819), - uvec2(0x08081908, 0x2b080819), uvec2(0x08082b19, 0x2b080819), uvec2(0x08190808, 0x2b080819), uvec2(0x0819082b, 0x2b080819), - uvec2(0x08191919, 0x2b080819), uvec2(0x08192b08, 0x2b080819), uvec2(0x082b0819, 0x2b080819), uvec2(0x082b1908, 0x2b080819), - uvec2(0x19080808, 0x2b080819), uvec2(0x1908082b, 0x2b080819), uvec2(0x19081919, 0x2b080819), uvec2(0x19082b08, 0x2b080819), - uvec2(0x19190819, 0x2b080819), uvec2(0x19191908, 0x2b080819), uvec2(0x2b080819, 0x2b080819), uvec2(0x2b081908, 0x2b080819), - uvec2(0x2b190808, 0x2b080819), uvec2(0x2b2b2b19, 0x2b080819), uvec2(0x08080808, 0x2b08082b), uvec2(0x08081919, 0x2b08082b), - uvec2(0x08082b2b, 0x2b08082b), uvec2(0x08190819, 0x2b08082b), uvec2(0x08191908, 0x2b08082b), uvec2(0x19080819, 0x2b08082b), - uvec2(0x19081908, 0x2b08082b), uvec2(0x19190808, 0x2b08082b), uvec2(0x08080819, 0x2b081908), uvec2(0x08081908, 0x2b081908), - uvec2(0x0808192b, 0x2b081908), uvec2(0x08082b19, 0x2b081908), uvec2(0x08190808, 0x2b081908), uvec2(0x0819082b, 0x2b081908), - uvec2(0x08191919, 0x2b081908), uvec2(0x08192b08, 0x2b081908), uvec2(0x082b0819, 0x2b081908), uvec2(0x19080808, 0x2b081908), - uvec2(0x1908082b, 0x2b081908), uvec2(0x19081919, 0x2b081908), uvec2(0x19082b08, 0x2b081908), uvec2(0x19190819, 0x2b081908), - uvec2(0x19191908, 0x2b081908), uvec2(0x192b0808, 0x2b081908), uvec2(0x2b080819, 0x2b081908), uvec2(0x2b081908, 0x2b081908), - uvec2(0x2b190808, 0x2b081908), uvec2(0x08080808, 0x2b081919), uvec2(0x0808082b, 0x2b081919), uvec2(0x08081919, 0x2b081919), - uvec2(0x08082b08, 0x2b081919), uvec2(0x08190819, 0x2b081919), uvec2(0x08191908, 0x2b081919), uvec2(0x082b0808, 0x2b081919), - uvec2(0x19080819, 0x2b081919), uvec2(0x19081908, 0x2b081919), uvec2(0x19190808, 0x2b081919), uvec2(0x2b080808, 0x2b081919), - uvec2(0x2b082b2b, 0x2b081919), uvec2(0x08080819, 0x2b08192b), uvec2(0x08081908, 0x2b08192b), uvec2(0x08190808, 0x2b08192b), - uvec2(0x082b2b19, 0x2b08192b), uvec2(0x19080808, 0x2b08192b), uvec2(0x08080808, 0x2b082b08), uvec2(0x08081919, 0x2b082b08), - uvec2(0x08190819, 0x2b082b08), uvec2(0x08191908, 0x2b082b08), uvec2(0x19080819, 0x2b082b08), uvec2(0x19081908, 0x2b082b08), - uvec2(0x19190808, 0x2b082b08), uvec2(0x2b2b082b, 0x2b082b08), uvec2(0x08080819, 0x2b082b19), uvec2(0x08081908, 0x2b082b19), - uvec2(0x19080808, 0x2b082b19), uvec2(0x192b1919, 0x2b082b19), uvec2(0x082b082b, 0x2b082b2b), uvec2(0x19192b08, 0x2b082b2b), - uvec2(0x19192b2b, 0x2b082b2b), uvec2(0x2b08082b, 0x2b082b2b), uvec2(0x2b2b082b, 0x2b082b2b), uvec2(0x08080819, 0x2b190808), - uvec2(0x08081908, 0x2b190808), uvec2(0x08082b19, 0x2b190808), uvec2(0x08190808, 0x2b190808), uvec2(0x0819082b, 0x2b190808), - uvec2(0x08191919, 0x2b190808), uvec2(0x08192b08, 0x2b190808), uvec2(0x082b1908, 0x2b190808), uvec2(0x19080808, 0x2b190808), - uvec2(0x1908082b, 0x2b190808), uvec2(0x19081919, 0x2b190808), uvec2(0x19082b08, 0x2b190808), uvec2(0x19190819, 0x2b190808), - uvec2(0x19191908, 0x2b190808), uvec2(0x192b0808, 0x2b190808), uvec2(0x2b080819, 0x2b190808), uvec2(0x2b081908, 0x2b190808), - uvec2(0x2b190808, 0x2b190808), uvec2(0x08080808, 0x2b190819), uvec2(0x08081919, 0x2b190819), uvec2(0x08190819, 0x2b190819), - uvec2(0x08191908, 0x2b190819), uvec2(0x19080819, 0x2b190819), uvec2(0x19081908, 0x2b190819), uvec2(0x19190808, 0x2b190819), - uvec2(0x19192b2b, 0x2b190819), uvec2(0x08080819, 0x2b19082b), uvec2(0x08081908, 0x2b19082b), uvec2(0x08190808, 0x2b19082b), - uvec2(0x19080808, 0x2b19082b), uvec2(0x2b2b192b, 0x2b19082b), uvec2(0x08080808, 0x2b191908), uvec2(0x0808082b, 0x2b191908), - uvec2(0x08081919, 0x2b191908), uvec2(0x08082b08, 0x2b191908), uvec2(0x08190819, 0x2b191908), uvec2(0x08191908, 0x2b191908), - uvec2(0x082b0808, 0x2b191908), uvec2(0x19080819, 0x2b191908), uvec2(0x19081908, 0x2b191908), uvec2(0x19190808, 0x2b191908), - uvec2(0x2b080808, 0x2b191908), uvec2(0x2b19192b, 0x2b191908), uvec2(0x08080819, 0x2b191919), uvec2(0x08081908, 0x2b191919), - uvec2(0x08190808, 0x2b191919), uvec2(0x19080808, 0x2b191919), uvec2(0x2b192b08, 0x2b191919), uvec2(0x2b2b0819, 0x2b191919), - uvec2(0x08080808, 0x2b19192b), uvec2(0x1908192b, 0x2b19192b), uvec2(0x192b1908, 0x2b19192b), uvec2(0x08080819, 0x2b192b08), - uvec2(0x08081908, 0x2b192b08), uvec2(0x08190808, 0x2b192b08), uvec2(0x082b192b, 0x2b192b08), uvec2(0x19080808, 0x2b192b08), - uvec2(0x2b2b2b19, 0x2b192b08), uvec2(0x08080808, 0x2b192b19), uvec2(0x19082b19, 0x2b192b19), uvec2(0x1919082b, 0x2b192b19), - uvec2(0x2b190808, 0x2b192b2b), uvec2(0x08080808, 0x2b2b0808), uvec2(0x08081919, 0x2b2b0808), uvec2(0x08082b2b, 0x2b2b0808), - uvec2(0x08191908, 0x2b2b0808), uvec2(0x082b082b, 0x2b2b0808), uvec2(0x082b2b2b, 0x2b2b0808), uvec2(0x19080819, 0x2b2b0808), - uvec2(0x19081908, 0x2b2b0808), uvec2(0x19190808, 0x2b2b0808), uvec2(0x2b2b082b, 0x2b2b0808), uvec2(0x2b2b2b2b, 0x2b2b0808), - uvec2(0x19080808, 0x2b2b0819), uvec2(0x192b1919, 0x2b2b0819), uvec2(0x0808082b, 0x2b2b082b), uvec2(0x08082b2b, 0x2b2b082b), - uvec2(0x082b082b, 0x2b2b082b), uvec2(0x082b2b08, 0x2b2b082b), uvec2(0x082b2b2b, 0x2b2b082b), uvec2(0x2b08082b, 0x2b2b082b), - uvec2(0x2b082b08, 0x2b2b082b), uvec2(0x2b082b2b, 0x2b2b082b), uvec2(0x2b2b2b08, 0x2b2b082b), uvec2(0x08080819, 0x2b2b1908), - uvec2(0x08081908, 0x2b2b1908), uvec2(0x08190808, 0x2b2b1908), uvec2(0x19080808, 0x2b2b1908), uvec2(0x2b082b19, 0x2b2b1908), - uvec2(0x2b2b1908, 0x2b2b1908), uvec2(0x08080808, 0x2b2b1919), uvec2(0x08192b19, 0x2b2b1919), uvec2(0x19190819, 0x2b2b192b), - uvec2(0x08082b2b, 0x2b2b2b08), uvec2(0x082b2b08, 0x2b2b2b08), uvec2(0x2b2b082b, 0x2b2b2b08), uvec2(0x19191908, 0x2b2b2b19), - uvec2(0x2b08192b, 0x2b2b2b19), uvec2(0x08082b08, 0x2b2b2b2b), uvec2(0x08082b2b, 0x2b2b2b2b), uvec2(0x082b0808, 0x2b2b2b2b), - uvec2(0x082b082b, 0x2b2b2b2b), uvec2(0x082b2b08, 0x2b2b2b2b), uvec2(0x2b082b08, 0x2b2b2b2b), uvec2(0x2b2b2b2b, 0x2b2b2b2b) -}; - #if defined(DATA_A_IQ2_S) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) { // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq2s_grid.length(); i += wgsize.x) { - if (iq2s_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2s_grid_const.length()) { - iq2s_grid[i + gl_LocalInvocationIndex.x] = iq2s_grid_const[i + gl_LocalInvocationIndex.x]; + if (iq2s_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq2s_grid.length()) { + iq2s_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ2S_GRID_OFFSET / 8 + i + gl_LocalInvocationIndex.x]; // bytes to uvec2 index } } barrier(); } -#endif -#if defined(DATA_A_IQ2_S) #define QUANT_K QUANT_K_IQ2_S #define QUANT_R QUANT_R_IQ2_S #define A_TYPE block_iq2_s #define A_TYPE_PACKED16 block_iq2_s_packed16 #endif -#endif #if defined(DATA_A_IQ3_XXS) || defined(DATA_A_IQ3_S) +layout (binding = IQ_GRID_BINDING) readonly buffer IQGrid { uint32_t iq_grid[]; }; + #if defined(DATA_A_IQ3_S) shared uint32_t iq3s_grid[512]; #else @@ -1611,43 +763,6 @@ struct block_iq3_xxs_packed16 uint16_t qs[QUANT_K_IQ3_XXS/8 + QUANT_K_IQ3_XXS/16]; }; -#if defined(DATA_A_IQ3_XXS) - -const uint32_t iq3xxs_grid_const[256] = { - 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, - 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, - 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, - 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, - 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, - 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, - 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, - 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, - 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, - 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, - 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, - 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, - 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, - 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, - 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, - 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, - 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, - 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, - 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, - 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, - 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, - 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, - 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, - 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, - 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, - 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, - 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, - 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, - 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, - 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, - 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, - 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, -}; - #if defined(DATA_A_IQ3_XXS) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) @@ -1655,20 +770,17 @@ void init_iq_shmem(uvec3 wgsize) // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq3xxs_grid.length(); i += wgsize.x) { if (iq3xxs_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq3xxs_grid.length()) { - iq3xxs_grid[i + gl_LocalInvocationIndex.x] = iq3xxs_grid_const[i + gl_LocalInvocationIndex.x]; + iq3xxs_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ3XXS_GRID_OFFSET / 4 + i + gl_LocalInvocationIndex.x]; // bytes to uint32 index } } barrier(); } -#endif -#if defined(DATA_A_IQ3_XXS) #define QUANT_K QUANT_K_IQ3_XXS #define QUANT_R QUANT_R_IQ3_XXS #define A_TYPE block_iq3_xxs #define A_TYPE_PACKED16 block_iq3_xxs_packed16 #endif -#endif #define QUANT_K_IQ3_S 256 #define QUANT_R_IQ3_S 1 @@ -1691,75 +803,6 @@ struct block_iq3_s_packed16 uint16_t scales[QUANT_K_IQ3_S/64/2]; }; -#if defined(DATA_A_IQ3_S) - -const uint32_t iq3s_grid_const[512] = { - 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, - 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, - 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, - 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, - 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, - 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, - 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, - 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, - 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, - 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, - 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, - 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, - 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, - 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, - 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, - 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, - 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, - 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, - 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, - 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, - 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, - 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, - 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, - 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, - 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, - 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, - 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, - 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, - 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, - 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, - 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, - 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, - 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, - 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, - 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, - 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, - 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, - 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, - 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, - 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, - 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, - 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, - 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, - 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, - 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, - 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, - 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, - 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, - 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, - 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, - 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, - 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, - 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, - 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, - 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, - 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, - 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, - 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, - 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, - 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, - 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, - 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, - 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, - 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, -}; - #if defined(DATA_A_IQ3_S) #define NEEDS_INIT_IQ_SHMEM void init_iq_shmem(uvec3 wgsize) @@ -1767,20 +810,17 @@ void init_iq_shmem(uvec3 wgsize) // copy the table into shared memory and sync [[unroll]] for (uint i = 0; i < iq3s_grid.length(); i += wgsize.x) { if (iq3s_grid.length() % wgsize.x == 0 || i + gl_LocalInvocationIndex.x < iq3s_grid.length()) { - iq3s_grid[i + gl_LocalInvocationIndex.x] = iq3s_grid_const[i + gl_LocalInvocationIndex.x]; + iq3s_grid[i + gl_LocalInvocationIndex.x] = iq_grid[IQ3S_GRID_OFFSET / 4 + i + gl_LocalInvocationIndex.x]; // bytes to uint32 index } } barrier(); } -#endif -#if defined(DATA_A_IQ3_S) #define QUANT_K QUANT_K_IQ3_S #define QUANT_R QUANT_R_IQ3_S #define A_TYPE block_iq3_s #define A_TYPE_PACKED16 block_iq3_s_packed16 #endif -#endif #define QUANT_K_IQ4_XS 256 #define QUANT_R_IQ4_XS 1 From 6d0716cff4966cb587c758b1c1baec13ee950fcd Mon Sep 17 00:00:00 2001 From: Pascal Date: Tue, 1 Dec 2026 15:43:55 +0100 Subject: [PATCH 315/401] gguf: document and test the NUL byte rule for keys and tensor names (#33443) State in the format description at the top of gguf.h that keys and tensor names must not contain null bytes while string values can. Add handcrafted test cases for both: a key with an embedded NUL placed before the key it would shadow, and tensor names that only differ after a NUL. Both files are now expected to be rejected. --- ggml/include/gguf.h | 1 + tests/test-gguf.cpp | 16 ++++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/ggml/include/gguf.h b/ggml/include/gguf.h index b3a1e1230a06..7423d3fcce66 100644 --- a/ggml/include/gguf.h +++ b/ggml/include/gguf.h @@ -24,6 +24,7 @@ // 7. The tensor data binary blob (optional, aligned). // // Strings are serialized as the string length (uint64_t) followed by the C string without the null terminator. +// Keys and tensor names must not contain null bytes, string values can. // All enums are stored as int32_t. // All bool values are stored as int8_t. // If the special key "general.alignment" (uint32_t) is defined it is used for alignment, diff --git a/tests/test-gguf.cpp b/tests/test-gguf.cpp index 6c63ecaeb4d7..f011710763bc 100644 --- a/tests/test-gguf.cpp +++ b/tests/test-gguf.cpp @@ -30,6 +30,7 @@ enum handcrafted_file_type { HANDCRAFTED_KV_BAD_TYPE = 20 + offset_has_kv, // HANDCRAFTED_KV_BAD_VALUE_SIZE = 30 + offset_has_kv, // removed because it can result in allocations > 1 TB (default sanitizer limit) HANDCRAFTED_KV_DUPLICATE_KEY = 40 + offset_has_kv, + HANDCRAFTED_KV_NUL_KEY = 45 + offset_has_kv, HANDCRAFTED_KV_BAD_ALIGN = 50 + offset_has_kv, HANDCRAFTED_KV_WRONG_TYPE_ALIGN = 55 + offset_has_kv, HANDCRAFTED_KV_SUCCESS = 800 + offset_has_kv, @@ -44,6 +45,7 @@ enum handcrafted_file_type { HANDCRAFTED_TENSORS_BAD_TYPE = 50 + offset_has_tensors, HANDCRAFTED_TENSORS_BAD_OFFSET = 60 + offset_has_tensors, HANDCRAFTED_TENSORS_DUPLICATE_NAME = 70 + offset_has_tensors, + HANDCRAFTED_TENSORS_NUL_NAME = 72 + offset_has_tensors, HANDCRAFTED_TENSORS_BAD_ALIGN = 75 + offset_has_tensors, HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN = 80 + offset_has_tensors, HANDCRAFTED_TENSORS_SUCCESS = 800 + offset_has_tensors, @@ -71,6 +73,7 @@ static std::string handcrafted_file_type_name(const enum handcrafted_file_type h case HANDCRAFTED_KV_EMPTY_KEY: return "KV_EMPTY_KEY"; case HANDCRAFTED_KV_BAD_TYPE: return "KV_BAD_TYPE"; case HANDCRAFTED_KV_DUPLICATE_KEY: return "KV_DUPLICATE_KEY"; + case HANDCRAFTED_KV_NUL_KEY: return "KV_NUL_KEY"; case HANDCRAFTED_KV_BAD_ALIGN: return "KV_BAD_ALIGN"; case HANDCRAFTED_KV_WRONG_TYPE_ALIGN: return "KV_WRONG_TYPE_ALIGN"; case HANDCRAFTED_KV_SUCCESS: return "KV_RANDOM_KV"; @@ -85,6 +88,7 @@ static std::string handcrafted_file_type_name(const enum handcrafted_file_type h case HANDCRAFTED_TENSORS_BAD_TYPE: return "TENSORS_BAD_TYPE"; case HANDCRAFTED_TENSORS_BAD_OFFSET: return "TENSORS_BAD_OFFSET"; case HANDCRAFTED_TENSORS_DUPLICATE_NAME: return "TENSORS_DUPLICATE_NAME"; + case HANDCRAFTED_TENSORS_NUL_NAME: return "TENSORS_NUL_NAME"; case HANDCRAFTED_TENSORS_BAD_ALIGN: return "TENSORS_BAD_ALIGN"; case HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN: return "TENSORS_INCONSISTENT_ALIGN"; case HANDCRAFTED_TENSORS_SUCCESS: return "TENSORS_SUCCESS"; @@ -302,9 +306,12 @@ static FILE * get_handcrafted_file(const unsigned int seed, const enum handcraft const enum gguf_type type = gguf_type(hft == HANDCRAFTED_KV_BAD_TYPE ? GGUF_TYPE_COUNT : kv_types[i].first); const enum gguf_type type_arr = gguf_type(hft == HANDCRAFTED_KV_BAD_TYPE ? GGUF_TYPE_COUNT : kv_types[i].second); - const std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY + std::string key = hft == HANDCRAFTED_KV_EMPTY_KEY ? "" - : "my_key_" + std::to_string((hft == HANDCRAFTED_KV_DUPLICATE_KEY ? i/2 : i)); + : "my_key_" + std::to_string((hft == HANDCRAFTED_KV_DUPLICATE_KEY || hft == HANDCRAFTED_KV_NUL_KEY ? i/2 : i)); + if (hft == HANDCRAFTED_KV_NUL_KEY && i % 2 == 0) { + key += std::string("\0x", 2); + } if (hft == HANDCRAFTED_KV_BAD_KEY_SIZE) { const uint64_t n = -1; @@ -401,6 +408,9 @@ static FILE * get_handcrafted_file(const unsigned int seed, const enum handcraft const std::array shape = tensor_configs[i].second; std::string name = "my_tensor"; + if (hft == HANDCRAFTED_TENSORS_NUL_NAME) { + name += '\0'; + } if (hft != HANDCRAFTED_TENSORS_DUPLICATE_NAME) { name += "_" + std::to_string(i); } @@ -773,6 +783,7 @@ static std::pair test_handcrafted_file(const unsigned int seed) { HANDCRAFTED_KV_EMPTY_KEY, HANDCRAFTED_KV_BAD_TYPE, HANDCRAFTED_KV_DUPLICATE_KEY, + HANDCRAFTED_KV_NUL_KEY, HANDCRAFTED_KV_BAD_ALIGN, HANDCRAFTED_KV_WRONG_TYPE_ALIGN, HANDCRAFTED_KV_SUCCESS, @@ -787,6 +798,7 @@ static std::pair test_handcrafted_file(const unsigned int seed) { HANDCRAFTED_TENSORS_BAD_TYPE, HANDCRAFTED_TENSORS_BAD_OFFSET, HANDCRAFTED_TENSORS_DUPLICATE_NAME, + HANDCRAFTED_TENSORS_NUL_NAME, HANDCRAFTED_TENSORS_BAD_ALIGN, HANDCRAFTED_TENSORS_INCONSISTENT_ALIGN, HANDCRAFTED_TENSORS_SUCCESS, From 30b900181be8193ff2e5267a28e9259eba5d1b0c Mon Sep 17 00:00:00 2001 From: ErsongWang <158176536+ErsongWang@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:47:26 +0800 Subject: [PATCH 316/401] CUDA/HIP: Use the MMA FA kernel for maskless attention on RDNA (#32930) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * CUDA/HIP: Use the MMA FA kernel for maskless attention on RDNA Vision encoders commonly use non-causal, maskless attention. On RDNA GPUs, the MMA kernel runs faster than the tile kernel for this workload. However, the current AMD MMA path is only selected for GQA-optimized attention. Enable the wide MMA kernel (`ncols1 = 64`, `ncols2 = 1`) for maskless attention when `n_queries >= 128` on all AMD GPUs that support WMMA. Assisted-by: GitHub Copilot * Remove extra tests Co-authored-by: Johannes Gäßler * CUDA: fix ALiBi slope in RDNA3 mma FA kernel Assisted-by: GitHub Copilot --------- Co-authored-by: uvos Co-authored-by: Johannes Gäßler --- ggml/src/ggml-cuda/fattn-mma-f16.cuh | 4 ++-- ggml/src/ggml-cuda/fattn.cu | 6 ++++++ tests/test-backend-ops.cpp | 2 ++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-cuda/fattn-mma-f16.cuh b/ggml/src/ggml-cuda/fattn-mma-f16.cuh index 8c0e9328c2a6..2cc338195ff1 100644 --- a/ggml/src/ggml-cuda/fattn-mma-f16.cuh +++ b/ggml/src/ggml-cuda/fattn-mma-f16.cuh @@ -754,7 +754,7 @@ static __device__ __forceinline__ void flash_attn_ext_f16_iter( const int i = i0 + T_C_KQ::get_j(l); const int j = ((threadIdx.y / np)*cols_per_warp + T_C_KQ::get_i(l)) / ncols2; - KQ_C[i00/(np*T_C_KQ::J)].x[l] += __half2float(tile_mask[j*(nbatch_fa + 8) + i]); + KQ_C[i00/(np*T_C_KQ::J)].x[l] += slope*__half2float(tile_mask[j*(nbatch_fa + 8) + i]); } #else #pragma unroll @@ -1913,7 +1913,7 @@ static __global__ void flash_attn_ext_f16( #endif // __CUDA_ARCH__ == GGML_CUDA_CC_TURING #if defined(AMD_WMMA_AVAILABLE) - if (ncols1*ncols2 < 16 || ncols2 == 1 || DKQ > 256) { + if (ncols1*ncols2 < 16 || DKQ > 256) { NO_DEVICE_CODE; return; } diff --git a/ggml/src/ggml-cuda/fattn.cu b/ggml/src/ggml-cuda/fattn.cu index 3f2fb0193447..f19ed620357a 100644 --- a/ggml/src/ggml-cuda/fattn.cu +++ b/ggml/src/ggml-cuda/fattn.cu @@ -860,6 +860,12 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const return BEST_FATTN_KERNEL_MMA_F16; } + // Mask-less attention with many queries (e.g. vision encoders) cannot use the GQA tiles above. + // The WMMA kernel is still much faster than the tile kernel for this case: + if (amd_wmma_available(cc) && !mask && Q->ne[0] <= 256 && Q->ne[1] >= 128) { + return BEST_FATTN_KERNEL_MMA_F16; + } + // If there are no tensor cores available, use the generic tile kernel: if (can_use_vector_kernel) { if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) { diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 5136668ff58c..648cf98d4d33 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -16067,6 +16067,8 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_flash_attn_ext(72, 72, 16, {1, 1}, 5776, 5776, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); // Same non-causal vision-encoder shape for the other head size padded in-kernel by the CUDA MMA kernels test_cases.emplace_back(new test_flash_attn_ext(40, 40, 16, {1, 1}, 5776, 5776, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); + // Same for the Qwen2.5-VL head size + test_cases.emplace_back(new test_flash_attn_ext(80, 80, 16, {1, 1}, 4096, 4096, false, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16)); // GCN sparse attention break-even for multiple query tokens. for (int64_t kv : {16384, 32768, 65536}) { From 06fa894b15f744d952df69357d4d2591cddac0d3 Mon Sep 17 00:00:00 2001 From: Niklas Wenzel Date: Tue, 1 Dec 2026 15:48:04 +0100 Subject: [PATCH 317/401] metal : detect Neural Accelerators without hardcoding chips (#33272) So that applications built with today's version of llama.cpp will properly use the tensor API on chips released in the future without requiring a llama.cpp update. --- ggml/src/ggml-metal/ggml-metal-device.m | 49 ++++++++++++++++--------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index e87187a12437..50e8fd938282 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -28,6 +28,9 @@ static const NSInteger MTLGPUFamilyMetal3_GGML = 5001; static const NSInteger MTLGPUFamilyMetal4_GGML = 5002; +// overload of MTLGPUFamilyAppleX (not available in some environments) +static const NSInteger MTLGPUFamilyApple10_GGML = 1010; + // MTLLanguageVersion4_0 is not present in older SDKs static const NSUInteger MTLLanguageVersion4_0_GGML = 4 << 16; @@ -1109,6 +1112,33 @@ static enum ggml_metal_device_id ggml_metal_device_id_parse(const char * name) { return "GGML_METAL_DEVICE_GENERIC"; } +static bool ggml_metal_has_tensor(id device) { + if (![device supportsFamily:MTLGPUFamilyMetal4_GGML]) { + return false; + } + + if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) { + return false; + } + + if (getenv("GGML_METAL_TENSOR_ENABLE") != NULL) { + return true; + } + + // enable the tensor API by default for M5+ and A19+ + // disable it for older chips because with the current implementation it is not useful + // - M2 Ultra: ~5% slower + // - M4, M4 Max: no significant difference + // + // TODO: try to update the tensor API kernels to at least match the simdgroup performance + if ([device supportsFamily:MTLGPUFamilyApple10_GGML]) { + return true; + } + + GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__); + return false; +} + ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) { ggml_metal_device_t dev = calloc(1, sizeof(struct ggml_metal_device)); @@ -1145,24 +1175,7 @@ ggml_metal_device_t ggml_metal_device_init(int device, int n_devices) { dev->props.has_bfloat = false; } - dev->props.has_tensor = [dev->mtl_device supportsFamily:MTLGPUFamilyMetal4_GGML]; - if (getenv("GGML_METAL_TENSOR_DISABLE") != NULL) { - dev->props.has_tensor = false; - } - - // note: disable the tensor API by default for old chips because with the current implementation it is not useful - // - M2 Ultra: ~5% slower - // - M4, M4 Max: no significant difference - // - // TODO: try to update the tensor API kernels to at least match the simdgroup performance - if (getenv("GGML_METAL_TENSOR_ENABLE") == NULL && - ![[dev->mtl_device name] containsString:@"M5"] && - ![[dev->mtl_device name] containsString:@"M6"] && - ![[dev->mtl_device name] containsString:@"A19"] && - ![[dev->mtl_device name] containsString:@"A20"]) { - GGML_LOG_INFO("%s: tensor API disabled for pre-M5 and pre-A19 devices\n", __func__); - dev->props.has_tensor = false; - } + dev->props.has_tensor = ggml_metal_has_tensor(dev->mtl_device); // double-check that the tensor API compiles if (dev->props.has_tensor) { From 94524527648367390024e2b48d29cd7b1dd417db Mon Sep 17 00:00:00 2001 From: Marin Radic Date: Tue, 1 Dec 2026 16:24:37 +0100 Subject: [PATCH 318/401] ggml-et : fix multi-line L2 flush and replace L2-SCP polling with FCC 0 (#33313) FlushVA encodes numlines - 1 in 4 bits (max 16 lines), so the 32-line Q4_0 panel flush in mul_mat_Q4_0_matrix_engine silently dropped lines 16..31. Add flush_to_l2_multi() in platform.h to chunk flushes by 16. L2-SCP also persists across kernel launches, so ready_ctr/consumed_ctr polling in mul_mat_Q4_0_matrix_engine and mul_mat_f16_matrix_engine raced at entry and could corrupt results or deadlock. Replace the L2-SCP counters with FCC 0 semaphores (et_sem_post/et_sem_wait) plus hart 1 exit credit drain (matching flash_attn_ext_f16_me.c), which avoids FLB 0 aliasing with uberkernel barriers and improves Q4_0 4096x512x14336 throughput from 632.9 to 668.1 GFLOPS (+5.6%). Assisted-by: Antigravity --- .../src/mul_mat_Q4_0_matrix_engine.c | 59 +++++------------ .../src/mul_mat_f16_matrix_engine.c | 63 +++++-------------- ggml/src/ggml-et/et-kernels/src/platform.h | 17 +++++ 3 files changed, 51 insertions(+), 88 deletions(-) diff --git a/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c b/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c index 28a10303235a..762760c7284b 100644 --- a/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c +++ b/ggml/src/ggml-et/et-kernels/src/mul_mat_Q4_0_matrix_engine.c @@ -25,32 +25,11 @@ #define A_L1_START 0 // L1 SCP lines 0..15 for A (activations) #define B_L1_START 16 // L1 SCP lines 16..31 for B (dequantized weights) -// L2 SCP layout per minion (double-buffered dequant panel + sync counters). +// L2 SCP layout per minion (double-buffered dequant panel). // panel = BLOCK_K k-lines x TILE_M m (FP32) = 32 * 64 = 2048 bytes, in TenB // [k][m] order: panel[k*TILE_M + m]. -#define SCP_PANEL_SIZE (BLOCK_K * TILE_M * (uint64_t) sizeof(float)) // 2048 -#define SCP_READY_OFF (2 * SCP_PANEL_SIZE) // 4096 -#define SCP_CONSUMED_OFF (SCP_READY_OFF + 64) // 4160 -#define SCP_PER_MINION (SCP_CONSUMED_OFF + 64) // 4224 - -// Signal a counter value to the other hart via L2 SCP. -static inline void __attribute__((always_inline)) scp_signal(volatile uint32_t * flag, uint32_t value) { - *flag = value; - FENCE; - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; -} - -// Wait for a counter in L2 SCP to reach the expected value. -static inline void __attribute__((always_inline)) scp_wait(volatile uint32_t * flag, uint32_t expected) { - while (1) { - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; - if (*flag >= expected) { - return; - } - } -} +#define SCP_PANEL_SIZE (BLOCK_K * TILE_M * (uint64_t) sizeof(float)) // 2048 +#define SCP_PER_MINION (2 * SCP_PANEL_SIZE) // 4096 // Dequantize one 32-element Q4_0 block of TILE_M weight rows into the FP32 // panel, written directly in TenB [k][m] order: panel[k*TILE_M + m]. @@ -192,22 +171,17 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { const int64_t kb_start = k_split * k_steps_per_split; // first block const int64_t kb_end = kb_start + k_steps_per_split; // one past last - // L2 SCP pointers for this minion's double-buffered panels + sync. + // L2 SCP pointers for this minion's double-buffered panels. uint64_t scp_base = local_minion * SCP_PER_MINION; float * scp_panel[2] = { (float *) et_shire_l2scp_local(scp_base), (float *) et_shire_l2scp_local(scp_base + SCP_PANEL_SIZE), }; - volatile uint32_t * ready_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_READY_OFF); - volatile uint32_t * consumed_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_CONSUMED_OFF); // ================================================================ // Hart 1: Q4_0 weight dequant producer // ================================================================ if (is_hart1) { - scp_signal(ready_ctr, 0); - scp_signal(consumed_ctr, 0); - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -229,22 +203,28 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { for (int64_t kb = kb_start; kb < kb_end; ++kb) { int buf = chunk_id & 1; - // Back-pressure: wait for hart 0 to finish with this buffer. + // Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers). if (chunk_id >= 2) { - scp_wait(consumed_ctr, chunk_id - 1); + et_sem_wait(ET_BARRIER_MINION); } dequant_q4_0_panel(scp_panel[buf], src0_batch, mb, kb, nb1_0); FENCE; - flush_to_l2(scp_panel[buf], BLOCK_K, 64); + flush_to_l2_multi(scp_panel[buf], BLOCK_K, 64); WAIT_CACHEOPS; + et_sem_post(ET_BARRIER_MINION); chunk_id++; - scp_signal(ready_ctr, chunk_id); } } + // Drain the up to 2 unconsumed FCC 0 credits from the wait-skip on chunks 0 and 1. + uint32_t drain = (chunk_id < 2) ? chunk_id : 2; + for (uint32_t d = 0; d < drain; ++d) { + et_sem_wait(ET_BARRIER_MINION); + } + FENCE; return 0; } @@ -261,11 +241,6 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { #endif CLEAR_TENSOR_ERROR; - evict_to_l2((const void *) ready_ctr, 1, 64); - WAIT_CACHEOPS; - evict_to_l2((const void *) consumed_ctr, 1, 64); - WAIT_CACHEOPS; - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -307,8 +282,7 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { int buf = chunk_id & 1; // Wait for hart 1 to finish dequantizing this block. - chunk_id++; - scp_wait(ready_ctr, chunk_id); + et_sem_wait(ET_BARRIER_MINION); // Two FMA passes over the 32-wide block (16 K-cols each). for (int half = 0; half < 2; ++half) { @@ -337,7 +311,8 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { } // Signal that this buffer is free for hart 1 to reuse. - scp_signal(consumed_ctr, chunk_id); + et_sem_post(ET_BARRIER_MINION); + chunk_id++; } // K-split ring reduce. diff --git a/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c b/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c index 2aab87ad5e52..25e6a27f9985 100644 --- a/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c +++ b/ggml/src/ggml-et/et-kernels/src/mul_mat_f16_matrix_engine.c @@ -10,7 +10,7 @@ // Hart 0: tensor engine (load A, load B from SCP, FMA, reduce, store) // Hart 1: pack B into double-buffered L2 SCP panels, flush for tensor_load // -// Sync: monotonic counters in L2 SCP with evict-based coherency. +// Sync: FCC 0 semaphores (et_sem_post / et_sem_wait). // Double-buffered bpanel allows pack/FMA overlap. // #define NUM_COMPUTE_SHIRES 32 @@ -28,34 +28,11 @@ typedef uint16_t et_fp16_t; -// L2 SCP layout per minion (double-buffered bpanel + sync counters) +// L2 SCP layout per minion (double-buffered bpanel) // [0..1023] bpanel buffer 0 (16 lines x 64 bytes) // [1024..2047] bpanel buffer 1 -// [2048..2111] ready counter (hart1 -> hart0, own cache line) -// [2112..2175] consumed counter (hart0 -> hart1, own cache line) -#define SCP_BPANEL_SIZE (16 * 32 * sizeof(et_fp16_t)) // 1024 bytes -#define SCP_READY_OFF (2 * SCP_BPANEL_SIZE) // 2048 -#define SCP_CONSUMED_OFF (SCP_READY_OFF + 64) // 2112 -#define SCP_PER_MINION (SCP_CONSUMED_OFF + 64) // 2176 - -// Signal a counter value to the other hart via L2 SCP. -static inline void __attribute__((always_inline)) scp_signal(volatile uint32_t * flag, uint32_t value) { - *flag = value; - FENCE; - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; -} - -// Wait for a counter in L2 SCP to reach the expected value. -static inline void __attribute__((always_inline)) scp_wait(volatile uint32_t * flag, uint32_t expected) { - while (1) { - evict_to_l2((const void *) flag, 1, 64); - WAIT_CACHEOPS; - if (*flag >= expected) { - return; - } - } -} +#define SCP_BPANEL_SIZE (16 * 32 * sizeof(et_fp16_t)) // 1024 bytes +#define SCP_PER_MINION (2 * SCP_BPANEL_SIZE) // 2048 bytes /** * Build the interleaved B panel that TensorFMA16A32 expects (vectorized). @@ -170,23 +147,17 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { const int64_t k_start = k_split * k_steps_per_split * TILE_K; const int64_t k_end = k_start + k_steps_per_split * TILE_K; - // L2 SCP pointers for this minion's double-buffered panels + sync + // L2 SCP pointers for this minion's double-buffered panels uint64_t scp_base = local_minion * SCP_PER_MINION; et_fp16_t * scp_bp[2] = { (et_fp16_t *) et_shire_l2scp_local(scp_base), (et_fp16_t *) et_shire_l2scp_local(scp_base + SCP_BPANEL_SIZE), }; - volatile uint32_t * ready_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_READY_OFF); - volatile uint32_t * consumed_ctr = (volatile uint32_t *) et_shire_l2scp_local(scp_base + SCP_CONSUMED_OFF); // ================================================================ // Hart 1: B-panel packer // ================================================================ if (is_hart1) { - // Initialize sync counters - scp_signal(ready_ctr, 0); - scp_signal(consumed_ctr, 0); - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -208,9 +179,9 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { for (int64_t kb = k_start; kb < k_end; kb += TILE_K) { int buf = chunk_id & 1; - // Back-pressure: wait for hart 0 to finish with this buffer + // Back-pressure via FCC 0 (avoids FLB 0 aliasing with uberkernel barriers). if (chunk_id >= 2) { - scp_wait(consumed_ctr, chunk_id - 1); + et_sem_wait(ET_BARRIER_MINION); } pack_b_interleaved(scp_bp[buf], src0_batch, mb, kb, nb1_0); @@ -219,11 +190,17 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { flush_to_l2(scp_bp[buf], 16, 64); WAIT_CACHEOPS; + et_sem_post(ET_BARRIER_MINION); chunk_id++; - scp_signal(ready_ctr, chunk_id); } } + // Drain the up to 2 unconsumed FCC 0 credits from the wait-skip on chunks 0 and 1. + uint32_t drain = (chunk_id < 2) ? chunk_id : 2; + for (uint32_t d = 0; d < drain; ++d) { + et_sem_wait(ET_BARRIER_MINION); + } + FENCE; return 0; } @@ -240,12 +217,6 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { #endif CLEAR_TENSOR_ERROR; - // Evict any stale L1D copies of sync counters - evict_to_l2((const void *) ready_ctr, 1, 64); - WAIT_CACHEOPS; - evict_to_l2((const void *) consumed_ctr, 1, 64); - WAIT_CACHEOPS; - uint32_t chunk_id = 0; for (int64_t tile = (int64_t) shire_id + local_tile_idx * NUM_COMPUTE_SHIRES; tile < base_tiles; @@ -282,8 +253,7 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { (uint64_t) nb1_1, 0); // Wait for hart 1 to finish packing this chunk - chunk_id++; - scp_wait(ready_ctr, chunk_id); + et_sem_wait(ET_BARRIER_MINION); // Load B from L2 SCP (hart 1 already flushed it) tensor_load(false, false, B_L1_START, TENSOR_LOAD_PLAIN, 0, (uint64_t) scp_bp[buf], 0, 15, 64, 1); @@ -298,7 +268,8 @@ int entry_point(struct ggml_et_binary_params * params, void * env) { tensor_wait(TENSOR_FMA_WAIT); // Signal that this buffer is free for hart 1 to reuse - scp_signal(consumed_ctr, chunk_id); + et_sem_post(ET_BARRIER_MINION); + chunk_id++; } // K-split ring reduce diff --git a/ggml/src/ggml-et/et-kernels/src/platform.h b/ggml/src/ggml-et/et-kernels/src/platform.h index cbec4c98d741..2ea9592a394c 100644 --- a/ggml/src/ggml-et/et-kernels/src/platform.h +++ b/ggml/src/ggml-et/et-kernels/src/platform.h @@ -476,6 +476,23 @@ static inline void __attribute__((always_inline)) flush_to_l2(const void * addr, : "x31", "memory"); } +// Flush any number of cache lines to L2 in 16-line chunks (FlushVA hardware cap). +static inline void __attribute__((always_inline)) flush_to_l2_multi(const void * addr, + uint64_t nlines, + uint64_t stride) { + const char * p = (const char *) addr; + const uint64_t step = stride & 0xFFFFFFFFFFC0ULL; + + while (nlines > 16) { + flush_to_l2(p, 16, step); + p += 16 * step; + nlines -= 16; + } + if (nlines > 0) { + flush_to_l2(p, nlines, step); + } +} + // Evict nlines cache lines at stride apart starting at addr from L1 to L2. // Uses EvictVA (CSR 0x89F). Unlike flush_to_l2, this guarantees the line is // NOT present in L1 after the operation - subsequent loads will miss and go From 562f4b85b24784965ca2c391b2ddfd2996889121 Mon Sep 17 00:00:00 2001 From: lhez Date: Tue, 1 Dec 2026 09:14:33 -0800 Subject: [PATCH 319/401] opencl: add log and non-contig scale (#33237) * opencl: refactor scale Assisted-by: Codex * opencl: add log Assisted-by: Codex * docs: update OpenCL operation support --- docs/ops.md | 2 +- docs/ops/OpenCL.csv | 25 +++-- ggml/src/ggml-opencl/ggml-opencl.cpp | 116 ++++++++++++++-------- ggml/src/ggml-opencl/kernels/scale.cl | 114 +++++++++++++++++---- ggml/src/ggml-opencl/kernels/unary_ext.cl | 1 + 5 files changed, 191 insertions(+), 67 deletions(-) diff --git a/docs/ops.md b/docs/ops.md index 6c838cad34b6..33da412ae068 100644 --- a/docs/ops.md +++ b/docs/ops.md @@ -69,7 +69,7 @@ Legend: | L2_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ | | LEAKY_RELU | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | LIGHTNING_INDEXER | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ | -| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | +| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | MEAN | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ | | MUL | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ | | MUL_MAT | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | diff --git a/docs/ops/OpenCL.csv b/docs/ops/OpenCL.csv index bee117961fc8..23d3da3e8f33 100644 --- a/docs/ops/OpenCL.csv +++ b/docs/ops/OpenCL.csv @@ -8979,10 +8979,14 @@ "OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=0","support","0","no","OpenCL" "OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=0","support","0","no","OpenCL" "OpenCL","SCALE","type=bf16,ne=[100,10,10,10],scale=0.500000,bias=0.000000,inplace=0,v=0","support","0","no","OpenCL" -"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=0.000000,inplace=0,v=1","support","0","no","OpenCL" -"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","0","no","OpenCL" -"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","0","no","OpenCL" +"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=0","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=0","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f16,ne=[100,10,10,10],scale=0.500000,bias=0.000000,inplace=0,v=0","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=0.000000,inplace=0,v=1","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","1","yes","OpenCL" +"OpenCL","SCALE","type=f32,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","1","yes","OpenCL" "OpenCL","SCALE","type=bf16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=1,v=1","support","0","no","OpenCL" +"OpenCL","SCALE","type=f16,ne=[10,10,10,10],scale=2.000000,bias=1.000000,inplace=0,v=1","support","1","yes","OpenCL" "OpenCL","SILU_BACK","type=f32,ne=[64,5,4,3],eps=0.000001","support","0","no","OpenCL" "OpenCL","NORM","type=f32,ne=[64,5,4,3],v=0,eps=0.000000,noncontig_rows=0","support","1","yes","OpenCL" "OpenCL","RMS_NORM","type=f32,ne=[64,5,4,3],v=0,eps=0.000000,inplace=0","support","1","yes","OpenCL" @@ -14821,7 +14825,7 @@ "OpenCL","ADD_ID","type_a=f32,type_b=f32,n_embd=129,n_experts=8,n_experts_used=4,n_token=129,skip=1","support","1","yes","OpenCL" "OpenCL","SQR","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f16,ne=[10,3,3,2]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f16,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=f16,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SIN","type=f16,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","COS","type=f16,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","CLAMP","type=f16,ne=[10,5,4,3],min=-0.500000,max=0.500000,v=0","support","0","no","OpenCL" @@ -14835,8 +14839,8 @@ "OpenCL","SQR","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f16,ne=[7,1,5,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL" -"OpenCL","LOG","type=f16,ne=[1024,1024,1,1]","support","0","no","OpenCL" +"OpenCL","LOG","type=f16,ne=[7,1,5,3]","support","1","yes","OpenCL" +"OpenCL","LOG","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SIN","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL" "OpenCL","SIN","type=f16,ne=[1024,1024,1,1]","support","0","no","OpenCL" "OpenCL","COS","type=f16,ne=[7,1,5,3]","support","0","no","OpenCL" @@ -14855,7 +14859,7 @@ "OpenCL","TRUNC","type=f16,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SQR","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f32,ne=[10,3,3,2]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f32,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=f32,ne=[10,5,4,3]","support","1","yes","OpenCL" "OpenCL","SIN","type=f32,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","COS","type=f32,ne=[10,2,2,2]","support","0","no","OpenCL" "OpenCL","CLAMP","type=f32,ne=[10,5,4,3],min=-0.500000,max=0.500000,v=0","support","1","yes","OpenCL" @@ -14869,8 +14873,11 @@ "OpenCL","SQR","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f32,ne=[7,1,5,3]","support","1","yes","OpenCL" "OpenCL","SQRT","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" -"OpenCL","LOG","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL" -"OpenCL","LOG","type=f32,ne=[1024,1024,1,1]","support","0","no","OpenCL" +"OpenCL","LOG","type=f32,ne=[7,1,5,3]","support","1","yes","OpenCL" +"OpenCL","LOG","type=f32,ne=[1024,1024,1,1]","support","1","yes","OpenCL" +"OpenCL","LOG","type=bf16,ne=[10,5,4,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=bf16,ne=[7,1,5,3]","support","0","no","OpenCL" +"OpenCL","LOG","type=bf16,ne=[1024,1024,1,1]","support","0","no","OpenCL" "OpenCL","SIN","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL" "OpenCL","SIN","type=f32,ne=[1024,1024,1,1]","support","0","no","OpenCL" "OpenCL","COS","type=f32,ne=[7,1,5,3]","support","0","no","OpenCL" diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 26e65e5b811e..635dcc0114d6 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -870,7 +870,8 @@ struct ggml_backend_opencl_context { cl_kernel kernel_sub, kernel_sub_row, kernel_sub_f16, kernel_sub_row_f16; cl_kernel kernel_add_id; cl_kernel kernel_add_id_add_id_swiglu_oai; - cl_kernel kernel_scale_f32, kernel_scale_f32_4; + cl_kernel kernel_scale_f32, kernel_scale_f32_4, kernel_scale_f32_nc; + cl_kernel kernel_scale_f16, kernel_scale_f16_4, kernel_scale_f16_nc; cl_kernel kernel_sqr_cont_f32, kernel_sqr_cont_f32_4, kernel_sqr_cont_f16, kernel_sqr_cont_f16_4; cl_kernel kernel_sqrt_cont_f32, kernel_sqrt_cont_f32_4, kernel_sqrt_cont_f16, kernel_sqrt_cont_f16_4; cl_kernel kernel_mean_f32, kernel_mean_f32_4; @@ -1172,6 +1173,7 @@ struct ggml_backend_opencl_context { cl_kernel kernel_ceil_f32, kernel_ceil_f32_4, kernel_ceil_f32_nc, kernel_ceil_f16, kernel_ceil_f16_4, kernel_ceil_f16_nc; cl_kernel kernel_round_f32, kernel_round_f32_4, kernel_round_f32_nc, kernel_round_f16, kernel_round_f16_4, kernel_round_f16_nc; cl_kernel kernel_trunc_f32, kernel_trunc_f32_4, kernel_trunc_f32_nc, kernel_trunc_f16, kernel_trunc_f16_4, kernel_trunc_f16_nc; + cl_kernel kernel_log_f32, kernel_log_f32_4, kernel_log_f32_nc, kernel_log_f16, kernel_log_f16_4, kernel_log_f16_nc; cl_kernel kernel_softplus_f32, kernel_softplus_f32_4, kernel_softplus_f32_nc; cl_kernel kernel_softplus_f16, kernel_softplus_f16_4, kernel_softplus_f16_nc; cl_kernel kernel_upscale; @@ -4693,8 +4695,12 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f32_nc = clCreateKernel(prog, "kernel_scale_f32_nc", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f16 = clCreateKernel(prog, "kernel_scale_f16", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f16_4 = clCreateKernel(prog, "kernel_scale_f16_4", &err), err)); + CL_CHECK((backend_ctx->kernel_scale_f16_nc = clCreateKernel(prog, "kernel_scale_f16_nc", &err), err)); CL_CHECK(clReleaseProgram(prog)); GGML_LOG_CONT("."); } @@ -5192,6 +5198,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { CL_UNARY_EXT_K(ceil) CL_UNARY_EXT_K(round) CL_UNARY_EXT_K(trunc) + CL_UNARY_EXT_K(log) #undef CL_UNARY_EXT_K CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err)); CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err)); @@ -12829,7 +12836,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te op->type == op->src[1]->type; } case GGML_OP_SCALE: - return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); + return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && + op->src[0]->type == op->type && ggml_is_contiguous_rows(op->src[0]); case GGML_OP_ADD: if (op->type == GGML_TYPE_F16) { const bool src0_ok = op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32; @@ -12846,6 +12854,8 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); case GGML_OP_ADD_ID: return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_LOG: + return op->src[0]->type == op->type && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); case GGML_OP_SQR: case GGML_OP_SQRT: return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && @@ -21893,6 +21903,7 @@ GGML_CL_UNARY_EXT_WRAP(ggml_cl_floor, floor) GGML_CL_UNARY_EXT_WRAP(ggml_cl_ceil, ceil) GGML_CL_UNARY_EXT_WRAP(ggml_cl_round, round) GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_log, log) #undef GGML_CL_UNARY_EXT_WRAP @@ -39863,54 +39874,75 @@ static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0 } static void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); + GGML_ASSERT(src0 && src0->extra); + GGML_ASSERT(dst && dst->extra); GGML_UNUSED(src1); - GGML_ASSERT(ggml_is_contiguous(src0)); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; + const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; - float scale; - float bias; - memcpy(&scale, ((int32_t *) dst->op_params) + 0, sizeof(float)); - memcpy(&bias, ((int32_t *) dst->op_params) + 1, sizeof(float)); + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + const float scale = ggml_get_op_params_f32(dst, 0); + const float bias = ggml_get_op_params_f32(dst, 1); + const bool is_f16 = src0->type == GGML_TYPE_F16; - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_kernel kernel; - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; + if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) { + size_t n = ggml_nelements(dst); + const size_t alignment = 4 * ggml_element_size(src0); + if (n % 4 == 0 && offset0 % alignment == 0 && offsetd % alignment == 0) { + kernel = is_f16 ? backend_ctx->kernel_scale_f16_4 : backend_ctx->kernel_scale_f32_4; + n /= 4; + } else { + kernel = is_f16 ? backend_ctx->kernel_scale_f16 : backend_ctx->kernel_scale_f32; + } - cl_kernel kernel; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); - int n = ggml_nelements(dst); + size_t global_work_size[] = {n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + size_t * local_work_size_ptr = local_work_size; + if (n % local_work_size[0] != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } - if (n % 4 == 0) { - kernel = backend_ctx->kernel_scale_f32_4; - n /= 4; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); } else { - kernel = backend_ctx->kernel_scale_f32; - } + kernel = is_f16 ? backend_ctx->kernel_scale_f16_nc : backend_ctx->kernel_scale_f32_nc; + const cl_ulong ne00 = src0->ne[0]; + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb3)); - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; + const size_t nth = 64; + size_t global_work_size[] = {(size_t)src0->ne[1] * nth, (size_t)src0->ne[2], (size_t)src0->ne[3]}; + size_t local_work_size[] = {nth, 1, 1}; - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); } static void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { @@ -41859,6 +41891,12 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor } func = ggml_cl_sub; break; + case GGML_OP_LOG: + if (!any_on_device) { + return false; + } + func = ggml_cl_log; + break; case GGML_OP_SQR: if (!any_on_device) { return false; diff --git a/ggml/src/ggml-opencl/kernels/scale.cl b/ggml/src/ggml-opencl/kernels/scale.cl index 17ed97f0d660..e01a2a81566a 100644 --- a/ggml/src/ggml-opencl/kernels/scale.cl +++ b/ggml/src/ggml-opencl/kernels/scale.cl @@ -1,27 +1,105 @@ #pragma OPENCL EXTENSION cl_khr_fp16 : enable kernel void kernel_scale_f32( - global float * src0, - ulong offset0, - global float * dst, - ulong offsetd, - float scale, - float bias + global const float * src0, + ulong offset0, + global float * dst, + ulong offsetd, + float scale, + float bias ) { - src0 = (global float*)((global char*)src0 + offset0); - dst = (global float*)((global char*)dst + offsetd); - dst[get_global_id(0)] = src0[get_global_id(0)] * scale + bias; + src0 = (global const float *)((global const char *)src0 + offset0); + dst = (global float *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = src0[i] * scale + bias; } kernel void kernel_scale_f32_4( - global float4 * src0, - ulong offset0, - global float4 * dst, - ulong offsetd, - float scale, - float bias + global const float4 * src0, + ulong offset0, + global float4 * dst, + ulong offsetd, + float scale, + float bias ) { - src0 = (global float4*)((global char*)src0 + offset0); - dst = (global float4*)((global char*)dst + offsetd); - dst[get_global_id(0)] = src0[get_global_id(0)] * scale + bias; + src0 = (global const float4 *)((global const char *)src0 + offset0); + dst = (global float4 *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = src0[i] * scale + bias; +} + +kernel void kernel_scale_f16( + global const half * src0, + ulong offset0, + global half * dst, + ulong offsetd, + float scale, + float bias +) { + src0 = (global const half *)((global const char *)src0 + offset0); + dst = (global half *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = convert_half(convert_float(src0[i]) * scale + bias); +} + +kernel void kernel_scale_f16_4( + global const half4 * src0, + ulong offset0, + global half4 * dst, + ulong offsetd, + float scale, + float bias +) { + src0 = (global const half4 *)((global const char *)src0 + offset0); + dst = (global half4 *)((global char *)dst + offsetd); + const size_t i = get_global_id(0); + dst[i] = convert_half4(convert_float4(src0[i]) * scale + bias); +} + +kernel void kernel_scale_f32_nc( + global const char * src0, + ulong offset0, + global char * dst, + ulong offsetd, + float scale, + float bias, + ulong ne00, + ulong nb00, ulong nb01, ulong nb02, ulong nb03, + ulong nb0, ulong nb1, ulong nb2, ulong nb3 +) { + const size_t i1 = get_group_id(0); + const size_t i2 = get_group_id(1); + const size_t i3 = get_group_id(2); + src0 += offset0 + i1*nb01 + i2*nb02 + i3*nb03; + dst += offsetd + i1*nb1 + i2*nb2 + i3*nb3; + + for (size_t i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) { + global const float * x = (global const float *)(src0 + i0*nb00); + global float * y = (global float *)(dst + i0*nb0); + *y = *x * scale + bias; + } +} + +kernel void kernel_scale_f16_nc( + global const char * src0, + ulong offset0, + global char * dst, + ulong offsetd, + float scale, + float bias, + ulong ne00, + ulong nb00, ulong nb01, ulong nb02, ulong nb03, + ulong nb0, ulong nb1, ulong nb2, ulong nb3 +) { + const size_t i1 = get_group_id(0); + const size_t i2 = get_group_id(1); + const size_t i3 = get_group_id(2); + src0 += offset0 + i1*nb01 + i2*nb02 + i3*nb03; + dst += offsetd + i1*nb1 + i2*nb2 + i3*nb3; + + for (size_t i0 = get_local_id(0); i0 < ne00; i0 += get_local_size(0)) { + global const half * x = (global const half *)(src0 + i0*nb00); + global half * y = (global half *)(dst + i0*nb0); + *y = convert_half(convert_float(*x) * scale + bias); + } } diff --git a/ggml/src/ggml-opencl/kernels/unary_ext.cl b/ggml/src/ggml-opencl/kernels/unary_ext.cl index e58cc0153ff1..c5dcfec257bd 100644 --- a/ggml/src/ggml-opencl/kernels/unary_ext.cl +++ b/ggml/src/ggml-opencl/kernels/unary_ext.cl @@ -74,6 +74,7 @@ kernel void kernel_##NAME##_f16_nc( \ } \ } +UNARY_EXT(log, log(x), log(x)) UNARY_EXT(sgn, sign(x), sign(x)) UNARY_EXT(step, x > 0.0f ? 1.0f : 0.0f, select((float4)0.0f, (float4)1.0f, x > 0.0f)) UNARY_EXT(elu, x > 0.0f ? x : expm1(x), select(expm1(x), x, x > 0.0f)) From cda9b4113cd4caa58b206e9f3f0478092686890e Mon Sep 17 00:00:00 2001 From: Pascal Date: Tue, 1 Dec 2026 18:21:04 +0100 Subject: [PATCH 320/401] metal : add apertus to the Metal fusion baseline (#33453) --- tests/fusion/MTL.csv | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/fusion/MTL.csv b/tests/fusion/MTL.csv index d33dee2a4b92..4796cc805e25 100644 --- a/tests/fusion/MTL.csv +++ b/tests/fusion/MTL.csv @@ -4,6 +4,7 @@ afmoe ,1 ,any ,MUL+ADD , 2 afmoe ,1 ,any ,RMS_NORM+MUL , 10 afmoe ,1 ,any ,RMS_NORM+MUL+ADD , 3 afmoe ,1 ,any ,UNARY+ADD+ARGSORT+GET_ROWS , 1 +apertus ,0 ,any ,RMS_NORM+MUL , 9 arcee ,0 ,any ,RMS_NORM+MUL , 5 arctic ,1 ,any ,MUL+ADD , 4 arctic ,1 ,any ,RMS_NORM+MUL , 7 From e5cd6e34ba1070a3e39c49d2388d7f188ef4fe35 Mon Sep 17 00:00:00 2001 From: Pascal Date: Tue, 1 Dec 2026 18:38:28 +0100 Subject: [PATCH 321/401] Vulkan: one thread per row for soft_max and sum_rows on short rows (#33197) * vulkan : one thread per row for soft_max and sum_rows on short rows A row of at most 8 columns got a whole workgroup with a shared memory reduction. Each invocation now handles a whole row, with fastdiv for the row indices, and sum_rows covers mean through its weight. On 3.4M rows of 4 on an RTX PRO 6000, soft_max goes from 1653 to 42 us and sum_rows from 1662 to 10 us. Hy4 flash decode goes from 53 to 60 t/s at 4k context and from 9.6 to 54.8 t/s at 16k. * vulkan : initialize soft_max fastdiv push constants * vulkan : use vec4 loads in the short row soft_max and sum_rows Rows of 4 or 8 floats were read and written one element at a time, so each load of a subgroup hit addresses 16 or 32 bytes apart. When the row length is a multiple of 4 and the strides are aligned, move whole vec4 instead, and keep the scalar loop otherwise. On a RTX PRO 6000 with 3.44M rows of 4 floats, soft_max goes from 42 to 19 us and sum_rows/mean from 10.3 to 9.5 us. * tests : remove the temporary short row cases * vulkan : revert the vec4 loads in the short row soft_max and sum_rows The vec4 path halves the soft_max kernel time on rows of 4 floats, but Hy4 flash decode is unchanged on a RTX PRO 6000 and sum_rows gets slower with 8 floats per row, so keep the simpler scalar loop. --- .../ggml-vulkan/ggml-vulkan-push-constants.h | 7 ++ ggml/src/ggml-vulkan/ggml-vulkan-types.h | 2 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 15 ++- .../vulkan-shaders/soft_max_short.comp | 94 +++++++++++++++++++ .../vulkan-shaders/sum_rows_short.comp | 35 +++++++ .../vulkan-shaders/vulkan-shaders-gen.cpp | 3 + 6 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp create mode 100644 ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h index bd01b766fa93..72e7b26a4ae2 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h @@ -614,8 +614,15 @@ struct vk_op_soft_max_push_constants { uint32_t n_head_log2; uint32_t nrows_x; uint32_t has_sinks; + uint32_t ne0_1mp, ne0_1L; + uint32_t ne0_12mp, ne0_12L; }; +template <> inline void init_pushconst_fastdiv(vk_op_soft_max_push_constants &p) { + init_fastdiv_values(p.ne01*p.ne02, p.ne0_12mp, p.ne0_12L); + init_fastdiv_values(p.ne01, p.ne0_1mp, p.ne0_1L); +} + struct vk_op_argsort_push_constants { uint32_t ncols; uint32_t ncols_padded; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 47383d50afe3..ea22c613527f 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -978,6 +978,7 @@ struct vk_device_struct { vk_pipeline pipeline_silu_back_f32; vk_pipeline pipeline_soft_max_f32, pipeline_soft_max_f32_f16; + vk_pipeline pipeline_soft_max_short_f32, pipeline_soft_max_short_f32_f16; vk_pipeline pipeline_soft_max_f32_wg512, pipeline_soft_max_f32_f16_wg512; vk_pipeline pipeline_soft_max_back_f32; @@ -995,6 +996,7 @@ struct vk_device_struct { vk_pipeline pipeline_topk_radix_f32; vk_pipeline pipeline_topk_radix_qsa; // qwen4 QSA indexer fusion (f16 mask) vk_pipeline pipeline_sum_rows_f32; + vk_pipeline pipeline_sum_rows_short_f32; vk_pipeline pipeline_cross_entropy_loss_f32, pipeline_cross_entropy_loss_f32_wg512; vk_pipeline pipeline_cross_entropy_loss_back_f32, pipeline_cross_entropy_loss_back_f32_wg512; vk_pipeline pipeline_fwht_f32[num_fwht_pipelines]; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 1cdb392c4c63..0ce67f21dd25 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4108,6 +4108,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_wg512, "soft_max_f32_wg512", soft_max_f32_len, soft_max_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16, "soft_max_f32_f16", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_f32_f16_wg512, "soft_max_f32_f16_wg512", soft_max_f32_f16_len, soft_max_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 512 }, 1); + ggml_vk_create_pipeline(device, device->pipeline_soft_max_short_f32, "soft_max_short_f32", soft_max_short_f32_len, soft_max_short_f32_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {256, 1, 1}, { 256 }, 1); + ggml_vk_create_pipeline(device, device->pipeline_soft_max_short_f32_f16, "soft_max_short_f32_f16", soft_max_short_f32_f16_len, soft_max_short_f32_f16_data, "main", 4, sizeof(vk_op_soft_max_push_constants), {256, 1, 1}, { 256 }, 1); ggml_vk_create_pipeline(device, device->pipeline_soft_max_back_f32, "soft_max_back_f32", soft_max_back_f32_len, soft_max_back_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true); ggml_vk_create_pipeline(device, device->pipeline_soft_max_large1_f32, "soft_max_large1_f32", soft_max_large1_f32_len, soft_max_large1_f32_data, "main", 6, sizeof(vk_op_soft_max_push_constants), {1, 1, 1}, { 128, 4 }, 1, true); @@ -4179,6 +4181,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_argmax_f32, "argmax_f32", argmax_f32_len, argmax_f32_data, "main", 2, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); ggml_vk_create_pipeline(device, device->pipeline_sum_rows_f32, "sum_rows_f32", sum_rows_f32_len, sum_rows_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {1, 1, 1}, { device->subgroup_size }, 1, true); + ggml_vk_create_pipeline(device, device->pipeline_sum_rows_short_f32, "sum_rows_short_f32", sum_rows_short_f32_len, sum_rows_short_f32_data, "main", 2, sizeof(vk_op_sum_rows_push_constants), {256, 1, 1}, { 256 }, 1, true); ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32, "cross_entropy_loss_f32", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_f32_wg512, "cross_entropy_loss_f32_wg512", cross_entropy_loss_f32_len, cross_entropy_loss_f32_data, "main", 3, sizeof(vk_op_push_constants), {1, 1, 1}, { 512 }, 1); ggml_vk_create_pipeline(device, device->pipeline_cross_entropy_loss_back_f32, "cross_entropy_loss_back_f32", cross_entropy_loss_back_f32_len, cross_entropy_loss_back_f32_data, "main", 4, sizeof(vk_op_push_constants), {1, 1, 1}, { device->subgroup_size }, 1); @@ -10620,9 +10623,15 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const } if (src0->type == GGML_TYPE_F32 && (src1 == nullptr || src1->type == GGML_TYPE_F32) && dst->type == GGML_TYPE_F32) { + if (src0->ne[0] <= 8) { + return ctx->device->pipeline_soft_max_short_f32; + } return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_wg512 : ctx->device->pipeline_soft_max_f32; } if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F32) { + if (src0->ne[0] <= 8) { + return ctx->device->pipeline_soft_max_short_f32_f16; + } return src0->ne[0] > 1024 ? ctx->device->pipeline_soft_max_f32_f16_wg512 : ctx->device->pipeline_soft_max_f32_f16; } return nullptr; @@ -10684,6 +10693,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const case GGML_OP_SUM_ROWS: case GGML_OP_MEAN: if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + if (op != GGML_OP_SUM && src0->ne[0] <= 8) { + return ctx->device->pipeline_sum_rows_short_f32; + } return ctx->device->pipeline_sum_rows_f32; } return nullptr; @@ -12945,7 +12957,8 @@ void ggml_vk_soft_max(ggml_backend_vk_context * ctx, vk_context& subctx, const g m0, m1, n_head_log2, nrows_x, - src2 != nullptr + src2 != nullptr, + 0, 0, 0, 0, }; if (ncols <= 16384) { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp b/ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp new file mode 100644 index 000000000000..c11dcc21b20d --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/soft_max_short.comp @@ -0,0 +1,94 @@ +#version 450 + +#extension GL_EXT_control_flow_attributes : enable + +layout (push_constant) uniform parameter +{ + uint KX; + uint KY; + uint ne00; + uint ne01; + uint ne02; + uint ne12; + uint ne13; + uint nb11; + uint nb12; + uint nb13; + float scale; + float max_bias; + float m0; + float m1; + uint n_head_log2; + uint nrows_x; + uint has_sinks; + uint ne0_1mp, ne0_1L; + uint ne0_12mp, ne0_12L; +} p; + +#include "types.glsl" +#include "utils.glsl" + +layout(constant_id = 0) const uint BLOCK_SIZE = 256; +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) readonly buffer Z {float data_c[];}; +layout (binding = 3) buffer D {D_TYPE data_d[];}; + +const uint MAX_COLS = 8; + +void main() { + const uint rowx = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x; + + if (rowx >= p.nrows_x) { + return; + } + + const uint i03 = fastdiv(rowx, p.ne0_12mp, p.ne0_12L); + const uint i012 = rowx - i03 * p.ne01 * p.ne02; + const uint i02 = fastdiv(i012, p.ne0_1mp, p.ne0_1L); + const uint i01 = i012 - i02 * p.ne01; + + uint rowy_start = 0; + if (p.KY > 0) { + rowy_start = i01 * p.nb11 + fastmod(i02, p.ne12) * p.nb12 + fastmod(i03, p.ne13) * p.nb13; + } + + float slope = 1.0f; + + if (p.max_bias > 0.0f) { + const float base = i02 < p.n_head_log2 ? p.m0 : p.m1; + const uint exp = i02 < p.n_head_log2 ? i02 + 1 : 2*(i02 - p.n_head_log2) + 1; + + slope = pow(base, exp); + } + + FLOAT_TYPE vals[MAX_COLS]; + FLOAT_TYPE max_val = p.has_sinks == 0 ? uintBitsToFloat(0xFF800000) : data_c[i02]; + + [[unroll]] for (uint col = 0; col < MAX_COLS; ++col) { + if (col < p.KX) { + const FLOAT_TYPE b = p.KY > 0 ? FLOAT_TYPE(data_b[rowy_start + col]) : FLOAT_TYPE(0.0f); + vals[col] = FLOAT_TYPE(data_a[rowx * p.KX + col]) * p.scale + slope * b; + max_val = max(max_val, vals[col]); + } + } + + FLOAT_TYPE sum = p.has_sinks == 0 ? FLOAT_TYPE(0.0f) : FLOAT_TYPE(exp(FLOAT_TYPE(data_c[i02]) - max_val)); + + [[unroll]] for (uint col = 0; col < MAX_COLS; ++col) { + if (col < p.KX) { + vals[col] = exp(vals[col] - max_val); + sum += vals[col]; + } + } + + const FLOAT_TYPE rcpdivisor = 1.0/sum; + + [[unroll]] for (uint col = 0; col < MAX_COLS; ++col) { + if (col < p.KX) { + data_d[rowx * p.KX + col] = D_TYPE(vals[col] * rcpdivisor); + } + } +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp b/ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp new file mode 100644 index 000000000000..a0bc50ed48f4 --- /dev/null +++ b/ggml/src/ggml-vulkan/vulkan-shaders/sum_rows_short.comp @@ -0,0 +1,35 @@ +#version 450 + +#include "types.glsl" +#include "sum_rows.glsl" + +#extension GL_EXT_control_flow_attributes : 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 = 256; + +void main() { + const uint row = gl_GlobalInvocationID.z * 262144 + gl_GlobalInvocationID.y * 512 + gl_GlobalInvocationID.x; + + if (row >= p.ne01 * p.ne02 * p.ne03) { return; } + + 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; + + FLOAT_TYPE sum = FLOAT_TYPE(0.0); + + for (uint i = 0; i < p.n_cols; ++i) { + sum += FLOAT_TYPE(data_a[src_idx + i]); + } + + data_d[dst_idx] = D_TYPE(sum * p.weight); +} diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index 8e15600974c8..dc0c61e73534 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -1059,6 +1059,8 @@ void process_shaders() { string_to_spv("soft_max_f32", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_f32_f16", "soft_max.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}})); + string_to_spv("soft_max_short_f32", "soft_max_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); + string_to_spv("soft_max_short_f32_f16", "soft_max_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float16_t"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_back_f32", "soft_max_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("soft_max_large1_f32", "soft_max_large1.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); @@ -1093,6 +1095,7 @@ void process_shaders() { string_to_spv("argmax_f32", "argmax.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "int"}})); string_to_spv("sum_rows_f32", "sum_rows.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); + string_to_spv("sum_rows_short_f32", "sum_rows_short.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("cross_entropy_loss_f32", "cross_entropy_loss.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("cross_entropy_loss_back_f32", "cross_entropy_loss_back.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"B_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("fwht_f32", "fwht.comp", {{"A_TYPE", "float"}}); From b9073e5483713f370755b3180d94c1f22c1ba740 Mon Sep 17 00:00:00 2001 From: Matheus Britto <55333133+matheusbrittod3v@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:40:02 -0300 Subject: [PATCH 322/401] jinja : support Unicode whitespace and multi-byte chars in strip/trim (#33461) * jinja : support Unicode whitespace and multi-byte chars in strip/trim Assisted-by: Antigravity * jinja : clarify Unicode strip comments and use args.func_name Assisted-by: Antigravity --------- Co-authored-by: matheusbrito --- common/jinja/string.cpp | 117 ++++++++++++++++++++++++++++------------ common/jinja/value.cpp | 47 ++++++++-------- tests/test-jinja.cpp | 23 ++++++++ 3 files changed, 128 insertions(+), 59 deletions(-) diff --git a/common/jinja/string.cpp b/common/jinja/string.cpp index 22189fa6f47c..ec661184faad 100644 --- a/common/jinja/string.cpp +++ b/common/jinja/string.cpp @@ -1,5 +1,6 @@ #include "jinja/string.h" #include "jinja/value.h" +#include "unicode.h" #include #include @@ -205,53 +206,103 @@ string string::titlecase() { return res; }); } -string string::strip(bool left, bool right, std::optional chars) { - static auto strip_part = [](const std::string & s, bool left, bool right, std::optional chars) -> std::string { - size_t start = 0; - size_t end = s.length(); - auto match_char = [&chars](unsigned char c) -> bool { - return chars ? (*chars).find(c) != std::string::npos : isspace(c); - }; - if (left) { - while (start < end && match_char(static_cast(s[start]))) { - ++start; - } - } - if (right) { - while (end > start && match_char(static_cast(s[end - 1]))) { - --end; - } +// mirrors Python str.isspace() (CPython Py_UNICODE_ISSPACE) +static bool is_unicode_whitespace(uint32_t cp) { + return (cp >= 0x0009 && cp <= 0x000D) || + (cp >= 0x001C && cp <= 0x0020) || + cp == 0x0085 || + cp == 0x00A0 || + cp == 0x1680 || + (cp >= 0x2000 && cp <= 0x200A) || + cp == 0x2028 || + cp == 0x2029 || + cp == 0x202F || + cp == 0x205F || + cp == 0x3000; +} + +static std::vector decode_utf8_cpts(std::string_view s) { + std::vector cpts; + size_t pos = 0; + while (pos < s.size()) { + auto parsed = common_parse_utf8_codepoint(s, pos); + if (parsed.status == utf8_parse_result::SUCCESS) { + cpts.push_back(parsed.codepoint); + pos += parsed.bytes_consumed; + } else { + // skip invalid UTF-8 bytes so they never match non-strippable raw bytes in the input + pos += 1; } - return s.substr(start, end - start); - }; + } + return cpts; +} + +string string::strip(bool left, bool right, std::optional chars) { if (parts.empty()) { return *this; } + + std::vector char_cpts; + if (chars) { + char_cpts = decode_utf8_cpts(*chars); + } + + auto match_cp = [&](uint32_t cp) -> bool { + if (chars) { + return std::find(char_cpts.begin(), char_cpts.end(), cp) != char_cpts.end(); + } + return is_unicode_whitespace(cp); + }; + + const std::string full = str(); + size_t start = 0; + size_t end = full.size(); + if (left) { - for (size_t i = 0; i < parts.size(); ++i) { - parts[i].val = strip_part(parts[i].val, true, false, chars); - if (parts[i].val.empty()) { - // remove empty part - parts.erase(parts.begin() + i); - --i; - continue; - } else { + while (start < end) { + auto parsed = common_parse_utf8_codepoint(full, start); + if (parsed.status != utf8_parse_result::SUCCESS || !match_cp(parsed.codepoint)) { break; } + start += parsed.bytes_consumed; } } + if (right) { - for (size_t i = parts.size(); i-- > 0;) { - parts[i].val = strip_part(parts[i].val, false, true, chars); - if (parts[i].val.empty()) { - // remove empty part - parts.erase(parts.begin() + i); - continue; + size_t new_end = start; + size_t pos = start; + while (pos < end) { + auto parsed = common_parse_utf8_codepoint(full, pos); + if (parsed.status != utf8_parse_result::SUCCESS) { + pos += 1; + new_end = pos; } else { - break; + pos += parsed.bytes_consumed; + if (!match_cp(parsed.codepoint)) { + new_end = pos; + } } } + end = new_end; + } + + std::vector new_parts; + size_t offset = 0; + for (const auto & part : parts) { + const size_t part_start = offset; + const size_t part_end = offset + part.val.size(); + offset = part_end; + + const size_t keep_start = std::max(part_start, start); + const size_t keep_end = std::min(part_end, end); + if (keep_start < keep_end) { + new_parts.push_back({ + part.is_input, + part.val.substr(keep_start - part_start, keep_end - keep_start) + }); + } } + parts = std::move(new_parts); return *this; } diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp index 79d79b2dbe51..04e78c16ac1f 100644 --- a/common/jinja/value.cpp +++ b/common/jinja/value.cpp @@ -739,6 +739,24 @@ static bool string_endswith(const std::string & str, const std::string & suffix) throw not_implemented_exception("String join builtin not implemented"); } +static value string_strip_impl(const func_args & args, bool left, bool right) { + args.ensure_kwargs({"chars"}); + args.ensure_count(1, 2); + const std::string & name = args.func_name; + value val_input = args.get_pos(0); + if (!is_val(val_input)) { + throw raised_exception(name + "() first argument must be a string"); + } + value val_chars = args.get_kwarg_or_pos("chars", 1); + if (val_chars->is_undefined() || is_val(val_chars)) { + return mk_val(val_input->as_string().strip(left, right)); + } + if (!is_val(val_chars)) { + throw raised_exception(name + "() argument must be None or str"); + } + return mk_val(val_input->as_string().strip(left, right, val_chars->as_string().str())); +} + const func_builtins & value_string_t::get_builtins() const { static const func_builtins builtins = { {"default", default_value}, @@ -757,36 +775,13 @@ const func_builtins & value_string_t::get_builtins() const { return mk_val(str); }}, {"strip", [](const func_args & args) -> value { - args.ensure_kwargs({"chars"}); - args.ensure_count(1, 2); - value val_input = args.get_pos(0); - if (!is_val(val_input)) { - throw raised_exception("strip() first argument must be a string"); - } - value val_chars = args.get_kwarg_or_pos("chars", 1); - if (val_chars->is_undefined()) { - return mk_val(args.get_pos(0)->as_string().strip(true, true)); - } else { - return mk_val(args.get_pos(0)->as_string().strip(true, true, val_chars->as_string().str())); - } + return string_strip_impl(args, true, true); }}, {"rstrip", [](const func_args & args) -> value { - args.ensure_vals(); - value val_chars = args.get_kwarg_or_pos("chars", 1); - if (val_chars->is_undefined()) { - return mk_val(args.get_pos(0)->as_string().strip(false, true)); - } else { - return mk_val(args.get_pos(0)->as_string().strip(false, true, val_chars->as_string().str())); - } + return string_strip_impl(args, false, true); }}, {"lstrip", [](const func_args & args) -> value { - args.ensure_vals(); - value val_chars = args.get_kwarg_or_pos("chars", 1); - if (val_chars->is_undefined()) { - return mk_val(args.get_pos(0)->as_string().strip(true, false)); - } else { - return mk_val(args.get_pos(0)->as_string().strip(true, false, val_chars->as_string().str())); - } + return string_strip_impl(args, true, false); }}, {"title", [](const func_args & args) -> value { args.ensure_kwargs(); diff --git a/tests/test-jinja.cpp b/tests/test-jinja.cpp index b72b00b12b0d..331745a185f9 100644 --- a/tests/test-jinja.cpp +++ b/tests/test-jinja.cpp @@ -1018,6 +1018,29 @@ static void test_filters(testing & t) { ); } + test_template(t, "trim and strip unicode whitespace", + "[{{ s|trim }}]|[{{ s.strip() }}]|[{{ s.lstrip() }}]|[{{ s.rstrip() }}]", + {{"s", "\u3000\u00a0hello\u2003\u202f"}}, + "[hello]|[hello]|[hello\u2003\u202f]|[\u3000\u00a0hello]" + ); + + test_template(t, "trim and strip multibyte custom chars", + "[{{ t|trim(c) }}]|[{{ t.strip(c) }}]|[{{ u|trim(c) }}]", + {{"t", "\u3001hi\u3002"}, {"u", "\u3000\u3001hi\u3000"}, {"c", "\u3000"}}, + "[\u3001hi\u3002]|[\u3001hi\u3002]|[\u3001hi]" + ); + + test_template(t, "trim and strip with none", + "[{{ s|trim(none) }}]|[{{ s|trim(chars=none) }}]|[{{ s.strip(none) }}]|[{{ s.lstrip(none) }}]|[{{ s.rstrip(none) }}]", + {{"s", "\u3000hello\u00a0"}}, + "[hello]|[hello]|[hello]|[hello\u00a0]|[\u3000hello]" + ); + + test_template_error(t, "strip rejects non-string non-none chars", + "{{ 'hello'.strip(123) }}", + "strip() argument must be None or str" + ); + test_template(t, "length string", "{{ 'hello'|length }}", json::object(), From 509468d5aa49609466d9e05e660d8c98c6d07b12 Mon Sep 17 00:00:00 2001 From: Animesh Date: Wed, 2 Dec 2026 01:55:42 +0530 Subject: [PATCH 323/401] ggml-cuda : optimize mmvq nwarps for Pascal DP4A (#25479) --- ggml/src/ggml-cuda/mmvq.cu | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-cuda/mmvq.cu b/ggml/src/ggml-cuda/mmvq.cu index fad806d76682..5a4a6108bf15 100644 --- a/ggml/src/ggml-cuda/mmvq.cu +++ b/ggml/src/ggml-cuda/mmvq.cu @@ -91,6 +91,7 @@ static constexpr __host__ __device__ int get_vdr_mmvq(ggml_type type) { enum mmvq_parameter_table_id { MMVQ_PARAMETERS_GENERIC = 0, + MMVQ_PARAMETERS_PASCAL_DP4A, MMVQ_PARAMETERS_TURING, MMVQ_PARAMETERS_GCN, MMVQ_PARAMETERS_RDNA1, @@ -118,6 +119,8 @@ static constexpr __device__ mmvq_parameter_table_id get_device_table_id() { return MMVQ_PARAMETERS_GB10; #elif __CUDA_ARCH__ == GGML_CUDA_CC_ORIN return MMVQ_PARAMETERS_ORIN; +#elif defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= GGML_CUDA_CC_DP4A && __CUDA_ARCH__ < GGML_CUDA_CC_VOLTA + return MMVQ_PARAMETERS_PASCAL_DP4A; #else return MMVQ_PARAMETERS_GENERIC; #endif @@ -148,6 +151,9 @@ static __host__ mmvq_parameter_table_id get_device_table_id(int cc) { if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) == GGML_CUDA_CC_ORIN) { return MMVQ_PARAMETERS_ORIN; } + if (GGML_CUDA_CC_IS_NVIDIA(cc) && ggml_cuda_highest_compiled_arch(cc) >= GGML_CUDA_CC_DP4A && ggml_cuda_highest_compiled_arch(cc) < GGML_CUDA_CC_VOLTA) { + return MMVQ_PARAMETERS_PASCAL_DP4A; + } return MMVQ_PARAMETERS_GENERIC; } @@ -478,7 +484,11 @@ static constexpr __device__ int get_mmvq_mmid_max_batch_for_device() { } static constexpr __host__ __device__ int calc_nwarps(ggml_type type, int ncols_dst, mmvq_parameter_table_id table_id, bool small_k = false, bool halve_iters = false) { - if (table_id == MMVQ_PARAMETERS_GENERIC) { + if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A) { + // Pascal cc 6.1/6.2 decode is bandwidth-bound on small SMs: 2 warps beat 4 for single-token. + if (table_id == MMVQ_PARAMETERS_PASCAL_DP4A && ncols_dst == 1) { + return 2; + } switch (ncols_dst) { case 1: case 2: @@ -641,7 +651,7 @@ static constexpr __host__ __device__ bool mmvq_two_rows_ncols1(ggml_type type) { } static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int ncols_dst, int table_id, bool small_k = false, int nwarps = 1) { - if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) { + if (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A || table_id == MMVQ_PARAMETERS_GCN || table_id == MMVQ_PARAMETERS_TURING || table_id == MMVQ_PARAMETERS_GB10 || table_id == MMVQ_PARAMETERS_RDNA1) { switch (ncols_dst) { case 1: if (small_k) { @@ -650,7 +660,7 @@ static constexpr __host__ __device__ int calc_rows_per_block(ggml_type type, int if (table_id == MMVQ_PARAMETERS_GB10) { return type == GGML_TYPE_IQ2_S || type == GGML_TYPE_IQ3_S ? 2 : 1; } - return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1; + return (table_id == MMVQ_PARAMETERS_GENERIC || table_id == MMVQ_PARAMETERS_PASCAL_DP4A || table_id == MMVQ_PARAMETERS_RDNA1) && mmvq_two_rows_ncols1(type) ? 2 : 1; case 2: case 3: case 4: From 92f76e5c564e0510e1e0a9574dc82209d509491b Mon Sep 17 00:00:00 2001 From: Ehsan Bateni Date: Tue, 1 Dec 2026 15:28:58 -0500 Subject: [PATCH 324/401] hexagon: optimize IQ2_XSS grid gathers (#33407) Co-authored-by: Max Krasnyansky --- ggml/src/ggml-hexagon/htp/htp-tensor.h | 11 +++++++++-- ggml/src/ggml-hexagon/htp/iq2xxs-tables.h | 2 +- ggml/src/ggml-hexagon/htp/matmul-internal.h | 9 ++++++--- ggml/src/ggml-hexagon/htp/matmul-ops.c | 22 ++++++++++++++++++++- 4 files changed, 37 insertions(+), 7 deletions(-) diff --git a/ggml/src/ggml-hexagon/htp/htp-tensor.h b/ggml/src/ggml-hexagon/htp/htp-tensor.h index 9d2de3081c92..b02bd963a49f 100644 --- a/ggml/src/ggml-hexagon/htp/htp-tensor.h +++ b/ggml/src/ggml-hexagon/htp/htp-tensor.h @@ -22,11 +22,18 @@ #define HTP_TENSOR_TILE_SIZE_IQ4_NL 576 #define HTP_TENSOR_TILE_SIZE_MXFP4 544 #define HTP_TENSOR_TILE_SIZE_NVFP4 576 -#define HTP_TENSOR_TILE_SIZE_IQ2_XXS 264 +#define HTP_TENSOR_TILE_SIZE_IQ2_XXS 264 #define HTP_TENSOR_TILE_SCRATCH_IQ2_XXS 256 #define HTP_IQ2XXS_NIBBLE_BYTES 128 // 16 words for vlut16, padded to a vector #define HTP_IQ2XXS_GRID_BYTES 512 // 256 entries x 8 elements x 2-bit magnitude code -#define HTP_IQ2XXS_LUT_BYTES (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_GRID_BYTES) +#define HTP_IQ2XXS_TABLE_BYTES (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_GRID_BYTES) +#define HTP_IQ2XXS_LANE_OFF_BYTES 128 // per-lane copy offsets for grid gathers, one vector +#define HTP_IQ2XXS_GRID_COPIES 16 // gather lane h reads copy (h % 16) to spread bank conflicts +#define HTP_IQ2XXS_GRID_SKEW 4 // bank skew between copies +#define HTP_IQ2XXS_GRID_STRIDE (HTP_IQ2XXS_GRID_BYTES + HTP_IQ2XXS_GRID_SKEW) +#define HTP_IQ2XXS_GRID_REGION (HTP_IQ2XXS_GRID_COPIES * HTP_IQ2XXS_GRID_STRIDE) +#define HTP_IQ2XXS_GRID_OFF (HTP_IQ2XXS_NIBBLE_BYTES + HTP_IQ2XXS_LANE_OFF_BYTES) +#define HTP_IQ2XXS_LUT_BYTES ((HTP_IQ2XXS_GRID_OFF + HTP_IQ2XXS_GRID_REGION + 127) & ~127) #define HTP_TENSOR_TILE_SIZE_Q4_K 640 #define HTP_TENSOR_TILE_SIZE_Q5_K 768 #define HTP_TENSOR_TILE_SIZE_Q6_K 896 diff --git a/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h b/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h index 5a3dbe26e3ad..8176b5b2fc15 100644 --- a/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h +++ b/ggml/src/ggml-hexagon/htp/iq2xxs-tables.h @@ -8,7 +8,7 @@ #include #include "htp-tensor.h" -static const uint8_t __attribute__((aligned(128))) htp_iq2xxs_lut[HTP_IQ2XXS_LUT_BYTES] = { +static const uint8_t __attribute__((aligned(128))) htp_iq2xxs_lut[HTP_IQ2XXS_TABLE_BYTES] = { 0x08, 0x08, 0x00, 0x00, 0x19, 0x08, 0x00, 0x00, 0x2b, 0x08, 0x00, 0x00, 0x2b, 0x08, 0x00, 0x00, 0x08, 0x19, 0x00, 0x00, 0x19, 0x19, 0x00, 0x00, 0x2b, 0x19, 0x00, 0x00, 0x2b, 0x19, 0x00, 0x00, 0x08, 0x2b, 0x00, 0x00, 0x19, 0x2b, 0x00, 0x00, 0x2b, 0x2b, 0x00, 0x00, 0x2b, 0x2b, 0x00, 0x00, diff --git a/ggml/src/ggml-hexagon/htp/matmul-internal.h b/ggml/src/ggml-hexagon/htp/matmul-internal.h index de4221c47266..51d0697a522a 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-internal.h +++ b/ggml/src/ggml-hexagon/htp/matmul-internal.h @@ -183,7 +183,8 @@ static inline HVX_Vector * iq2xxs_tile_scratch(const uint8_t * tile) { // IQ2_XXS: start the 2 halfword grid-code gathers of a tile into its scratch, returns the sign/scale words static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) { HVX_Vector * restrict v_scr = iq2xxs_tile_scratch(tile); - const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES; + const uint8_t * grid = iq2xxs_vtcm_lut + HTP_IQ2XXS_GRID_OFF; + const HVX_Vector v_lane = hvx_vmem(iq2xxs_vtcm_lut + HTP_IQ2XXS_NIBBLE_BYTES); // lo: 4 grid indices per row, hi: 4 sign indices + scale per row HVX_VectorPair p = Q6_W_vdeal_VVR(hvx_vmem(tile + VLEN), hvx_vmem(tile), -IQ2XXS_WORD_BYTES); @@ -194,8 +195,10 @@ static inline HVX_Vector iq2xxs_gather_issue(const uint8_t * restrict tile) { Q6_V_vand_VV(Q6_Vw_vasl_VwR(v_idx, IQ2XXS_CODE_SHIFT + IQ2XXS_IDX_BITS), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK))); HVX_Vector v_off1 = Q6_V_vor_VV(Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, 2 * IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_LO_MASK)), Q6_V_vand_VV(Q6_Vuw_vlsr_VuwR(v_idx, IQ2XXS_IDX_BITS - IQ2XXS_CODE_SHIFT), Q6_V_vsplat_R(IQ2XXS_IDX_HI_MASK))); - Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off0); - Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_BYTES - 1, v_off1); + v_off0 = Q6_Vh_vadd_VhVh(v_off0, v_lane); + v_off1 = Q6_Vh_vadd_VhVh(v_off1, v_lane); + Q6_vgather_ARMVh(&v_scr[0], (size_t) grid, HTP_IQ2XXS_GRID_REGION - 1, v_off0); + Q6_vgather_ARMVh(&v_scr[1], (size_t) grid, HTP_IQ2XXS_GRID_REGION - 1, v_off1); return Q6_V_hi_W(p); } diff --git a/ggml/src/ggml-hexagon/htp/matmul-ops.c b/ggml/src/ggml-hexagon/htp/matmul-ops.c index d8dddef1fea1..289e14c01ffe 100644 --- a/ggml/src/ggml-hexagon/htp/matmul-ops.c +++ b/ggml/src/ggml-hexagon/htp/matmul-ops.c @@ -38,10 +38,30 @@ const uint8_t __attribute__((aligned(VLEN))) kvalues_mxfp4_lut[] = { const uint8_t * iq2xxs_vtcm_lut; +_Static_assert((HTP_IQ2XXS_GRID_COPIES & (HTP_IQ2XXS_GRID_COPIES - 1)) == 0, "grid copies must be a power of 2"); + +// VTCM layout: nibble table, per-lane grid copy offsets, then HTP_IQ2XXS_GRID_COPIES skewed grid copies void iq2xxs_lut_copy(uint8_t * restrict lut) { - for (uint32_t i = 0; i < HTP_IQ2XXS_LUT_BYTES / VLEN; i++) { + uint16_t __attribute__((aligned(VLEN))) lane_off[HTP_IQ2XXS_LANE_OFF_BYTES / sizeof(uint16_t)]; + for (uint32_t h = 0; h < HTP_IQ2XXS_LANE_OFF_BYTES / sizeof(uint16_t); h++) { + lane_off[h] = (h & (HTP_IQ2XXS_GRID_COPIES - 1)) * HTP_IQ2XXS_GRID_STRIDE; + } + + for (uint32_t i = 0; i < HTP_IQ2XXS_NIBBLE_BYTES / VLEN; i++) { hvx_vmem(lut + i * VLEN) = hvx_vmem(htp_iq2xxs_lut + i * VLEN); } + hvx_vmem(lut + HTP_IQ2XXS_NIBBLE_BYTES) = hvx_vmem(lane_off); + + HVX_Vector v_grid[HTP_IQ2XXS_GRID_BYTES / VLEN]; + for (uint32_t i = 0; i < HTP_IQ2XXS_GRID_BYTES / VLEN; i++) { + v_grid[i] = hvx_vmem(htp_iq2xxs_lut + HTP_IQ2XXS_NIBBLE_BYTES + i * VLEN); + } + for (uint32_t c = 0; c < HTP_IQ2XXS_GRID_COPIES; c++) { + for (uint32_t i = 0; i < HTP_IQ2XXS_GRID_BYTES / VLEN; i++) { + hvx_vmemu(lut + HTP_IQ2XXS_GRID_OFF + c * HTP_IQ2XXS_GRID_STRIDE + i * VLEN) = v_grid[i]; + } + } + iq2xxs_vtcm_lut = lut; } From 94be107ac2f2069d8751950487fa7c117242111f Mon Sep 17 00:00:00 2001 From: George Burton <8233643+gecBurton@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:31:39 +0000 Subject: [PATCH 325/401] model: add clef-omni (#33354) * add: model clef-omni Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com> * add: has_lm_head to prevent double loading output.weight * fix: potential key/index error in _load_clef_hparams * remove: trailing ggml_build_forward_expand(gf, cur), fix: provenance comment * add: test_decision_media_order to show that the media order matters * fix: decision_order_media so that media is ordered correctly * fix: comment in llama_tensor_get_type_impl * remove: unsused ggml_build_forward_expand(), fix: comment in build_arch_graph * fix: set min and max vison pixels for ClefOmniMmprojModel * add: decision type for cloudflare-clef-omni and reject video media * add: top-level audio in server-decision.cpp --------- Co-authored-by: WestWaters <100190545+WestWaters@users.noreply.github.com> --- common/common.cpp | 2 + common/common.h | 1 + conversion/__init__.py | 2 + conversion/clef.py | 66 ++++++++++--- gguf-py/gguf/constants.py | 50 ++++++++++ src/llama-arch.cpp | 2 + src/llama-arch.h | 1 + src/llama-model.cpp | 4 + src/llama-quant.cpp | 8 +- src/models/clef-omni.cpp | 96 ++++++++++++++++++ src/models/clef.cpp | 164 +++++++++++++++++-------------- src/models/models.h | 60 ++++++++--- src/models/qwen3vlmoe.cpp | 12 ++- tests/test-llama-archs.cpp | 3 +- tests/test-server-component.cpp | 120 ++++++++++++++++++++++ tools/server/README.md | 16 +-- tools/server/server-common.cpp | 1 + tools/server/server-decision.cpp | 54 ++++++++-- tools/server/server-decision.h | 9 +- 19 files changed, 548 insertions(+), 123 deletions(-) create mode 100644 src/models/clef-omni.cpp diff --git a/common/common.cpp b/common/common.cpp index b009d460d697..da7657d13399 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -1170,6 +1170,7 @@ static const std::map COMMON_DECISION_TYPE_NA { COMMON_DECISION_TYPE_MINICPM_OCR_JEV, "openbmb-minicpm-ocr-jev" }, { COMMON_DECISION_TYPE_LFM3_D1, "lfm3-d1" }, { COMMON_DECISION_TYPE_LFM3_D1_OMNI, "lfm3-d1-omni" }, + { COMMON_DECISION_TYPE_CLEF_OMNI, "cloudflare-clef-omni" }, // for future models, ALWAYS add org name prefix to avoid name collisions, e.g. "orgname-modelname" }; @@ -1298,6 +1299,7 @@ common_init_result::common_init_result(common_params & params, bool model_only) const auto decision_type = common_get_decision_type(model); // minicpm-ocr-jev reads its class scores from the pooled output, the pooling type is the one of the GGUF if (decision_type == COMMON_DECISION_TYPE_LAYA || decision_type == COMMON_DECISION_TYPE_KEV || decision_type == COMMON_DECISION_TYPE_CLEF || + decision_type == COMMON_DECISION_TYPE_CLEF_OMNI || decision_type == COMMON_DECISION_TYPE_LFM2_D1_OMNI || decision_type == COMMON_DECISION_TYPE_VLLM_DECISION2 || decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV) { const auto pooling_type = decision_type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV ? LLAMA_POOLING_TYPE_UNSPECIFIED : LLAMA_POOLING_TYPE_NONE; diff --git a/common/common.h b/common/common.h index aa454944c98b..1d8d57d714a3 100644 --- a/common/common.h +++ b/common/common.h @@ -1002,6 +1002,7 @@ enum common_decision_type { COMMON_DECISION_TYPE_MINICPM_OCR_JEV, // one score per class, the pooled embeddings output of the last token COMMON_DECISION_TYPE_LFM3_D1, // same as lfm2-d1, non-causal, label codes A..Z then AA, AB.. COMMON_DECISION_TYPE_LFM3_D1_OMNI, // same as lfm3-d1 + COMMON_DECISION_TYPE_CLEF_OMNI, // same as clef, with audio input and no video input COMMON_DECISION_TYPE_UNKNOWN, // a decision model of a type that is not supported }; diff --git a/conversion/__init__.py b/conversion/__init__.py index 87624f653205..9b72df673cb6 100644 --- a/conversion/__init__.py +++ b/conversion/__init__.py @@ -50,6 +50,7 @@ "ChatGLMModel": "chatglm", "ChatterboxModel": "chatterbox", "ClefModel": "clef", + "ClefOmniModel": "clef", "CloverMoeModelLM": "clover", "CodeShellForCausalLM": "codeshell", "CogVLMForCausalLM": "cogvlm", @@ -361,6 +362,7 @@ "AudioFlamingo3ForConditionalGeneration": "ultravox", "ChatterboxModel": "chatterbox", "ClefModel": "clef", + "ClefOmniModel": "clef", "CogVLMForCausalLM": "cogvlm", "Cohere2VisionForConditionalGeneration": "command_r", "PplxDeciderModel": "pplx_decider", diff --git a/conversion/clef.py b/conversion/clef.py index b793d92c8d32..ff9afa801c1b 100644 --- a/conversion/clef.py +++ b/conversion/clef.py @@ -4,7 +4,7 @@ import math from pathlib import Path -from typing import Any, Iterable, Iterator, TYPE_CHECKING +from typing import Any, Callable, Iterable, Iterator, TYPE_CHECKING import torch @@ -13,7 +13,7 @@ from .base import ModelBase, gguf, logger from .qwen import Qwen3_5TextModel -from .qwen3vl import Qwen3VLVisionModel +from .qwen3vl import Qwen3OmniMmprojModel, Qwen3OmniMoeTextModel, Qwen3VLVisionModel def _is_clef_checkpoint(dir_model: Path) -> bool: @@ -24,16 +24,16 @@ def _is_clef_checkpoint(dir_model: Path) -> bool: def _load_clef_hparams(dir_model: Path) -> dict[str, Any]: logger.info("gguf: detected Clef checkpoint") hparams = ModelBase.load_hparams(dir_model, False, guess=False) - hparams["architectures"] = ["ClefModel"] + # clef-omni has the same head on the Qwen3-Omni thinker + is_omni = "thinker_config" in hparams + hparams["architectures"] = ["ClefOmniModel" if is_omni else "ClefModel"] with open(dir_model / "joint_head_config.json", encoding="utf-8") as f: hparams["decision"] = json.load(f) return hparams -@ModelBase.register("ClefModel") -class ClefModel(Qwen3_5TextModel): - model_arch = gguf.MODEL_ARCH.CLEF - no_mtp = True # the checkpoint has no MTP head +class _ClefHeadMixin: + # the joint schema head, on top of the text model of the class that uses this mixin # prompt follows joint_schema_model.py of the model repo _SYSTEM_PROMPT = ( @@ -42,6 +42,17 @@ class ClefModel(Qwen3_5TextModel): ) # torch.nn.LayerNorm default, used by the head _HEAD_NORM_EPS = 1e-5 + # clef-omni puts a newline after each image, clef after all of them + _NEWLINE_PER_IMAGE = False + _DECISION_TYPE = gguf.DecisionType.CLEF + + model_arch: gguf.MODEL_ARCH + hparams: dict[str, Any] + block_count: int + gguf_writer: gguf.GGUFWriter + dir_model: Path + format_tensor_name: Callable[..., str] + map_tensor_name: Callable[..., str] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -52,7 +63,7 @@ def __init__(self, *args, **kwargs): self._scales: dict[str, float] = {} def set_vocab(self): - super().set_vocab() + super().set_vocab() # ty: ignore[missing-attribute] self.gguf_writer.add_chat_template([{"name": "systemone", "template": self._systemone_template()}]) @classmethod @@ -75,9 +86,13 @@ def render(name: str) -> str: "{% endif %}" "{{ ({'option_id': o.key} if d is none else {'description': d, 'option_id': o.key}) | tojson(separators=[',', ':']) }}" ) + if cls._NEWLINE_PER_IMAGE: + images = "{% for image in images %}{{ image }}" + text("\n") + "{% endfor %}" + else: + images = "{% for image in images %}{{ image }}{% endfor %}" + text("\n") return ( text(f"<|im_start|>system\n{cls._SYSTEM_PROMPT}<|im_end|>\n<|im_start|>user\nSTATE:\n") - + "{% if images %}{{ sep }}{% for image in images %}{{ image }}{% endfor %}" + text("\n") + "{% endif %}" + + "{% if images %}{{ sep }}" + images + "{% endif %}" + "{{ sep }}" + render("state") + "{{ sep }}" + text("\n\nSCHEMA FIELDS:\n") + "{% for q in questions %}" @@ -96,23 +111,23 @@ def render(name: str) -> str: ) def set_gguf_parameters(self): - super().set_gguf_parameters() + super().set_gguf_parameters() # ty: ignore[missing-attribute] head = self.hparams["decision"] - self.gguf_writer.add_decision_type(gguf.DecisionType.CLEF) + self.gguf_writer.add_decision_type(self._DECISION_TYPE) self.gguf_writer.add_decision_routing_block_count(head["routing_layers"]) self.gguf_writer.add_decision_block_count(head["layers"]) self.gguf_writer.add_decision_head_count(head["heads"]) self.gguf_writer.add_layer_norm_eps(self._HEAD_NORM_EPS) def get_tensors(self) -> Iterator[tuple[str, Tensor]]: - yield from super().get_tensors() + yield from super().get_tensors() # ty: ignore[missing-attribute] from safetensors.torch import load_file for name, data in load_file(self.dir_model / "joint_head.safetensors").items(): yield "joint_head." + name, data def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: if not name.startswith("joint_head."): - yield from super().modify_tensors(data_torch, name, bid) + yield from super().modify_tensors(data_torch, name, bid) # ty: ignore[missing-attribute] return parts = name.split(".") @@ -145,6 +160,31 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter yield self.map_tensor_name(name), data_torch +@ModelBase.register("ClefModel") +class ClefModel(_ClefHeadMixin, Qwen3_5TextModel): + model_arch = gguf.MODEL_ARCH.CLEF + no_mtp = True # the checkpoint has no MTP head + + @ModelBase.register("ClefModel") class ClefVisionModel(Qwen3VLVisionModel): pass + + +@ModelBase.register("ClefOmniModel") +class ClefOmniModel(_ClefHeadMixin, Qwen3OmniMoeTextModel): + model_arch = gguf.MODEL_ARCH.CLEF_OMNI + _NEWLINE_PER_IMAGE = True + _DECISION_TYPE = gguf.DecisionType.CLEF_OMNI + + +@ModelBase.register("ClefOmniModel") +class ClefOmniMmprojModel(Qwen3OmniMmprojModel): + # IMAGE_SIZE of joint_schema_model.py, the image budget is set there and not in the processor config + _IMAGE_MIN_PIXELS = 65_536 + _IMAGE_MAX_PIXELS = 1_048_576 + + def set_gguf_parameters(self): + super().set_gguf_parameters() + self.gguf_writer.add_vision_min_pixels(self._IMAGE_MIN_PIXELS) + self.gguf_writer.add_vision_max_pixels(self._IMAGE_MAX_PIXELS) diff --git a/gguf-py/gguf/constants.py b/gguf-py/gguf/constants.py index ccae76f8282b..43dc461ae563 100644 --- a/gguf-py/gguf/constants.py +++ b/gguf-py/gguf/constants.py @@ -653,6 +653,7 @@ class MODEL_ARCH(IntEnum): QWEN35MOE = auto() CLEF = auto() VLLM_DECISION2 = auto() + CLEF_OMNI = auto() CLOVER_MOE = auto() QWEN4EXP = auto() PHI2 = auto() @@ -1684,6 +1685,7 @@ class MODEL_TENSOR(IntEnum): MODEL_ARCH.QWEN35MOE: "qwen35moe", MODEL_ARCH.CLEF: "clef", MODEL_ARCH.VLLM_DECISION2: "vllm-decision2", + MODEL_ARCH.CLEF_OMNI: "clef-omni", MODEL_ARCH.CLOVER_MOE: "clover_moe", MODEL_ARCH.QWEN4EXP: "qwen4exp", MODEL_ARCH.PHI2: "phi2", @@ -3775,6 +3777,53 @@ class MODEL_TENSOR(IntEnum): MODEL_TENSOR.DECISION_SCORER, MODEL_TENSOR.DECISION_SCORER_OUT, ], + MODEL_ARCH.CLEF_OMNI: [ + MODEL_TENSOR.TOKEN_EMBD, + MODEL_TENSOR.OUTPUT_NORM, + MODEL_TENSOR.OUTPUT, + MODEL_TENSOR.ATTN_NORM, + MODEL_TENSOR.ATTN_Q, + MODEL_TENSOR.ATTN_Q_NORM, + MODEL_TENSOR.ATTN_K, + MODEL_TENSOR.ATTN_K_NORM, + MODEL_TENSOR.ATTN_V, + MODEL_TENSOR.ATTN_OUT, + MODEL_TENSOR.ATTN_QKV, + MODEL_TENSOR.FFN_NORM, + MODEL_TENSOR.FFN_GATE_INP, + MODEL_TENSOR.FFN_DOWN_EXP, + MODEL_TENSOR.FFN_UP_EXP, + MODEL_TENSOR.FFN_GATE_EXP, + # decision head + MODEL_TENSOR.TOKEN_TYPES, + MODEL_TENSOR.DEC_ATTN_NORM, + MODEL_TENSOR.DEC_ATTN_Q, + MODEL_TENSOR.DEC_ATTN_K, + MODEL_TENSOR.DEC_ATTN_V, + MODEL_TENSOR.DEC_ATTN_OUT, + MODEL_TENSOR.DEC_CROSS_ATTN_NORM, + MODEL_TENSOR.DEC_CROSS_ATTN_NORM_KV, + MODEL_TENSOR.DEC_CROSS_ATTN_Q, + MODEL_TENSOR.DEC_CROSS_ATTN_K, + MODEL_TENSOR.DEC_CROSS_ATTN_V, + MODEL_TENSOR.DEC_CROSS_ATTN_OUT, + MODEL_TENSOR.DEC_FFN_NORM, + MODEL_TENSOR.DEC_FFN_DOWN, + MODEL_TENSOR.DEC_FFN_UP, + MODEL_TENSOR.DECISION_HIDDEN_NORM, + MODEL_TENSOR.DECISION_PROJ_MEMORY, + MODEL_TENSOR.DECISION_PROJ_QUESTION, + MODEL_TENSOR.DECISION_PROJ_OPTION_QUESTION, + MODEL_TENSOR.DECISION_PROJ_GLOBAL, + MODEL_TENSOR.DECISION_PROJ_OPTION_CONTEXT, + MODEL_TENSOR.DECISION_PROJ_OPTION_LEXICAL, + MODEL_TENSOR.DECISION_OPTION_SUMMARY_NORM, + MODEL_TENSOR.DECISION_FIELD_NORM, + MODEL_TENSOR.DECISION_OPTION_NORM, + MODEL_TENSOR.DECISION_SCALES, + MODEL_TENSOR.DECISION_SCORER, + MODEL_TENSOR.DECISION_SCORER_OUT, + ], MODEL_ARCH.VLLM_DECISION2: [ MODEL_TENSOR.TOKEN_EMBD, MODEL_TENSOR.OUTPUT_NORM, @@ -7654,6 +7703,7 @@ class DecisionType: GRANITE_SWITCH = "granite-switch" # same as openjev, run by the decision aLoRA of granite switch H2O_LIGHTNING = "h2o-lightning" # same as openjev, labels read after an answer prefill MINICPM_OCR_JEV = "openbmb-minicpm-ocr-jev" # class scores of a value head read at the last token, one fixed task + CLEF_OMNI = "cloudflare-clef-omni" # same as clef on the Qwen3-Omni thinker, with audio input and no video input class VisionProjectorType: diff --git a/src/llama-arch.cpp b/src/llama-arch.cpp index e78c3d2a8479..f41434f7ab7a 100644 --- a/src/llama-arch.cpp +++ b/src/llama-arch.cpp @@ -45,6 +45,7 @@ static const std::map LLM_ARCH_NAMES = { { LLM_ARCH_QWEN35, "qwen35" }, { LLM_ARCH_QWEN35MOE, "qwen35moe" }, { LLM_ARCH_CLEF, "clef" }, + { LLM_ARCH_CLEF_OMNI, "clef-omni" }, { LLM_ARCH_VLLM_DECISION2, "vllm-decision2" }, { LLM_ARCH_QWEN4EXP, "qwen4exp" }, { LLM_ARCH_PHI2, "phi2" }, @@ -1655,6 +1656,7 @@ bool llama_arch_supports_save(llm_arch arch) { case LLM_ARCH_T5: case LLM_ARCH_STEP35: case LLM_ARCH_CLEF: // the head tensors are not saved + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_INKLING2_LOOP: // the loop tensors are not saved and the cache slots are expanded at load case LLM_ARCH_VLLM_DECISION2: return false; diff --git a/src/llama-arch.h b/src/llama-arch.h index 03e8b8c80e61..7508fd2af0dd 100644 --- a/src/llama-arch.h +++ b/src/llama-arch.h @@ -48,6 +48,7 @@ enum llm_arch { LLM_ARCH_QWEN35, LLM_ARCH_QWEN35MOE, LLM_ARCH_CLEF, + LLM_ARCH_CLEF_OMNI, LLM_ARCH_VLLM_DECISION2, LLM_ARCH_CLOVER_MOE, LLM_ARCH_QWEN4EXP, diff --git a/src/llama-model.cpp b/src/llama-model.cpp index 7b6e9ea118f2..4de14366632a 100644 --- a/src/llama-model.cpp +++ b/src/llama-model.cpp @@ -373,6 +373,8 @@ static llama_model * llama_model_mapping(llm_arch arch, const llama_model_params return new llama_model_qwen35moe(params); case LLM_ARCH_CLEF: return new llama_model_clef(params); + case LLM_ARCH_CLEF_OMNI: + return new llama_model_clef_omni(params); case LLM_ARCH_VLLM_DECISION2: return new llama_model_vllm_decision2(params); case LLM_ARCH_CLOVER_MOE: @@ -3044,6 +3046,7 @@ llama_memory_i * llama_model::create_memory(const llama_memory_params & params, case LLM_ARCH_LLADA_MOE: case LLM_ARCH_RND1: case LLM_ARCH_CLEF: + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_KOKORO: case LLM_ARCH_TINY_VOCA: { @@ -3977,6 +3980,7 @@ llama_rope_type llama_model_rope_type(const llama_model * model) { case LLM_ARCH_QWEN35: case LLM_ARCH_QWEN35MOE: case LLM_ARCH_CLEF: + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_QWEN4EXP: case LLM_ARCH_QWEN3TTS: return LLAMA_ROPE_TYPE_IMROPE; diff --git a/src/llama-quant.cpp b/src/llama-quant.cpp index 38eb0d588ba8..2c93e16dca8f 100644 --- a/src/llama-quant.cpp +++ b/src/llama-quant.cpp @@ -528,7 +528,13 @@ static ggml_type llama_tensor_get_type_impl(quantize_state_impl & qs, ggml_type if (n_expert > 1) { // Experts may not be consecutive and simply dividing i_ffn_down by n_expert does not work, // so we need to parse the tensor name - if (sscanf(tname, "blk.%d.", &i_layer) != 1) { throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); } + if (sscanf(tname, "blk.%d.", &i_layer) != 1) { + // the blocks of a decision head use their own numbering, block N is treated like backbone layer N + if (sscanf(tname, "dec.blk.%d.", &i_layer) == 1) { + return std::make_pair(i_layer, n_layer); + } + throw std::runtime_error(format("Failed to determine layer for tensor %s", tname)); + } if (i_layer < 0 || i_layer >= n_layer) { throw std::runtime_error(format("Bad layer %d for tensor %s. Must be in [0, %d)", i_layer, tname, n_layer)); } } diff --git a/src/models/clef-omni.cpp b/src/models/clef-omni.cpp new file mode 100644 index 000000000000..d54332cf018d --- /dev/null +++ b/src/models/clef-omni.cpp @@ -0,0 +1,96 @@ +#include "models.h" + +void llama_model_clef_omni::load_arch_hparams(llama_model_loader & ml) { + llama_model_qwen3vlmoe::load_arch_hparams(ml); + head.load_hparams(ml, hparams); +} + +void llama_model_clef_omni::load_arch_tensors(llama_model_loader & ml) { + llama_model_qwen3vlmoe::load_arch_tensors(ml); + head.load_tensors(ml, *this); +} + +std::unique_ptr llama_model_clef_omni::build_arch_graph(const llm_graph_params & params) const { + return std::make_unique(params); +} + +// the backbone is copied from llama_model_qwen3vlmoe::graph, without the memory module +// it also drops inp_out_ids (the head reads all tokens) and build_cvec(), as clef does +llama_model_clef_omni::graph::graph(const llm_graph_params & params) : llm_graph_context(params) { + const auto & model = static_cast(*params.model); + + const int64_t n_embd_head = hparams.n_embd_head_v(); + + GGML_ASSERT(n_embd_head == hparams.n_embd_head_k()); + GGML_ASSERT(n_embd_head == n_rot); + + ggml_tensor * cur; + ggml_tensor * inpL; + + inpL = build_inp_embd(model.tok_embd); + + ggml_tensor * inp_pos = build_inp_pos(); + + auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this); + + for (int il = 0; il < n_layer; ++il) { + ggml_tensor * inpSA = inpL; + + cur = build_norm(inpL, model.layers[il].attn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "attn_norm", il); + + auto [Qcur, Kcur, Vcur] = build_qkv(model.layers[il], cur, n_embd_head, n_head, n_head_kv, il); + + Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, NULL, LLM_NORM_RMS, il); + cb(Qcur, "Qcur_normed", il); + + Qcur = build_rope(Qcur, inp_pos, il); + + Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, NULL, LLM_NORM_RMS, il); + cb(Kcur, "Kcur_normed", il); + + Kcur = build_rope(Kcur, inp_pos, il); + + cur = build_attn(inp_attn, + model.layers[il].wo, model.layers[il].wo_b, + Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il); + + ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA); + cb(ffn_inp, "ffn_inp", il); + + cur = build_norm(ffn_inp, model.layers[il].ffn_norm, NULL, LLM_NORM_RMS, il); + cb(cur, "ffn_norm", il); + + cur = build_moe_ffn(cur, + model.layers[il].ffn_gate_inp, + model.layers[il].ffn_up_exps, + model.layers[il].ffn_gate_exps, + model.layers[il].ffn_down_exps, + nullptr, + n_expert, n_expert_used, + LLM_FFN_SILU, true, + hparams.expert_weights_scale, + LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX, + il); + cb(cur, "ffn_moe_out", il); + + cur = ggml_add(ctx0, cur, ffn_inp); + cb(cur, "l_out", il); + + if (il < (int) hparams.n_deepstack_layers) { + ggml_tensor * ds = ggml_view_2d(ctx0, res->t_inp_embd, n_embd, n_tokens, res->t_inp_embd->nb[1], (il + 1) * n_embd * sizeof(float)); + cur = ggml_add(ctx0, cur, ds); + cb(cur, "deepstack_out", il); + } + + inpL = cur; + } + + cur = build_norm(inpL, model.output_norm, NULL, LLM_NORM_RMS, -1); + cb(cur, "result_norm", -1); + + // the head is always evaluated, so that the graph has the same nodes for every batch + cur = model.head.build(*this, cur); + + res->t_embd = cur; +} diff --git a/src/models/clef.cpp b/src/models/clef.cpp index d7d94f49b825..13756147612a 100644 --- a/src/models/clef.cpp +++ b/src/models/clef.cpp @@ -5,9 +5,7 @@ #include #include -void llama_model_clef::load_arch_hparams(llama_model_loader & ml) { - llama_model_qwen35::load_arch_hparams(ml); - +void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hparams) { ml.get_key(LLM_KV_DECISION_ROUTING_BLOCK_COUNT, n_layer_routing); ml.get_key(LLM_KV_DECISION_BLOCK_COUNT, n_layer_joint); ml.get_key(LLM_KV_DECISION_HEAD_COUNT, n_head_decision); @@ -23,10 +21,18 @@ void llama_model_clef::load_arch_hparams(llama_model_loader & ml) { hparams.n_embd_out_impl = 1; } -void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { - llama_model_qwen35::load_arch_tensors(ml); +void llama_model_clef::load_arch_hparams(llama_model_loader & ml) { + llama_model_qwen35::load_arch_hparams(ml); + head.load_hparams(ml, hparams); +} - LLAMA_LOAD_LOCALS; +void llama_clef_head::load_tensors(llama_model_loader & ml, llama_model_base & model) { + const auto & tn = model.tn; + const int64_t n_embd = model.hparams.n_embd; + + auto create_tensor = [&](const LLM_TN_IMPL & name, const std::initializer_list & ne, int flags) { + return model.create_tensor(ml, name, ne, flags); + }; const auto * w_memory = ml.get_weight(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight").str().c_str()); const auto * w_ffn = ml.get_weight(tn(LLM_TENSOR_DEC_FFN_UP, "weight", 0).str().c_str()); @@ -82,10 +88,10 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { load_norm(field_norm, LLM_TENSOR_DECISION_FIELD_NORM, n_embd_h); load_norm(option_norm, LLM_TENSOR_DECISION_OPTION_NORM, n_embd_h); - output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); + output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, model.vocab.n_tokens()}, model.TENSOR_NOT_REQUIRED); if (output_lexical == nullptr) { - output_lexical = tok_embd; + output_lexical = model.tok_embd; } proj_memory = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight"), {n_embd, n_embd_h}, 0); @@ -104,6 +110,11 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { scorer_out_b = create_tensor(tn(LLM_TENSOR_DECISION_SCORER_OUT, "bias"), {1}, 0); } +void llama_model_clef::load_arch_tensors(llama_model_loader & ml) { + llama_model_qwen35::load_arch_tensors(ml); + head.load_tensors(ml, *this); +} + std::unique_ptr llama_model_clef::build_arch_graph(const llm_graph_params & params) const { return std::make_unique(params); } @@ -185,7 +196,7 @@ static size_t clef_n_questions(int64_t n_tokens) { return n_tokens / 2 + 1; } static size_t clef_n_options (int64_t n_tokens) { return std::max(n_tokens - 1, 1); } // pooling matrices and indices computed from the spans -class llama_model_clef::input_decision : public llm_graph_input_i { +class llama_clef_head::input_decision : public llm_graph_input_i { public: input_decision(const llama_ubatch & ubatch) : n_tokens(ubatch.n_tokens), n_questions(clef_n_questions(n_tokens)), n_options(clef_n_options(n_tokens)) {} @@ -277,11 +288,7 @@ llama_model_clef::graph::graph(const llm_graph_params & params) : ggml_tensor * inp_pos = build_inp_pos(); - auto * inp_attn = build_attn_inp_causal(); - - auto inp_decision_ptr = std::make_unique(ubatch); - auto * inp_decision = inp_decision_ptr.get(); - res->add_input(std::move(inp_decision_ptr)); + auto * inp_attn = llama_clef_head::build_attn_inp_causal(*this); for (int il = 0; il < n_layer; ++il) { ggml_tensor * inpSA = inpL; @@ -321,16 +328,9 @@ llama_model_clef::graph::graph(const llm_graph_params & params) : cb(cur, "result_norm", -1); // the head is always evaluated, so that the graph has the same nodes for every batch - cur = build_head(cur, inp_decision); - - // row i of the output is the score of option i - cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0); - cur = ggml_add(ctx0, cur, inp_decision->status); - cb(cur, "result_decision", -1); + cur = model.head.build(*this, cur); res->t_embd = cur; - - ggml_build_forward_expand(gf, cur); } // causal mask by batch order: the tokens of an image share the same position @@ -361,16 +361,16 @@ class llm_graph_input_attn_clef : public llm_graph_input_attn_no_cache { }; // same as build_attn_inp_no_cache(), with a causal mask even if the batch is processed by the encoder path -llm_graph_input_attn_no_cache * llama_model_clef::graph::build_attn_inp_causal() { - auto inp = std::make_unique(hparams, cparams); +llm_graph_input_attn_no_cache * llama_clef_head::build_attn_inp_causal(const llm_graph_context & ctx) { + auto inp = std::make_unique(ctx.hparams, ctx.cparams); - const auto type_mask = cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32; + const auto type_mask = ctx.cparams.flash_attn ? GGML_TYPE_F16 : GGML_TYPE_F32; - inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx0, type_mask, GGML_PAD(n_tokens, 256), n_tokens, 1, 1); + inp->self_attn_mask.raw = ggml_new_tensor_4d(ctx.ctx0, type_mask, GGML_PAD(ctx.n_tokens, 256), ctx.n_tokens, 1, 1); ggml_set_input(inp->self_attn_mask.raw); - cb(inp->self_attn_mask.raw, "self_kq_mask", -1); + ctx.cb(inp->self_attn_mask.raw, "self_kq_mask", -1); - return (llm_graph_input_attn_no_cache *) res->add_input(std::move(inp)); + return (llm_graph_input_attn_no_cache *) ctx.res->add_input(std::move(inp)); } ggml_tensor * llama_model_clef::graph::build_layer_attn( @@ -496,21 +496,23 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear( return ggml_reshape_2d(ctx0, cur, n_embd, n_tokens); } -ggml_tensor * llama_model_clef::graph::build_head_norm(ggml_tensor * cur, const norm & n) { - return build_norm(cur, n.w, n.b, LLM_NORM, -1); +ggml_tensor * llama_clef_head::build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const { + return ctx.build_norm(cur, n.w, n.b, LLM_NORM, -1); } // q: [n_embd_h, n_q], kv: [n_embd_h, n_kv], kq_mask: [n_kv, n_q] or null -ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) { +ggml_tensor * llama_clef_head::build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask) const { + ggml_context * ctx0 = ctx.ctx0; + const int64_t n_embd_h = q->ne[0]; - const int64_t n_head_h = model.n_head_decision; + const int64_t n_head_h = n_head_decision; const int64_t d_head = n_embd_h / n_head_h; const int64_t n_q = q->ne[1]; const int64_t n_kv = kv->ne[1]; - ggml_tensor * Qcur = ggml_add(ctx0, build_lora_mm(a.wq, q), a.bq); - ggml_tensor * Kcur = ggml_add(ctx0, build_lora_mm(a.wk, kv), a.bk); - ggml_tensor * Vcur = ggml_add(ctx0, build_lora_mm(a.wv, kv), a.bv); + ggml_tensor * Qcur = ggml_add(ctx0, ctx.build_lora_mm(a.wq, q), a.bq); + ggml_tensor * Kcur = ggml_add(ctx0, ctx.build_lora_mm(a.wk, kv), a.bk); + ggml_tensor * Vcur = ggml_add(ctx0, ctx.build_lora_mm(a.wv, kv), a.bv); Qcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Qcur, d_head, n_head_h, n_q), 0, 2, 1, 3); // [d_head, n_q, n_head] Kcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Kcur, d_head, n_head_h, n_kv), 0, 2, 1, 3); // [d_head, n_kv, n_head] @@ -523,18 +525,29 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head] cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q); - return ggml_add(ctx0, build_lora_mm(a.wo, cur), a.bo); + return ggml_add(ctx0, ctx.build_lora_mm(a.wo, cur), a.bo); } -ggml_tensor * llama_model_clef::graph::build_head_ffn(ggml_tensor * cur, const head_layer & layer) { - cur = build_head_norm(cur, layer.ffn_norm); - cur = ggml_add(ctx0, build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b); +ggml_tensor * llama_clef_head::build_head_ffn(const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const { + ggml_context * ctx0 = ctx.ctx0; + + cur = build_head_norm(ctx, cur, layer.ffn_norm); + cur = ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b); cur = ggml_gelu_erf(ctx0, cur); - return ggml_add(ctx0, build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b); + return ggml_add(ctx0, ctx.build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b); } // ref: JointSchemaHead in joint_schema_model.py of the model repo -ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_decision * inp) { +ggml_tensor * llama_clef_head::build(const llm_graph_context & ctx, ggml_tensor * hidden) const { + ggml_context * ctx0 = ctx.ctx0; + + const int64_t n_embd = hidden->ne[0]; + const int64_t n_tokens = hidden->ne[1]; + + auto inp_ptr = std::make_unique(ctx.ubatch); + auto * inp = inp_ptr.get(); + ctx.res->add_input(std::move(inp_ptr)); + const int64_t n_questions = inp->n_questions; const int64_t n_options = inp->n_options; @@ -550,9 +563,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_set_input(t); } - hidden = build_head_norm(hidden, model.hidden_norm); + hidden = build_head_norm(ctx, hidden, hidden_norm); - ggml_tensor * memory = build_lora_mm(model.proj_memory, hidden); // [n_embd_h, n_tokens] + ggml_tensor * memory = ctx.build_lora_mm(proj_memory, hidden); // [n_embd_h, n_tokens] const int64_t n_embd_h = memory->ne[0]; @@ -565,29 +578,29 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_tensor * opt_ctx = ggml_mul_mat(ctx0, hidden_t, inp->pool_o); // [n_embd, n_options] // mean of the output embeddings of the tokens of each option - ggml_tensor * lexical = ggml_get_rows(ctx0, model.output_lexical, inp->tokens); + ggml_tensor * lexical = ggml_get_rows(ctx0, output_lexical, inp->tokens); lexical = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, lexical)), inp->pool_o); // [n_embd, n_options] // one query per option - ggml_tensor * options = build_lora_mm(model.proj_option_context, opt_ctx); - options = ggml_add(ctx0, options, build_lora_mm(model.proj_option_lexical, lexical)); - options = ggml_add(ctx0, options, ggml_get_rows(ctx0, build_lora_mm(model.proj_option_question, question), inp->option_question)); + ggml_tensor * options = ctx.build_lora_mm(proj_option_context, opt_ctx); + options = ggml_add(ctx0, options, ctx.build_lora_mm(proj_option_lexical, lexical)); + options = ggml_add(ctx0, options, ggml_get_rows(ctx0, ctx.build_lora_mm(proj_option_question, question), inp->option_question)); // the options read the prompt - for (uint32_t il = 0; il < model.n_layer_routing; ++il) { - const auto & layer = model.head_layers[il]; + for (uint32_t il = 0; il < n_layer_routing; ++il) { + const auto & layer = head_layers[il]; - ggml_tensor * cur = build_head_attn( - build_head_norm(options, layer.cross_norm), - build_head_norm(memory, layer.cross_norm_kv), + ggml_tensor * cur = build_head_attn(ctx, + build_head_norm(ctx, options, layer.cross_norm), + build_head_norm(ctx, memory, layer.cross_norm_kv), layer.cross_attn); options = ggml_add(ctx0, options, cur); - options = ggml_add(ctx0, options, build_head_ffn(options, layer)); + options = ggml_add(ctx0, options, build_head_ffn(ctx, options, layer)); } - cb(options, "decision_options", -1); + ctx.cb(options, "decision_options", -1); // one vector per question: its text, a summary of its options, the end of the prompt and its type - ggml_tensor * fields = build_lora_mm(model.proj_question, question); // [n_embd_h, n_questions] + ggml_tensor * fields = ctx.build_lora_mm(proj_question, question); // [n_embd_h, n_questions] { // each question weights its own options ggml_tensor * weights = ggml_mul_mat(ctx0, options, fields); // [n_options, n_questions] @@ -596,25 +609,25 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_tensor * summary = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, options)), weights); - fields = ggml_add(ctx0, fields, build_head_norm(summary, model.option_summary_norm)); - fields = ggml_add(ctx0, fields, build_lora_mm(model.proj_global, global)); - fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, model.type_embd, inp->question_type)); + fields = ggml_add(ctx0, fields, build_head_norm(ctx, summary, option_summary_norm)); + fields = ggml_add(ctx0, fields, ctx.build_lora_mm(proj_global, global)); + fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, type_embd, inp->question_type)); } // the questions read each other and the prompt - for (uint32_t il = model.n_layer_routing; il < model.head_layers.size(); ++il) { - const auto & layer = model.head_layers[il]; + for (uint32_t il = n_layer_routing; il < head_layers.size(); ++il) { + const auto & layer = head_layers[il]; - ggml_tensor * cur = build_head_norm(fields, layer.self_norm); - fields = ggml_add(ctx0, fields, build_head_attn(cur, cur, layer.self_attn, inp->question_mask)); + ggml_tensor * cur = build_head_norm(ctx, fields, layer.self_norm); + fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, cur, layer.self_attn, inp->question_mask)); - cur = build_head_norm(fields, layer.cross_norm); - fields = ggml_add(ctx0, fields, build_head_attn(cur, memory, layer.cross_attn)); + cur = build_head_norm(ctx, fields, layer.cross_norm); + fields = ggml_add(ctx0, fields, build_head_attn(ctx, cur, memory, layer.cross_attn)); - fields = ggml_add(ctx0, fields, build_head_ffn(fields, layer)); + fields = ggml_add(ctx0, fields, build_head_ffn(ctx, fields, layer)); } - fields = build_head_norm(fields, model.field_norm); - cb(fields, "decision_fields", -1); + fields = build_head_norm(ctx, fields, field_norm); + ctx.cb(fields, "decision_fields", -1); const float eps = 1e-12f; @@ -624,7 +637,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de ggml_tensor * prior = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, lexical, eps), anchor)); // [1, n_options] // joint: each option against the vector of its question - options = build_head_norm(options, model.option_norm); + options = build_head_norm(ctx, options, option_norm); ggml_tensor * field = ggml_get_rows(ctx0, fields, inp->option_question); // [n_embd_h, n_options] ggml_tensor * cosine = ggml_sum_rows(ctx0, ggml_mul(ctx0, ggml_l2_norm(ctx0, field, eps), ggml_l2_norm(ctx0, options, eps))); @@ -633,15 +646,22 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de features = ggml_concat(ctx0, features, ggml_mul(ctx0, field, options), 0); features = ggml_concat(ctx0, features, ggml_abs(ctx0, ggml_sub(ctx0, field, options)), 0); - ggml_tensor * residual = ggml_add(ctx0, build_lora_mm(model.scorer, features), model.scorer_b); + ggml_tensor * residual = ggml_add(ctx0, ctx.build_lora_mm(scorer, features), scorer_b); residual = ggml_gelu_erf(ctx0, residual); - residual = ggml_add(ctx0, build_lora_mm(model.scorer_out, residual), model.scorer_out_b); // [1, n_options] + residual = ggml_add(ctx0, ctx.build_lora_mm(scorer_out, residual), scorer_out_b); // [1, n_options] auto scale = [&](int i) { - return ggml_view_1d(ctx0, model.scales, 1, i * ggml_element_size(model.scales)); + return ggml_view_1d(ctx0, scales, 1, i * ggml_element_size(scales)); }; ggml_tensor * joint = ggml_add(ctx0, ggml_mul(ctx0, cosine, scale(1)), residual); - return ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2))); + ggml_tensor * cur = ggml_add(ctx0, ggml_mul(ctx0, prior, scale(0)), ggml_mul(ctx0, joint, scale(2))); + + // row i of the output is the score of option i + cur = ggml_pad(ctx0, cur, 0, n_tokens - cur->ne[1], 0, 0); + cur = ggml_add(ctx0, cur, inp->status); + ctx.cb(cur, "result_decision", -1); + + return cur; } diff --git a/src/models/models.h b/src/models/models.h index 893e74251703..e4bd4eb5877f 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -701,6 +701,8 @@ struct llama_model_qwen3vlmoe : public llama_model_base { graph(const llm_graph_params & params); }; + // if false, the derived model does not use the LM head and builds its own output + virtual bool has_lm_head() const { return true; } std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; @@ -3004,12 +3006,8 @@ struct llama_model_qwen35 : public llama_model_base { std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; }; -// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states -struct llama_model_clef : public llama_model_qwen35 { - llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {} - void load_arch_hparams(llama_model_loader & ml) override; - void load_arch_tensors(llama_model_loader & ml) override; - +// joint decision head of clef, on top of the final hidden states of a backbone evaluated without memory +struct llama_clef_head { struct attn { ggml_tensor * wq = nullptr; ggml_tensor * bq = nullptr; @@ -3058,6 +3056,7 @@ struct llama_model_clef : public llama_model_qwen35 { ggml_tensor * proj_option_context = nullptr; ggml_tensor * proj_option_lexical = nullptr; ggml_tensor * scales = nullptr; // prior scale, joint scale, residual gate + ggml_tensor * type_embd = nullptr; ggml_tensor * scorer = nullptr; ggml_tensor * scorer_b = nullptr; ggml_tensor * scorer_out = nullptr; @@ -3066,11 +3065,33 @@ struct llama_model_clef : public llama_model_qwen35 { class input_decision; + void load_hparams(llama_model_loader & ml, llama_hparams & hparams); + void load_tensors(llama_model_loader & ml, llama_model_base & model); + + // causal mask by batch order, for the attention layers of the backbone + static llm_graph_input_attn_no_cache * build_attn_inp_causal(const llm_graph_context & ctx); + + // hidden: [n_embd, n_tokens] + // returns [1, n_tokens], row i is the score of option i + ggml_tensor * build(const llm_graph_context & ctx, ggml_tensor * hidden) const; + +private: + ggml_tensor * build_head_norm(const llm_graph_context & ctx, ggml_tensor * cur, const norm & n) const; + ggml_tensor * build_head_attn(const llm_graph_context & ctx, ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr) const; + ggml_tensor * build_head_ffn (const llm_graph_context & ctx, ggml_tensor * cur, const head_layer & layer) const; +}; + +// Qwen3.5 backbone evaluated without memory, with a joint decision head on top of its hidden states +struct llama_model_clef : public llama_model_qwen35 { + llama_model_clef(const struct llama_model_params & params) : llama_model_qwen35(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + llama_clef_head head; + struct graph : public llm_build_delta_net_base { graph(const llm_graph_params & params); private: - llm_graph_input_attn_no_cache * build_attn_inp_causal(); - ggml_tensor * build_layer_attn( llm_graph_input_attn_no_cache * inp_attn, ggml_tensor * cur, @@ -3081,16 +3102,23 @@ struct llama_model_clef : public llama_model_qwen35 { ggml_tensor * cur, int il); - // hidden: [n_embd, n_tokens], returns one score per option: [1, n_options] - ggml_tensor * build_head( - ggml_tensor * hidden, - input_decision * inp); + const llama_model_clef & model; + }; - ggml_tensor * build_head_norm(ggml_tensor * cur, const norm & n); - ggml_tensor * build_head_attn(ggml_tensor * q, ggml_tensor * kv, const attn & a, ggml_tensor * kq_mask = nullptr); - ggml_tensor * build_head_ffn (ggml_tensor * cur, const head_layer & layer); + bool has_lm_head() const override { return false; } + std::unique_ptr build_arch_graph(const llm_graph_params & params) const override; +}; - const llama_model_clef & model; +// Qwen3-Omni thinker (Qwen3 MoE) backbone evaluated without memory, with the clef decision head +struct llama_model_clef_omni : public llama_model_qwen3vlmoe { + llama_model_clef_omni(const struct llama_model_params & params) : llama_model_qwen3vlmoe(params) {} + void load_arch_hparams(llama_model_loader & ml) override; + void load_arch_tensors(llama_model_loader & ml) override; + + llama_clef_head head; + + struct graph : public llm_graph_context { + graph(const llm_graph_params & params); }; bool has_lm_head() const override { return false; } diff --git a/src/models/qwen3vlmoe.cpp b/src/models/qwen3vlmoe.cpp index 0d13a1dc5425..acab474ef5d6 100644 --- a/src/models/qwen3vlmoe.cpp +++ b/src/models/qwen3vlmoe.cpp @@ -20,10 +20,14 @@ void llama_model_qwen3vlmoe::load_arch_tensors(llama_model_loader &) { // output output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0); - output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); - // if output is NULL, init from the input tok embed - if (output == NULL) { - output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + + if (has_lm_head()) { + output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED); + + // if output is NULL, init from the input tok embed + if (output == NULL) { + output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED); + } } for (int i = 0; i < n_layer; ++i) { diff --git a/tests/test-llama-archs.cpp b/tests/test-llama-archs.cpp index dc4eeaba4d7c..7b53cd947a53 100644 --- a/tests/test-llama-archs.cpp +++ b/tests/test-llama-archs.cpp @@ -1184,6 +1184,7 @@ static bool moe_mandatory(const llm_arch arch) { case LLM_ARCH_QWEN3MOE: case LLM_ARCH_QWEN3NEXT: case LLM_ARCH_QWEN3VLMOE: + case LLM_ARCH_CLEF_OMNI: case LLM_ARCH_QWEN35MOE: case LLM_ARCH_CLOVER_MOE: case LLM_ARCH_QWEN4EXP: @@ -1297,7 +1298,7 @@ static bool arch_supported(const llm_arch arch) { if (arch == LLM_ARCH_PLM) { return false; // TODO tensor shapes } - if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_VLLM_DECISION2) { + if (arch == LLM_ARCH_CLEF || arch == LLM_ARCH_CLEF_OMNI || arch == LLM_ARCH_VLLM_DECISION2) { return false; // TODO decision head tensors } if (arch == LLM_ARCH_DEEPSEEK2OCR) { diff --git a/tests/test-server-component.cpp b/tests/test-server-component.cpp index d5933167e746..6f0dc64d041b 100644 --- a/tests/test-server-component.cpp +++ b/tests/test-server-component.cpp @@ -773,6 +773,40 @@ static void test_decision_ocr_jev_validation(testing & t) { reject_state("two images, three given", files_of(3), "this model needs exactly 2 images"); } +// server_decision_context::parse_state: "images" and "audio" are aliases of "files" +// + +static void test_decision_media_fields(testing & t) { + server_decision_context ctx; + ctx.type = COMMON_DECISION_TYPE_CLEF_OMNI; + + // only base64-decoded, the media itself is not parsed here + const std::string image = "data:image/png;base64,AAAA"; + const std::string audio = "data:audio/wav;base64,AQID"; + + std::vector files; + ctx.parse_state({{"state", "x"}, {"audio", json::array({audio})}}, files); + t.assert_equal("audio is read", (size_t) 1, files.size()); + t.assert_true("audio content", files[0] == raw_buffer({1, 2, 3})); + + files.clear(); + ctx.parse_state({{"state", "x"}, {"files", json::array({image})}, {"images", json::array({image})}, {"audio", json::array({audio})}}, files); + t.assert_equal("all fields are read", (size_t) 3, files.size()); + t.assert_true("audio after files and images", files[2] == raw_buffer({1, 2, 3})); + + files.clear(); + ctx.parse_state({{"state", "x"}, {"audio", nullptr}}, files); + t.assert_true("null audio", files.empty()); + + std::string error; + try { + ctx.parse_state({{"state", "x"}, {"audio", audio}}, files); + } catch (const std::invalid_argument & e) { + error = e.what(); + } + t.assert_true("audio must be an array: " + error, error.find("\"audio\" must be an array") != std::string::npos); +} + // server_decision_context: the recursive functions stop at RECURSIVE_LIMIT // @@ -798,6 +832,90 @@ static void test_decision_depth(testing & t) { }); } +// +// server_decision_context: the joint head reads media grouped by kind (images, then audio, then video) +// + +static std::vector make_wav_16khz(size_t n_samples) { + std::vector b(44 + 2 * n_samples, 0); + const auto put32 = [&](size_t o, uint32_t v) { b[o] = v; b[o + 1] = v >> 8; b[o + 2] = v >> 16; b[o + 3] = v >> 24; }; + const auto put16 = [&](size_t o, uint16_t v) { b[o] = v; b[o + 1] = v >> 8; }; + memcpy(b.data(), "RIFF", 4); + put32(4, 36 + (uint32_t) (2 * n_samples)); + memcpy(b.data() + 8, "WAVEfmt ", 8); + put32(16, 16); // fmt chunk size + put16(20, 1); // PCM + put16(22, 1); // channels + put32(24, 16000); // sample rate + put32(28, 16000 * 2); // byte rate + put16(32, 2); // block align + put16(34, 16); // bits per sample + memcpy(b.data() + 36, "data", 4); + put32(40, (uint32_t) (2 * n_samples)); + return b; +} + +static void test_decision_media_order(testing & t) { + const mtmd_helper_init_opt opt = mtmd_helper_init_opt_default(); + + const std::vector png = { // a 1x1 grayscale PNG + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x7e, 0x9b, + 0x55, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0x60, 0x00, 0x00, 0x00, + 0x02, 0x00, 0x01, 0x48, 0xaf, 0xa4, 0x71, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, + 0x42, 0x60, 0x82, + }; + const raw_buffer image = png; + const raw_buffer audio_a = make_wav_16khz(16); + const raw_buffer audio_b = make_wav_16khz(32); + + // the detector recognizes the buffers, so the test exercises the real grouping + mtmd_helper_media_meta meta; + t.assert_true("image detected", mtmd_helper_get_media_meta(image.data(), image.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_IMAGE); + t.assert_true("audio detected", mtmd_helper_get_media_meta(audio_a.data(), audio_a.size(), opt, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_AUDIO); + + // images come first even when the request lists audio first + const std::vector grouped = decision_order_media({audio_a, image}, opt); + t.assert_equal("count", (size_t) 2, grouped.size()); + t.assert_true("image first", grouped[0] == image); + t.assert_true("audio last", grouped[1] == audio_a); + + // the order within a kind is kept + const std::vector stable = decision_order_media({audio_b, image, audio_a}, opt); + t.assert_equal("stable count", (size_t) 3, stable.size()); + t.assert_true("stable image first", stable[0] == image); + t.assert_true("stable audio order", stable[1] == audio_b && stable[2] == audio_a); + + // a decoder that reads any buffer as a video, the built-in one needs ffmpeg + static int decoder_state = 0; + mtmd_helper_video_decoder decoder = {}; + decoder.open = [](void *, const char *, const unsigned char *, size_t, mtmd_helper_video_stream_info * info) -> void * { + *info = {16, 16, 2.0f, 4, 2.0f}; + return &decoder_state; + }; + decoder.read_frame = [](void *, unsigned char *, uint32_t, uint32_t) { return false; }; + decoder.close = [](void *) {}; + + mtmd_helper_init_opt opt_video = opt; + opt_video.video_params.decoder = &decoder; + + const raw_buffer video = {'v', 'i', 'd', 'e', 'o'}; + t.assert_true("video detected", mtmd_helper_get_media_meta(video.data(), video.size(), opt_video, &meta) == 0 && meta.type == MTMD_HELPER_MEDIA_TYPE_VIDEO); + + const std::vector with_video = decision_order_media({video, audio_a, image}, opt_video); + t.assert_true("video last", with_video.size() == 3 && with_video[0] == image && with_video[1] == audio_a && with_video[2] == video); + + // cloudflare-clef-omni + std::string error; + try { + decision_order_media({image, video}, opt_video, false); + } catch (const std::invalid_argument & e) { + error = e.what(); + } + t.assert_true("video rejected: " + error, error.find("video input is not supported") != std::string::npos); + t.assert_equal("no video, nothing rejected", (size_t) 2, decision_order_media({audio_a, image}, opt_video, false).size()); +} + // DRY sequence breakers // @@ -992,7 +1110,9 @@ int main(int argc, char ** argv) { t.test("rerank_template", test_rerank_template); t.test("decision_class_scores", test_decision_class_scores); t.test("decision_ocr_jev_validation", test_decision_ocr_jev_validation); + t.test("decision_media_fields", test_decision_media_fields); t.test("decision_depth", test_decision_depth); + t.test("decision_media_order", test_decision_media_order); t.test("glob_match", test_glob_match); t.test("dry_sequence_breakers", test_dry_sequence_breakers); t.test("stop_strings", test_stop_strings); diff --git a/tools/server/README.md b/tools/server/README.md index f690d7c04843..6dda4de48b77 100644 --- a/tools/server/README.md +++ b/tools/server/README.md @@ -1932,6 +1932,8 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo `images`: Optional. An alias of `files`. +`audio`: Optional. An alias of `files`. + `questions`: An object that maps a question id to a question. Each question has these fields: - `type`: One of `choice`, `score`, `noul`. @@ -1941,11 +1943,11 @@ Follows the [TypeSafe API](https://docs.typesafe.ai/api), streaming is not suppo - `score`: An array of 2 to 10 level descriptions, lowest level first. - `noul`: Optional. An object with the descriptions of `true` and `false`. -The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef, which reads all the questions in one prompt and decides them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass). +The questions of a request are answered independently, an answer does not depend on the other questions. The exceptions are clef and cloudflare-clef-omni, which read all the questions in one prompt and decide them jointly, and lfm3-d1 and lfm3-d1-omni, which read up to 16 questions after the state in one pass, as the models were trained (requests with a spoken question read one question per pass). -The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with. +The number of options of a `choice` question is limited by the model, for example: 52 for openjev, 255 for granite-switch, laya, clef, cloudflare-clef-omni, pplx-decider, vllm-decision2, vllm-d3, lfm2-d1, lfm2-d1-omni and h2o-lightning, 2 for openbmb-minicpm-ocr-jev. For laya, long questions and options are truncated to the token budget the model was trained with. -For laya, clef, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`. +For laya, clef, cloudflare-clef-omni, vllm-d3, lfm2-d1-omni, lfm3-d1 and lfm3-d1-omni, the whole prompt is evaluated in one batch: it must fit in `--ubatch-size`. An lfm2-d1-omni prompt is cut to 16384 tokens. For vllm-decision2, the options of a question and the end of the prompt must fit in one batch. An h2o-lightning state longer than 32000 tokens keeps its first and last 16000 tokens. A server that runs clef or cloudflare-clef-omni only serves this endpoint, text generation is not available. A decision model that is also a text model, such as granite-switch, serves both and reports `["text", "decisions"]`. openbmb-minicpm-ocr-jev answers one fixed question: is an OCR text, rendered as an image, consistent with the original image? `state` is the OCR text, as a string, special tokens written in it are escaped. `files` (or `images`) has exactly 2 images: the original, then the rendered one, both are required. The request has one question and no `instructions`: the task is part of the prompt of the model, so a request that sends one is rejected. It is either a `choice` with the `criteria` `{"0": null, "1": null}`, where `1` means consistent, or a `noul` without `criteria`, which returns the probability of `1`. The model has no LM head, so text generation is not available. @@ -1953,14 +1955,16 @@ Its prompt carries two images, so it is much longer than a text-only one: size t *Image input:* -Image input needs a model that supports it (for example: openjev, clef, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`. +Image input needs a model that supports it (for example: openjev, clef, cloudflare-clef-omni, pplx-decider, vllm-d3, lfm2-d1, lfm2-d1-omni, h2o-lightning, openbmb-minicpm-ocr-jev) and its multimodal projector, see `--mmproj`. Images can be given in two ways, and both can be used in the same request: -- The `files` field, or its alias `images`. +- The `files` field, or its aliases `images` and `audio`. - A `state` made of chat messages, either an array of messages or an object with a `messages` array. An `image_url` part in the `content` of a message is taken as an image, in the same format as chat completions. Only data URLs are accepted. For lfm2-d1-omni, an `input_audio` part is taken as an audio clip, as base64 data. -All the images are placed before the state in the prompt, the ones from `files` and `images` first. The image parts are removed from the state. +All the images are placed before the state in the prompt, the ones from `files`, `images` and `audio` first. The image parts are removed from the state. + +For clef and cloudflare-clef-omni, the files are grouped by kind, as the models were trained: images, then audio clips, then videos. A video is rejected by cloudflare-clef-omni. *Response:* diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index 18564b6e47cb..5097c60ca0d3 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -241,6 +241,7 @@ std::vector server_model_output_modalities(common_decision_type dec case COMMON_DECISION_TYPE_MINICPM_OCR_JEV: case COMMON_DECISION_TYPE_LFM3_D1: case COMMON_DECISION_TYPE_LFM3_D1_OMNI: + case COMMON_DECISION_TYPE_CLEF_OMNI: out = {"decisions"}; break; case COMMON_DECISION_TYPE_GRANITE_SWITCH: diff --git a/tools/server/server-decision.cpp b/tools/server/server-decision.cpp index 32eeec361010..0db4d53c0c28 100644 --- a/tools/server/server-decision.cpp +++ b/tools/server/server-decision.cpp @@ -153,7 +153,7 @@ void server_decision_context::init(const llama_model * model) { throw std::runtime_error("decision model has no valid max_head_tokens"); } n_options_max = 255; - } else if (model_type == COMMON_DECISION_TYPE_CLEF) { + } else if (model_type == COMMON_DECISION_TYPE_CLEF || model_type == COMMON_DECISION_TYPE_CLEF_OMNI) { n_options_max = 255; noul_true_first = true; choice_sorted = true; @@ -410,6 +410,40 @@ static void decision_load_audio(const json & data, std::vector & fil handle_media(files, data.get(), ""); } +// the joint head reads media grouped by kind, as the model was trained: images, then audio, then video +std::vector decision_order_media(const std::vector & files, const mtmd_helper_init_opt & init_opt, bool allow_video) { + auto rank_of = [&](const raw_buffer & file) -> int { + mtmd_helper_media_meta meta; + if (mtmd_helper_get_media_meta(file.data(), file.size(), init_opt, &meta) == 0) { + switch (meta.type) { + case MTMD_HELPER_MEDIA_TYPE_IMAGE: return 0; + case MTMD_HELPER_MEDIA_TYPE_AUDIO: return 1; + case MTMD_HELPER_MEDIA_TYPE_VIDEO: + if (!allow_video) { + throw std::invalid_argument("video input is not supported by this model"); + } + return 2; + default: break; + } + } + return 3; // mtmd reports the error when the prompt is tokenized + }; + + std::vector> ranked; + ranked.reserve(files.size()); + for (const auto & file : files) { + ranked.emplace_back(rank_of(file), &file); + } + std::stable_sort(ranked.begin(), ranked.end(), [](const auto & a, const auto & b) { return a.first < b.first; }); + + std::vector out; + out.reserve(files.size()); + for (const auto & entry : ranked) { + out.push_back(*entry.second); + } + return out; +} + json server_decision_context::parse_state(const json & body, std::vector & files) const { if (type == COMMON_DECISION_TYPE_MINICPM_OCR_JEV && !body.at("state").is_string()) { throw std::invalid_argument("\"state\" must be the OCR text"); @@ -417,8 +451,8 @@ json server_decision_context::parse_state(const json & body, std::vector media = decision_order_media(files, init_opt, type != COMMON_DECISION_TYPE_CLEF_OMNI); + + // the template puts one media marker per file json images = json::array(); - if (!files.empty()) { + if (!media.empty()) { inp = decision_replace_text(inp, get_media_marker(), " "); - for (size_t i = 0; i < files.size(); i++) { + for (size_t i = 0; i < media.size(); i++) { images.push_back(get_media_marker()); } } @@ -1579,7 +1617,7 @@ void server_decision_context::fill_task_joint( size_t i_piece = 0; task.tokens = server_tokens(llama_tokens(), false); - if (!files.empty()) { + if (!media.empty()) { // the text before the images is tokenized with them, a vision token separates the pieces anyway std::string head; while (i_piece < pieces.size() && head.find(get_media_marker()) == std::string::npos) { @@ -1588,7 +1626,7 @@ void server_decision_context::fill_task_joint( if (head.find(get_media_marker()) == std::string::npos || head.find(CLEF_MARKER) != std::string::npos) { throw invalid; } - task.tokens = process_mtmd_prompt(mctx, head, files, init_opt); + task.tokens = process_mtmd_prompt(mctx, head, media, init_opt); task.decision.order.resize(task.tokens.size(), LLAMA_DECISION_ORDER_NONE); } diff --git a/tools/server/server-decision.h b/tools/server/server-decision.h index 175aa46ebac3..a02c7b9eed1a 100644 --- a/tools/server/server-decision.h +++ b/tools/server/server-decision.h @@ -56,7 +56,7 @@ struct server_decision_context { // true if all the questions of a request go in one prompt, see fill_task_joint() bool is_joint() const { - return type == COMMON_DECISION_TYPE_CLEF; + return type == COMMON_DECISION_TYPE_CLEF || type == COMMON_DECISION_TYPE_CLEF_OMNI; } bool is_lfm3_d1() const { @@ -76,6 +76,7 @@ struct server_decision_context { case COMMON_DECISION_TYPE_MINICPM_OCR_JEV: case COMMON_DECISION_TYPE_LFM3_D1: case COMMON_DECISION_TYPE_LFM3_D1_OMNI: + case COMMON_DECISION_TYPE_CLEF_OMNI: return true; default: return false; @@ -96,7 +97,7 @@ struct server_decision_context { json prepare_state(const json & state) const; // returns the state without its images, they are appended to files in order - // images come from "files" (alias "images") and from the image_url and input_audio parts of a state made of chat messages + // images come from "files" (aliases "images" and "audio") and from the image_url and input_audio parts of a state made of chat messages // an image can be an audio clip if the model supports it json parse_state(const json & body, std::vector & files) const; @@ -207,5 +208,9 @@ struct server_decision_context { // note: the order of the tasks is preserved std::vector server_decision_group_tasks(std::vector && tasks, size_t n_slots); +// order the media as the joint head reads them: images, then audio, then video +// throw std::invalid_argument on a video if allow_video is false +std::vector decision_order_media(const std::vector & files, const mtmd_helper_init_opt & init_opt, bool allow_video = true); + // write "<|name|>" with U+00A6 in place of "|", so text from the request is not parsed as special tokens std::string server_decision_escape_special_tokens(const std::string & text); From 08dc1cea9e96f2f6fab5ba0dcb29d5f2b802090d Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Wed, 2 Dec 2026 01:53:54 +0100 Subject: [PATCH 326/401] llama : refactor decision model api (#33305) * non-overlap version * wip * drop ggml_prec_set --- common/common.cpp | 8 +- common/common.h | 5 +- src/llama-batch.cpp | 137 ++++++++++++++++++++++++------- src/llama-batch.h | 40 ++++++--- src/llama-context.cpp | 65 ++++++++++++++- src/llama-context.h | 7 ++ src/llama-ext.h | 37 ++++++--- src/llama-graph.cpp | 77 ++++++++++++++--- src/llama-graph.h | 14 ++++ src/llama-kv-cache-dsv4.cpp | 5 +- src/models/clef.cpp | 76 ++++++++++------- src/models/models.h | 3 +- src/models/vllm-decision2.cpp | 87 ++++++++++++-------- tests/test-batch-alloc.cpp | 76 +++++++++++++++++ tools/server/server-context.cpp | 56 +++++++------ tools/server/server-decision.cpp | 36 ++++---- tools/server/server-task.h | 18 ++-- 17 files changed, 560 insertions(+), 187 deletions(-) diff --git a/common/common.cpp b/common/common.cpp index da7657d13399..9ea6b51ee99d 100644 --- a/common/common.cpp +++ b/common/common.cpp @@ -2338,11 +2338,11 @@ llama_batch_ext * common_batch::get_sub_batch(int32_t off, int32_t n) { if (t.state_row >= 0 && !llama_batch_ext_set_embd_state_row(res, idx, t.state_row)) { GGML_ABORT("%s: failed to set the state row of the entry at index %d\n", __func__, i); } - if (t.decision_order != 0) { - llama_batch_ext_set_decision_order(res, idx, (llama_decision_order) t.decision_order); + if (t.span != 0 && !(llama_batch_ext_set_pool_span(res, idx, t.span) && llama_batch_ext_set_pool_span_type(res, t.span, (llama_pool_span_type) t.span_type))) { + GGML_ABORT("%s: failed to set the span of the entry at index %d\n", __func__, i); } - if (t.decision_group != 0 && !llama_batch_ext_set_decision_group(res, idx, t.decision_group)) { - GGML_ABORT("%s: failed to set the decision group of the entry at index %d\n", __func__, i); + if (t.attn_scope != 0 && !llama_batch_ext_set_attn_scope(res, idx, t.attn_scope)) { + GGML_ABORT("%s: failed to set the attention scope of the entry at index %d\n", __func__, i); } } diff --git a/common/common.h b/common/common.h index 1d8d57d714a3..e5f4fb2afde1 100644 --- a/common/common.h +++ b/common/common.h @@ -1123,8 +1123,9 @@ struct common_batch { llama_embd embd; // non-owning view of the data passed to add_embd()/set_embd(), data == NULL if none llama_embd state; // non-owning view of the data passed to set_embd_state(), data == NULL if none std::vector seq_ids_extra; // see add_seq() - int32_t decision_order = 0; // see llama_batch_ext_set_decision_order() - int32_t decision_group = 0; // see llama_batch_ext_set_decision_group() + int32_t span = 0; // see llama_batch_ext_set_pool_span() + int32_t span_type = 0; // see llama_batch_ext_set_pool_span_type() + int32_t attn_scope = 0; // see llama_batch_ext_set_attn_scope() int32_t embd_row = -1; // see add_embd_row(), -1 if none int32_t state_row = -1; // see set_embd_state_row(), -1 if none }; diff --git a/src/llama-batch.cpp b/src/llama-batch.cpp index 3391cb49e858..b13a81a970a5 100644 --- a/src/llama-batch.cpp +++ b/src/llama-batch.cpp @@ -12,6 +12,27 @@ #include #include +std::vector llama_ubatch_get_spans(const llama_ubatch & ubatch) { + std::vector res; + if (ubatch.span == nullptr) { + return res; + } + + const int32_t n_tokens = ubatch.n_tokens; + for (int32_t i = 0; i < n_tokens;) { + int32_t end = i + 1; + while (end < n_tokens && ubatch.span[end] == ubatch.span[i]) { + end++; + } + if (ubatch.span[i] != 0) { + res.push_back({ ubatch.span[i], ubatch.span_type[i], i, end }); + } + i = end; + } + + return res; +} + llama_batch_allocr::llama_batch_allocr(uint32_t n_pos_per_embd, bool allow_mixed) : n_pos_per_embd(n_pos_per_embd), allow_mixed(allow_mixed) { const char * LLAMA_BATCH_DEBUG = getenv("LLAMA_BATCH_DEBUG"); debug = LLAMA_BATCH_DEBUG ? atoi(LLAMA_BATCH_DEBUG) : 0; @@ -255,16 +276,44 @@ bool llama_batch_allocr::init( // kept empty if no entry has one for (int32_t i = 0; i < n_tok; ++i) { - if (batch_inp.tokens[i].decision_order != 0) { - decision_order.resize(n_tok, 0); - decision_order[i] = batch_inp.tokens[i].decision_order; + const auto & tok = batch_inp.tokens[i]; + if (tok.span != 0) { + span.resize(n_tok, 0); + span_type.resize(n_tok, LLAMA_POOL_SPAN_TYPE_DEFAULT); + span[i] = tok.span; + const auto it = batch_inp.span_types.find(tok.span); + if (it != batch_inp.span_types.end()) { + span_type[i] = it->second; + } } - if (batch_inp.tokens[i].decision_group != 0) { - decision_group.resize(n_tok, 0); - decision_group[i] = batch_inp.tokens[i].decision_group; + if (tok.attn_scope != 0) { + attn_scope.resize(n_tok, 0); + attn_scope[i] = tok.attn_scope; } } + // a span is one run of entries in one sequence + if (!span.empty()) { + std::unordered_set seen; + for (int32_t i = 0; i < n_tok; ++i) { + if (span[i] == 0) { + continue; + } + if (i > 0 && span[i - 1] == span[i]) { + if (batch_inp.tokens[i].seq_ids != batch_inp.tokens[i - 1].seq_ids) { + LLAMA_LOG_ERROR("%s: the entries of span %d are not in the same sequence\n", __func__, span[i]); + return false; + } + continue; + } + if (!seen.insert(span[i]).second) { + LLAMA_LOG_ERROR("%s: the entries of span %d are not next to each other\n", __func__, span[i]); + return false; + } + } + n_spans = seen.size(); + } + // // set up the internal llama_batch to point to our owned arrays // @@ -356,8 +405,9 @@ bool llama_batch_allocr::init( /*.seq_idx =*/ this->seq_idx.data(), /*.output =*/ batch.logits, /*.type =*/ is_embd_vec.empty() ? nullptr : is_embd_vec.data(), - /*.decision_order =*/ decision_order.empty() ? nullptr : decision_order.data(), - /*.decision_group =*/ decision_group.empty() ? nullptr : decision_group.data(), + /*.span =*/ span.empty() ? nullptr : span.data(), + /*.span_type =*/ span_type.empty() ? nullptr : span_type.data(), + /*.attn_scope =*/ attn_scope.empty() ? nullptr : attn_scope.data(), /*.data =*/ {}, }; @@ -583,8 +633,9 @@ llama_ubatch llama_batch_allocr::ubatch_reserve(uint32_t n_seq_tokens, uint32_t /*.seq_idx =*/ udata->seq_idx.data(), /*.output =*/ udata->output.data(), /*.type =*/ nullptr, - /*.decision_order =*/ nullptr, - /*.decision_group =*/ nullptr, + /*.span =*/ nullptr, + /*.span_type =*/ nullptr, + /*.attn_scope =*/ nullptr, /*.data =*/ std::move(udata), }; @@ -607,6 +658,14 @@ uint32_t llama_batch_allocr::get_n_used() const { return n_used; } +bool llama_batch_allocr::has_spans() const { + return !span.empty(); +} + +uint32_t llama_batch_allocr::get_n_spans() const { + return n_spans; +} + std::vector & llama_batch_allocr::get_out_ids() { return out_ids; } @@ -892,8 +951,10 @@ void llama_batch_allocr::clear() { seq_id .clear(); seq_id_unq .clear(); output .clear(); - decision_order.clear(); - decision_group.clear(); + span .clear(); + n_spans = 0; + span_type .clear(); + attn_scope .clear(); for (auto & cur : seq_pos) { cur.clear(); @@ -949,8 +1010,9 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector & idxs, u udata->seq_idx .resize(LLAMA_MAX_SEQ, -1); udata->output .resize(n_tokens); udata->type .resize(mixed ? n_tokens : 0); - udata->decision_order.resize(decision_order.empty() ? 0 : n_tokens); - udata->decision_group.resize(decision_group.empty() ? 0 : n_tokens); + udata->span .resize(span.empty() ? 0 : n_tokens); + udata->span_type .resize(span.empty() ? 0 : n_tokens); + udata->attn_scope.resize(attn_scope.empty() ? 0 : n_tokens); udata->batch_idxs = idxs; udata->seq_id_data.reserve(n_tokens); @@ -989,11 +1051,12 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector & idxs, u udata->n_seq_id[i] = batch.n_seq_id[idxs[i]]; udata->output[i] = batch.logits[idxs[i]]; - if (!decision_order.empty()) { - udata->decision_order[i] = decision_order[idxs[i]]; + if (!span.empty()) { + udata->span[i] = span[idxs[i]]; + udata->span_type[i] = span_type[idxs[i]]; } - if (!decision_group.empty()) { - udata->decision_group[i] = decision_group[idxs[i]]; + if (!attn_scope.empty()) { + udata->attn_scope[i] = attn_scope[idxs[i]]; } for (int s = 0; s < udata->n_seq_id[i]; ++s) { @@ -1040,8 +1103,9 @@ llama_ubatch llama_batch_allocr::ubatch_add(const std::vector & idxs, u /*.seq_idx =*/ udata->seq_idx.data(), /*.output =*/ udata->output.data(), /*.type =*/ mixed ? udata->type.data() : nullptr, - /*.decision_order =*/ udata->decision_order.empty() ? nullptr : udata->decision_order.data(), - /*.decision_group =*/ udata->decision_group.empty() ? nullptr : udata->decision_group.data(), + /*.span =*/ udata->span.empty() ? nullptr : udata->span.data(), + /*.span_type =*/ udata->span_type.empty() ? nullptr : udata->span_type.data(), + /*.attn_scope =*/ udata->attn_scope.empty() ? nullptr : udata->attn_scope.data(), /*.data =*/ std::move(udata), }; @@ -1261,6 +1325,7 @@ void llama_batch_ext::clear() { tokens.clear(); embd .clear(); state .clear(); + span_types.clear(); n_embd = 0; } @@ -1438,19 +1503,27 @@ bool llama_batch_ext::set_output(int32_t idx, bool output_last) { return true; } -bool llama_batch_ext::set_decision_order(int32_t idx, int32_t order) { - if (idx < 0 || idx >= (int32_t) tokens.size()) { +bool llama_batch_ext::set_span(int32_t idx, int32_t span) { + if (idx < 0 || idx >= (int32_t) tokens.size() || span < 0) { + return false; + } + tokens[idx].span = span; + return true; +} + +bool llama_batch_ext::set_span_type(int32_t span, int32_t type) { + if (span <= 0 || type < LLAMA_POOL_SPAN_TYPE_DEFAULT || type > LLAMA_POOL_SPAN_TYPE_DECISION_OPTION) { return false; } - tokens[idx].decision_order = order; + span_types[span] = type; return true; } -bool llama_batch_ext::set_decision_group(int32_t idx, int32_t group) { - if (idx < 0 || idx >= (int32_t) tokens.size() || group < 0) { +bool llama_batch_ext::set_attn_scope(int32_t idx, int32_t scope) { + if (idx < 0 || idx >= (int32_t) tokens.size() || scope < 0) { return false; } - tokens[idx].decision_group = group; + tokens[idx].attn_scope = scope; return true; } @@ -1533,12 +1606,16 @@ bool llama_batch_ext_set_output_logits(llama_batch_ext * batch, int32_t idx, boo return batch->set_output(idx, value); } -bool llama_batch_ext_set_decision_order(llama_batch_ext * batch, int32_t idx, llama_decision_order order) { - return batch->set_decision_order(idx, order); +bool llama_batch_ext_set_pool_span(llama_batch_ext * batch, int32_t idx, int32_t span) { + return batch->set_span(idx, span); +} + +bool llama_batch_ext_set_pool_span_type(llama_batch_ext * batch, int32_t span, llama_pool_span_type type) { + return batch->set_span_type(span, type); } -bool llama_batch_ext_set_decision_group(llama_batch_ext * batch, int32_t idx, int32_t group) { - return batch->set_decision_group(idx, group); +bool llama_batch_ext_set_attn_scope(llama_batch_ext * batch, int32_t idx, int32_t scope) { + return batch->set_attn_scope(idx, scope); } // llama_batch_compat diff --git a/src/llama-batch.h b/src/llama-batch.h index e6f4be6a28a0..f46bb65dfa4a 100644 --- a/src/llama-batch.h +++ b/src/llama-batch.h @@ -60,8 +60,9 @@ struct llama_ubatch { int32_t * seq_idx; // [LLAMA_MAX_SEQ] | - | seq_idx int8_t * output; // [n_tokens] | i | - int8_t * type; // [n_tokens] | i | - (mixed ubatch only, 0 - token, 1 - embd) - int32_t * decision_order; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_decision_order() - int32_t * decision_group; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_decision_group() + int32_t * span; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_pool_span() + int32_t * span_type; // [n_tokens], NULL if no entry has a span + int32_t * attn_scope; // [n_tokens], NULL if no entry has one, see llama_batch_ext_set_attn_scope() struct data_t { std::vector token; @@ -77,8 +78,9 @@ struct llama_ubatch { std::vector output; std::vector type; std::vector batch_idxs; // original batch index for each token - std::vector decision_order; - std::vector decision_group; + std::vector span; + std::vector span_type; + std::vector attn_scope; std::vector seq_id_data; }; @@ -87,6 +89,17 @@ struct llama_ubatch { std::shared_ptr data; }; +// a span of a ubatch, see llama_batch_ext_set_pool_span() +struct llama_ubatch_span { + int32_t id; + int32_t type; // see llama_pool_span_type + int32_t start; // [start, end) in ubatch token indices + int32_t end; +}; + +// the spans of the ubatch, in the order of their first token +std::vector llama_ubatch_get_spans(const llama_ubatch & ubatch); + // crash if a mixed ubatch reaches code that expects only tokens or only embd #define ASSERT_EMBD_OR_TOKEN(ubatch) GGML_ASSERT(!(ubatch).is_mixed() && "mixed token/embd ubatch is not supported here") @@ -122,14 +135,15 @@ struct llama_batch_ext { int32_t embd_row = -1; // row of ctx_other's layer input device buffer used as embd, -1 if none int32_t state_row = -1; // row of ctx_state_src's h_nextn device buffer used as state, -1 if none bool output = false; // TODO: have dedicated output flags - int32_t decision_order = 0; // see llama_batch_ext_set_decision_order() - int32_t decision_group = 0; // see llama_batch_ext_set_decision_group() + int32_t span = 0; // see llama_batch_ext_set_pool_span() + int32_t attn_scope = 0; // see llama_batch_ext_set_attn_scope() std::unordered_set seq_ids; std::array pos = {0, 0, 0, 0}; }; std::vector tokens; std::vector embd; std::vector state; + std::unordered_map span_types; // span id -> llama_pool_span_type, default if missing llama_batch_ext(llama_context * ctx); @@ -157,8 +171,9 @@ struct llama_batch_ext { bool set_token_state_row(int32_t idx, int32_t row); bool set_token_pos(int32_t idx, const llama_pos * pos_in); bool set_output(int32_t idx, bool output_last); - bool set_decision_order(int32_t idx, int32_t order); - bool set_decision_group(int32_t idx, int32_t group); + bool set_span(int32_t idx, int32_t span); + bool set_span_type(int32_t span, int32_t type); + bool set_attn_scope(int32_t idx, int32_t scope); }; // a helper for sanitizing, fulfilling and splitting a batch @@ -178,6 +193,9 @@ class llama_batch_allocr { uint32_t get_n_outputs() const; uint32_t get_n_used() const; + bool has_spans() const; + uint32_t get_n_spans() const; + // the array of output indices in the order they were encountered during the ubatch splitting std::vector & get_out_ids(); @@ -244,8 +262,10 @@ class llama_batch_allocr { std::vector seq_id_unq; std::vector seq_idx; std::vector output; - std::vector decision_order; // empty if no entry has one - std::vector decision_group; // empty if no entry has one + std::vector span; // empty if no entry has one + uint32_t n_spans = 0; + std::vector span_type; // empty if no entry has a span + std::vector attn_scope; // empty if no entry has one using pos_set_t = std::set; using seq_cpl_t = std::vector; diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 88cc05630092..f6af3ac99a87 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -1168,6 +1168,30 @@ float * llama_context::get_embeddings_seq(llama_seq_id seq_id) { return it->second.data(); } +float * llama_context::get_embeddings_span(int32_t span) { + auto it = embd_span.find(span); + if (it == embd_span.end()) { + return nullptr; + } + + return it->second.data(); +} + +void llama_context::output_embd_spans(const llama_ubatch & ubatch, ggml_tensor * t_embd_span) { + ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd_span); + GGML_ASSERT(backend_embd != nullptr); + + const auto spans = llama_ubatch_get_spans(ubatch); + GGML_ASSERT((int64_t) spans.size() <= t_embd_span->ne[1]); + + const size_t n_row = t_embd_span->ne[0]; + for (size_t s = 0; s < spans.size(); ++s) { + auto & out = embd_span[spans[s].id]; + out.resize(n_row); + ggml_backend_tensor_get_async(backend_embd, t_embd_span, out.data(), s*n_row*sizeof(float), n_row*sizeof(float)); + } +} + float * llama_context::get_embeddings_nextn() { output_reorder(); @@ -1892,6 +1916,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { return -1; } + if (llm_graph_pools_spans(cparams) && balloc->get_n_spans() > LLAMA_MAX_POOL_SPANS) { + LLAMA_LOG_ERROR("%s: too many spans to pool, n_spans = %u > %d\n", __func__, balloc->get_n_spans(), LLAMA_MAX_POOL_SPANS); + return -1; + } + const uint32_t n_tokens = balloc->get_n_tokens(); // [TAG_NO_CACHE_PAD] @@ -1907,10 +1936,11 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { // TODO: this clear of the buffer can easily be forgotten - need something better // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { + if (!embd_seq.empty() || !embd_span.empty()) { synchronize(); } embd_seq.clear(); + embd_span.clear(); if (t_compute_start_us == 0) { t_compute_start_us = ggml_time_us(); @@ -1960,6 +1990,8 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { auto * t_embd = res->get_embd_pooled() ? res->get_embd_pooled() : res->get_embd(); auto * t_h_nextn = cparams.embeddings_nextn ? res->get_h_nextn() : nullptr; + auto * t_embd_span = ubatch.span ? res->get_embd_span() : nullptr; + // extract logits if (logits.data && t_logits) { ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits); @@ -1970,7 +2002,9 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } // extract embeddings - if (embd.data && t_embd) { + if (embd.data && t_embd_span) { + output_embd_spans(ubatch, t_embd_span); + } else if (embd.data && t_embd) { ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd); GGML_ASSERT(backend_embd != nullptr); @@ -2204,14 +2238,27 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { GGML_ASSERT(n_tokens_all <= cparams.n_batch); + if (llm_graph_pools_spans(cparams) && balloc->get_n_spans() > LLAMA_MAX_POOL_SPANS) { + LLAMA_LOG_ERROR("%s: too many spans to pool, n_spans = %u > %d\n", __func__, balloc->get_n_spans(), LLAMA_MAX_POOL_SPANS); + return -1; + } + + // a span cannot be split over two ubatches + if (output_all && balloc->has_spans() && n_tokens_all > cparams.n_ubatch) { + LLAMA_LOG_ERROR("%s: a batch with spans is read in one pass, n_tokens = %u > n_ubatch = %u, increase n_ubatch (-ub)\n", + __func__, n_tokens_all, cparams.n_ubatch); + return -1; + } + GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); // TODO: this clear of the buffer can easily be forgotten - need something better // sync first so any in-flight async copies into embd_seq complete before it is freed - if (!embd_seq.empty()) { + if (!embd_seq.empty() || !embd_span.empty()) { synchronize(); } embd_seq.clear(); + embd_span.clear(); if (t_compute_start_us == 0) { t_compute_start_us = ggml_time_us(); @@ -2388,6 +2435,8 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { t_embd = res->get_embd_pooled(); } + auto * t_embd_span = cparams.embeddings && ubatch.span ? res->get_embd_span() : nullptr; + // extract logits if (logits.data && t_logits && n_outputs > 0 && needs_raw_logits(ubatch, sampling.samplers)) { ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits); @@ -2404,7 +2453,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { } // extract embeddings - if (embd.data && t_embd && n_outputs > 0) { + if (embd.data && t_embd_span) { + output_embd_spans(ubatch, t_embd_span); + } else if (embd.data && t_embd && n_outputs > 0) { ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd); GGML_ASSERT(backend_embd != nullptr); @@ -4692,6 +4743,12 @@ float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) { return ctx->get_embeddings_seq(seq_id); } +float * llama_get_embeddings_pool_span(llama_context * ctx, int32_t span) { + ctx->synchronize(); + + return ctx->get_embeddings_span(span); +} + void llama_set_embeddings_nextn(llama_context * ctx, bool value, bool masked) { ctx->set_embeddings_nextn(value, masked); } diff --git a/src/llama-context.h b/src/llama-context.h index 3e3921c7df28..e7ababe51770 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -87,6 +87,7 @@ struct llama_context { float * get_embeddings(); float * get_embeddings_ith(int32_t i); float * get_embeddings_seq(llama_seq_id seq_id); + float * get_embeddings_span(int32_t span); float * get_embeddings_nextn(); float * get_embeddings_nextn_ith(int32_t i); @@ -251,6 +252,9 @@ struct llama_context { void output_reorder(); + // copy t_embd_span rows to embd_span, see llama_ubatch_get_spans() + void output_embd_spans(const llama_ubatch & ubatch, ggml_tensor * t_embd_span); + // map the output row index `i` to batch index int64_t output_resolve_row(int32_t i) const; @@ -386,6 +390,9 @@ struct llama_context { // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE std::map> embd_seq; + // span embeddings output, see llama_get_embeddings_pool_span() + std::map> embd_span; + // reuse the batch_allocr to avoid unnecessary memory allocations std::unique_ptr balloc; diff --git a/src/llama-ext.h b/src/llama-ext.h index a77b2f40948a..2dbe9fa2d7a1 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -125,23 +125,34 @@ LLAMA_API std::vector llama_memory_get_buffers(const llam // Useful for testing purposes. LLAMA_API void llama_model_set_attn_rot(struct llama_model * model, bool value); -// Marks the entries that a decision head (clef, vllm-decision2) reads, the default is 0 +// span id of an entry, 0 (default) = no span +// a span is one run of entries in one sequence, a batch with spans must fit in one ubatch +// with mean, cls or last pooling, each span is pooled instead of each sequence +// note: spans cannot overlap +// to pool overlapping or disjoint ranges, cut them into spans, then join the results: +// mean = sum(n_tokens(span) * mean(span)) / sum(n_tokens(span)), before normalization +// cls / last = result of the first / last span +LLAMA_API bool llama_batch_ext_set_pool_span(struct llama_batch_ext * batch, int32_t idx, int32_t span); + +// role of a span, read by a decision head (clef, vllm-decision2) // See https://github.com/ggml-org/llama.cpp/pull/29831 for details -// A run of entries with the same value is one span, spans must be separated by entries with value 0 // An option belongs to the last question before it -enum llama_decision_order { - LLAMA_DECISION_ORDER_NONE = 0, // not read by the head - LLAMA_DECISION_ORDER_QUESTION_NOUL = 1, // text of a question - LLAMA_DECISION_ORDER_QUESTION_CHOICE = 2, - LLAMA_DECISION_ORDER_QUESTION_SCORE = 3, - LLAMA_DECISION_ORDER_OPTION = 4, // text of an option +enum llama_pool_span_type { + LLAMA_POOL_SPAN_TYPE_DEFAULT = 0, // pooled with the context pooling type + LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_NOUL = 1, // text of a question + LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_CHOICE = 2, + LLAMA_POOL_SPAN_TYPE_DECISION_QUESTION_SCORE = 3, + LLAMA_POOL_SPAN_TYPE_DECISION_OPTION = 4, // text of an option }; -// The embeddings output has one value per entry: row i is the score of option i -LLAMA_API bool llama_batch_ext_set_decision_order(struct llama_batch_ext * batch, int32_t idx, enum llama_decision_order order); +LLAMA_API bool llama_batch_ext_set_pool_span_type(struct llama_batch_ext * batch, int32_t span, enum llama_pool_span_type type); -// Questions packed after a shared state in one sequence, contexts without memory only -// 0 (default) is the state, k > 0 the k-th question; full attention layers hide other questions from a question -LLAMA_API bool llama_batch_ext_set_decision_group(struct llama_batch_ext * batch, int32_t idx, int32_t group); +// result of a span of the last batch, nullptr if none +// n_embd_out pooled values, or 1 score for an option span of a decision head +LLAMA_API float * llama_get_embeddings_pool_span(struct llama_context * ctx, int32_t span); + +// entries packed after a shared prefix in one sequence, contexts without memory only +// 0 (default) is seen by all, scope k > 0 is hidden from other scopes in full attn layers +LLAMA_API bool llama_batch_ext_set_attn_scope(struct llama_batch_ext * batch, int32_t idx, int32_t scope); // Label of option i of a decision model (".decision.labels"), nullptr past the last one LLAMA_API const char * llama_model_decision_label(const struct llama_model * model, uint32_t i); diff --git a/src/llama-graph.cpp b/src/llama-graph.cpp index 948a02ce7233..f1bef630d116 100644 --- a/src/llama-graph.cpp +++ b/src/llama-graph.cpp @@ -431,6 +431,21 @@ bool llm_graph_input_moe_ids::can_reuse(const llm_graph_params & params) { return res; } +bool llm_graph_pools_spans(const llama_cparams & cparams) { + return cparams.embeddings && ( + cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN || + cparams.pooling_type == LLAMA_POOLING_TYPE_CLS || + cparams.pooling_type == LLAMA_POOLING_TYPE_LAST); +} + +int64_t llm_graph_n_pooled(const llama_cparams & cparams, const llama_ubatch & ubatch) { + return llm_graph_pools_spans(cparams) ? std::max(LLAMA_MAX_POOL_SPANS, cparams.n_seq_max) : ubatch.n_seqs_unq; +} + +std::vector llm_graph_pooling_spans(const llama_cparams & cparams, const llama_ubatch & ubatch) { + return llm_graph_pools_spans(cparams) ? llama_ubatch_get_spans(ubatch) : std::vector(); +} + void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) { if (cparams.embeddings && (cparams.pooling_type == LLAMA_POOLING_TYPE_MEAN || @@ -444,7 +459,19 @@ void llm_graph_input_mean::set_input(const llama_ubatch * ubatch) { GGML_ASSERT(ggml_backend_buffer_is_host(mean->buffer)); float * data = (float *) mean->data; - memset(mean->data, 0, n_tokens*n_seqs_unq*ggml_element_size(mean)); + + memset(mean->data, 0, ggml_nbytes(mean)); + + const auto spans = llm_graph_pooling_spans(cparams, *ubatch); + if (!spans.empty()) { + GGML_ASSERT((int64_t) spans.size() <= mean->ne[1]); + for (size_t s = 0; s < spans.size(); ++s) { + for (int32_t i = spans[s].start; i < spans[s].end; ++i) { + data[s*n_tokens + i] = 1.0f/float(spans[s].end - spans[s].start); + } + } + return; + } std::vector sums(n_seqs_unq, 0); for (int i = 0; i < n_tokens; i += n_seq_tokens) { @@ -490,16 +517,26 @@ void llm_graph_input_cls::set_input(const llama_ubatch * ubatch) { GGML_ASSERT(ggml_backend_buffer_is_host(cls->buffer)); uint32_t * data = (uint32_t *) cls->data; - memset(cls->data, 0, n_seqs_unq*ggml_element_size(cls)); - - std::vector target_pos(n_seqs_unq, -1); - std::vector target_row(n_seqs_unq, -1); const bool last = ( cparams.pooling_type == LLAMA_POOLING_TYPE_LAST || (cparams.pooling_type == LLAMA_POOLING_TYPE_RANK && cparams.causal_attn) ); + memset(cls->data, 0, ggml_nbytes(cls)); + + const auto spans = llm_graph_pooling_spans(cparams, *ubatch); + if (!spans.empty()) { + GGML_ASSERT((int64_t) spans.size() <= cls->ne[0]); + for (size_t s = 0; s < spans.size(); ++s) { + data[s] = last ? spans[s].end - 1 : spans[s].start; + } + return; + } + + std::vector target_pos(n_seqs_unq, -1); + std::vector target_row(n_seqs_unq, -1); + for (int i = 0; i < n_tokens; ++i) { const llama_pos pos = ubatch->pos[i]; @@ -636,28 +673,28 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { const int64_t n_kv = self_attn_mask.raw->ne[0]; const int64_t n_tokens = ubatch->n_tokens; - const auto fill_mask = [&](auto * data, int64_t ne, int n_swa, llama_swa_type swa_type, bool causal, const int32_t * group) { + const auto fill_mask = [&](auto * data, int64_t ne, int n_swa, llama_swa_type swa_type, bool causal, const int32_t * scope) { using T = std::remove_reference_t; std::fill(data, data + ne, llama_cast(-INFINITY)); for (int i1 = 0; i1 < n_tokens; ++i1) { const llama_seq_id s1 = ubatch->seq_id[i1][0]; const llama_pos p1 = ubatch->pos[i1]; - const int32_t g1 = group ? group[i1] : 0; + const int32_t g1 = scope ? scope[i1] : 0; const uint64_t idst = i1*n_kv; for (int i0 = 0; i0 < n_tokens; ++i0) { const llama_seq_id s0 = ubatch->seq_id[i0][0]; const llama_pos p0 = ubatch->pos[i0]; - const int32_t g0 = group ? group[i0] : 0; + const int32_t g0 = scope ? scope[i0] : 0; // mask different sequences if (s0 != s1) { continue; } - // mask other questions, see llama_batch_ext_set_decision_group() + // mask other scopes, see llama_batch_ext_set_attn_scope() if (g0 != 0 && g1 != 0 && g0 != g1) { continue; } @@ -688,9 +725,9 @@ void llm_graph_input_attn_no_cache::set_input(const llama_ubatch * ubatch) { GGML_ASSERT(self_attn_mask.raw); GGML_ASSERT(ggml_backend_buffer_is_host(self_attn_mask.raw->buffer)); if (self_attn_mask.raw->type == GGML_TYPE_F16) { - fill_mask((ggml_fp16_t *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->decision_group); + fill_mask((ggml_fp16_t *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->attn_scope); } else { - fill_mask((float *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->decision_group); + fill_mask((float *) self_attn_mask.raw->data, ggml_nelements(self_attn_mask.raw), 0, LLAMA_SWA_TYPE_NONE, causal, ubatch->attn_scope); } if (hparams.swa_type != LLAMA_SWA_TYPE_NONE) { @@ -1587,6 +1624,7 @@ void llm_graph_result::reset() { t_logits = nullptr; t_embd = nullptr; t_embd_pooled = nullptr; + t_embd_span = nullptr; t_h_nextn = nullptr; t_layer_inp.resize(LLAMA_MAX_LAYERS + 1); @@ -1639,6 +1677,9 @@ void llm_graph_result::set_outputs(const llm_graph_params & params) { if (t_embd_pooled != nullptr) { ggml_set_output(t_embd_pooled); } + if (t_embd_span != nullptr) { + ggml_set_output(t_embd_span); + } if (t_h_nextn != nullptr) { ggml_set_output(t_h_nextn); } @@ -3019,7 +3060,7 @@ ggml_tensor * llm_graph_context::build_inp_mean() const { auto & cur = inp->mean; - cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, ubatch.n_seqs_unq); + cur = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_tokens, llm_graph_n_pooled(cparams, ubatch)); ggml_set_input(cur); ggml_set_name(cur, "mean"); @@ -3033,7 +3074,7 @@ ggml_tensor * llm_graph_context::build_inp_cls() const { auto & cur = inp->cls; - cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_seqs_unq); + cur = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, llm_graph_n_pooled(cparams, ubatch)); ggml_set_input(cur); ggml_set_name(cur, "cls"); @@ -4517,6 +4558,8 @@ void llm_graph_context::build_dense_out( ggml_tensor * cur = res->t_embd_pooled != nullptr ? res->t_embd_pooled : res->t_embd; GGML_ASSERT(cur != nullptr && "missing t_embd_pooled/t_embd"); + const bool is_span = cur == res->t_embd_span; + if (dense_2) { cur = build_lora_mm(dense_2, cur); } @@ -4528,6 +4571,9 @@ void llm_graph_context::build_dense_out( } cb(cur, "result_embd_pooled", -1); res->t_embd_pooled = cur; + if (is_span) { + res->t_embd_span = cur; + } ggml_build_forward_expand(gf, cur); } @@ -4631,6 +4677,11 @@ void llm_graph_context::build_pooling( cb(cur, "result_embd_pooled", -1); res->t_embd_pooled = cur; + // a model with its own head has set it already + if (res->t_embd_span == nullptr && !llm_graph_pooling_spans(cparams, ubatch).empty()) { + res->t_embd_span = cur; + } + ggml_build_forward_expand(gf, cur); } diff --git a/src/llama-graph.h b/src/llama-graph.h index a9e155012bbc..4406399cc995 100644 --- a/src/llama-graph.h +++ b/src/llama-graph.h @@ -283,6 +283,18 @@ class llm_graph_input_moe_ids : public llm_graph_input_i { const int64_t n_expert; }; +// max number of spans pooled in one ubatch +#define LLAMA_MAX_POOL_SPANS 64 + +// true if the context pools spans instead of sequences +bool llm_graph_pools_spans(const llama_cparams & cparams); + +// number of pooled rows, fixed when pooling spans to avoid a realloc +int64_t llm_graph_n_pooled(const llama_cparams & cparams, const llama_ubatch & ubatch); + +// the spans to pool, empty if pooling per sequence +std::vector llm_graph_pooling_spans(const llama_cparams & cparams, const llama_ubatch & ubatch); + class llm_graph_input_mean : public llm_graph_input_i { public: llm_graph_input_mean(const llama_cparams & cparams) : cparams(cparams) {} @@ -1006,6 +1018,7 @@ class llm_graph_result { ggml_tensor * get_logits() const { return t_logits; } ggml_tensor * get_embd() const { return t_embd; } ggml_tensor * get_embd_pooled() const { return t_embd_pooled; } + ggml_tensor * get_embd_span() const { return t_embd_span; } ggml_tensor * get_h_nextn() const { return t_h_nextn; } ggml_tensor * get_layer_inp(int il) const { return t_layer_inp[il]; } @@ -1047,6 +1060,7 @@ class llm_graph_result { ggml_tensor * t_logits = nullptr; ggml_tensor * t_embd = nullptr; ggml_tensor * t_embd_pooled = nullptr; + ggml_tensor * t_embd_span = nullptr; // [n_embd_out or 1, n_pooled], one row per span ggml_tensor * t_h_nextn = nullptr; // [n_embd, n_outputs] hidden state before final output norm std::vector t_layer_inp; diff --git a/src/llama-kv-cache-dsv4.cpp b/src/llama-kv-cache-dsv4.cpp index 9c0a9b22dffc..8a8e6a424427 100644 --- a/src/llama-kv-cache-dsv4.cpp +++ b/src/llama-kv-cache-dsv4.cpp @@ -168,8 +168,9 @@ static llama_ubatch dsv4_build_raw_write_ubatch(const llama_ubatch & ubatch) { /*.seq_idx =*/ data->seq_idx.data(), /*.output =*/ data->output.data(), /*.type =*/ nullptr, - /*.decision_order =*/ nullptr, - /*.decision_group =*/ nullptr, + /*.span =*/ nullptr, + /*.span_type =*/ nullptr, + /*.attn_scope =*/ nullptr, /*.data =*/ data, }; diff --git a/src/models/clef.cpp b/src/models/clef.cpp index 13756147612a..01d1589dc069 100644 --- a/src/models/clef.cpp +++ b/src/models/clef.cpp @@ -17,7 +17,7 @@ void llama_clef_head::load_hparams(llama_model_loader & ml, llama_hparams & hpar // used by the head ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_eps); - // the output is one score per token, see llama_batch_ext_set_decision_order() + // the output is one score per span, see llama_batch_ext_set_pool_span_type() hparams.n_embd_out_impl = 1; } @@ -133,50 +133,47 @@ struct clef_spans { }; std::vector questions; std::vector
{#if line.media?.type === AttachmentType.IMAGE} - {line.media.name} {/if} {/each} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte index 1091b8dcbbb9..82b473d2226b 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallBlockReadMedia.svelte @@ -2,6 +2,7 @@ import { parseReadMediaMeta } from './parsers/read-media'; import ToolCallBlock from './ToolCallBlock.svelte'; import ToolCallTitle from './ToolCallTitle.svelte'; + import { ChatAttachmentsGalleryImage } from '#lib/components/app/index.ts'; import { ATTACHMENT_SAVED_REGEX } from '#lib/constants/agentic.constants.ts'; import { AttachmentType, MimeTypeAudio } from '#lib/enums/index.ts'; import type { @@ -70,11 +71,10 @@
{:else}
- {readMediaMeta?.fileName
{/if} diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte index ebc3460cd4be..a82d5fec0f3a 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageToolCall/ChatMessageToolCallGroup.svelte @@ -6,10 +6,13 @@ import { describeToolActivity, summarizeToolCalls } from './parsers/tool-call-phrasing'; import ToolCallElapsed from './ToolCallElapsed.svelte'; - import { CollapsibleContentBlock } from '#lib/components/app/index.ts'; - import { ScrollCarousel } from '#lib/components/app/index.ts'; + import { + ChatAttachmentsGalleryImage, + CollapsibleContentBlock, + ScrollCarousel + } from '#lib/components/app/index.ts'; import { ScrollCarouselVariant } from '#lib/enums/index.ts'; - import { mediaGalleryStore, settingsStore } from '#lib/stores/index.ts'; + import { settingsStore } from '#lib/stores/index.ts'; import type { AgenticSection } from '#lib/types/index.ts'; import { imageExtras, toolCallShownArg } from '#lib/utils/index.ts'; import type { Snippet } from 'svelte'; @@ -86,19 +89,11 @@
{#each images as image, i (i)} - + {image} + imageClass="h-full w-auto max-w-60 object-cover" + /> {/each}
diff --git a/ui/apps/chat/src/lib/components/app/chat/index.ts b/ui/apps/chat/src/lib/components/app/chat/index.ts index 2276eff89cd8..fa4ad1800abc 100644 --- a/ui/apps/chat/src/lib/components/app/chat/index.ts +++ b/ui/apps/chat/src/lib/components/app/chat/index.ts @@ -94,6 +94,9 @@ export { default as ChatAttachmentsListItemVoice } from './ChatAttachments/ChatA */ export { default as ChatAttachmentsListItemThumbnailImage } from './ChatAttachments/ChatAttachmentsList/ChatAttachmentsListItem/ChatAttachmentsListItemThumbnailImage.svelte'; +/** An image of the thread shown in place; a click opens the conversation's slideshow at it. */ +export { default as ChatAttachmentsGalleryImage } from './ChatAttachments/ChatAttachmentsGalleryImage.svelte'; + /** * Unified attachment preview component for dialog display. Shows a single file * preview without carousel, or a gallery/carousel view when multiple items exist. diff --git a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte index 0edd8cbcde15..113dd2be3601 100644 --- a/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte +++ b/ui/apps/chat/src/lib/components/app/content/MarkdownContent/MarkdownContent.svelte @@ -30,9 +30,9 @@ SETTINGS_KEYS, SVG } from '#lib/constants/index.ts'; - import { BooleanString, ColorMode, UrlProtocol } from '#lib/enums/index.ts'; + import { AttachmentType, BooleanString, ColorMode, UrlProtocol } from '#lib/enums/index.ts'; import { createStickToBottom } from '#lib/hooks/use-stick-to-bottom.svelte.ts'; - import { settingsStore } from '#lib/stores/index.ts'; + import { mediaGalleryStore, settingsStore } from '#lib/stores/index.ts'; import type { DatabaseMessageExtra } from '#lib/types/database.js'; import { copyCodeToClipboard, @@ -456,8 +456,23 @@ * Also handles copy and preview button clicks for mermaid blocks. * Uses event delegation: a single handler on the container. */ - async function handleMermaidClick(event: MouseEvent) { + async function handleContentClick(event: MouseEvent) { const target = event.target as HTMLElement; + // an attachment's image opens the conversation's slideshow at it + const image = target.closest('img'); + const attachment = + image && + attachments?.find( + (extra) => + extra.type === AttachmentType.IMAGE && extra.base64Url === image.getAttribute('src') + ); + + if (attachment) { + event.preventDefault(); + mediaGalleryStore.show(attachment); + + return; + } if (toggleDiagramSource(target)) { event.preventDefault(); @@ -648,7 +663,7 @@ class="{className}{settingsStore.config[SETTINGS_KEYS.FULL_HEIGHT_CODE_BLOCKS] ? ' full-height-code-blocks' : ''}" - onclick={handleMermaidClick} + onclick={handleContentClick} > {#each renderedBlocks as block (block.id)}
diff --git a/ui/apps/chat/src/lib/constants/image.constants.ts b/ui/apps/chat/src/lib/constants/image.constants.ts index 53a90eaa4e19..bffed37de1e8 100644 --- a/ui/apps/chat/src/lib/constants/image.constants.ts +++ b/ui/apps/chat/src/lib/constants/image.constants.ts @@ -7,6 +7,10 @@ export const IMAGE = { MEGAPIXELS_TO_PIXELS: 1_000_000 } as const; +/** What a screen reader calls an image that opens the slideshow at itself. */ +export const IMAGE_PREVIEW_LABEL = (name?: string): string => + name ? `Preview ${name}` : 'Preview image'; + /** * JPEG and EXIF binary format constants for orientation parsing. */ diff --git a/ui/apps/chat/src/lib/utils/attachment-display.ts b/ui/apps/chat/src/lib/utils/attachment-display.ts index 0bbfa4c033f9..16fdf6730788 100644 --- a/ui/apps/chat/src/lib/utils/attachment-display.ts +++ b/ui/apps/chat/src/lib/utils/attachment-display.ts @@ -48,7 +48,7 @@ function getUploadedFileCategory(file: ChatUploadedFile): FileTypeCategory | nul /** * Creates a unified list of display items from uploaded files and stored attachments. - * Items are returned in reverse order (newest first). + * Items keep the order they were added in. */ export function getAttachmentDisplayItems( options: AttachmentDisplayItemsOptions @@ -96,5 +96,5 @@ export function getAttachmentDisplayItems( }); } - return items.reverse(); + return items; } diff --git a/ui/apps/chat/src/lib/utils/branching.ts b/ui/apps/chat/src/lib/utils/branching.ts index b74b0a5c04a0..7ed05c070917 100644 --- a/ui/apps/chat/src/lib/utils/branching.ts +++ b/ui/apps/chat/src/lib/utils/branching.ts @@ -83,6 +83,10 @@ export function filterByLeafNodeId( currentNode = nodeMap.get(currentNode.parent); } + // root first, so messages of the same timestamp (results of parallel tool calls) keep their + // order through the stable sort below + result.reverse(); + // Sort: system messages first, then by timestamp result.sort((a, b) => { if (a.role === MessageRole.SYSTEM && b.role !== MessageRole.SYSTEM) return -1; diff --git a/ui/apps/chat/tests/unit/attachment-display.test.ts b/ui/apps/chat/tests/unit/attachment-display.test.ts new file mode 100644 index 000000000000..f4f31e2fc23c --- /dev/null +++ b/ui/apps/chat/tests/unit/attachment-display.test.ts @@ -0,0 +1,23 @@ +// The order getAttachmentDisplayItems returns: the order the attachments were added in, as the +// attachment lists show them. + +import { AttachmentType } from '#lib/enums/index.ts'; +import type { DatabaseMessageExtra } from '#lib/types/database.js'; +import { getAttachmentDisplayItems } from '#lib/utils/attachment-display.ts'; +import { describe, expect, it } from 'vitest'; + +const attachments = ['first.png', 'second.png'].map( + (name): DatabaseMessageExtra => ({ + base64Url: `data:image/png;base64,${name}`, + name, + type: AttachmentType.IMAGE + }) +); + +describe('getAttachmentDisplayItems', () => { + it('keeps the order they were added in', () => { + const names = getAttachmentDisplayItems({ attachments }).map((item) => item.name); + + expect(names).toEqual(['first.png', 'second.png']); + }); +}); diff --git a/ui/apps/chat/tests/unit/branching.test.ts b/ui/apps/chat/tests/unit/branching.test.ts index 0832998eaf14..fa80ac65346e 100644 --- a/ui/apps/chat/tests/unit/branching.test.ts +++ b/ui/apps/chat/tests/unit/branching.test.ts @@ -4,7 +4,7 @@ import { MessageRole, MessageType } from '#lib/enums/index.ts'; import type { DatabaseMessage } from '#lib/types/database.js'; -import { buildSiblingInfoMap, findLeafNode } from '#lib/utils/branching.ts'; +import { buildSiblingInfoMap, filterByLeafNodeId, findLeafNode } from '#lib/utils/branching.ts'; import { describe, expect, it } from 'vitest'; function msg(id: string, parent: string | null, children: string[] = []): DatabaseMessage { @@ -93,3 +93,12 @@ describe('buildSiblingInfoMap', () => { } }); }); + +describe('filterByLeafNodeId', () => { + it('keeps the path order for messages of the same timestamp', () => { + // every message of the chain has timestamp 0, as parallel tool results can + const ids = filterByLeafNodeId(linearChain(3), 'm3').map((message) => message.id); + + expect(ids).toEqual(['m0', 'm1', 'm2', 'm3']); + }); +}); From b9fcf77a499205b15bed35b7b2f3495571bca8cf Mon Sep 17 00:00:00 2001 From: Radoslav Gerganov Date: Thu, 3 Dec 2026 21:08:03 +0200 Subject: [PATCH 376/401] rpc : fix stale alloc_size cache entry reused for larger src tensor (#33611) The RPC client's alloc-size cache key for ggml_backend_rpc_buffer_type_get_alloc_size() omits the src tensors. For ops in ggml_op_alloc_size_may_expand() the server-side allocation size can depend on a src, e.g. TOP_K on Metal with nelements(src0) or FLASH_ATTN_EXT on CUDA/Metal with the KV length. A size cached for a small src could be reused for a larger one, overrunning the server-side compute buffer. Key the cache on the full layout of the tensor and its srcs, reusing the supports_op key (renamed to op_layout_key), and move the cache and its mutex from function-level statics into ggml_backend_rpc_buffer_type_context. ref: #30794 Testing done (on Apple M4 Max): TEST_RPC_DEVICE=MTL0 bash tests/test-rpc-multi-server.sh \ build/bin/ggml-rpc-server build/bin/test-rpc-multi-server Assisted-by: Claude Opus 5.5 Co-authored-by: Brian Woods --- ggml/src/ggml-rpc/ggml-rpc.cpp | 137 +++++++++++++------------------- tests/test-rpc-multi-server.cpp | 31 +++++++- tests/test-rpc-multi-server.sh | 7 +- 3 files changed, 91 insertions(+), 84 deletions(-) diff --git a/ggml/src/ggml-rpc/ggml-rpc.cpp b/ggml/src/ggml-rpc/ggml-rpc.cpp index 92796e6c047c..fe1a60268fd8 100644 --- a/ggml/src/ggml-rpc/ggml-rpc.cpp +++ b/ggml/src/ggml-rpc/ggml-rpc.cpp @@ -338,11 +338,13 @@ struct ggml_backend_rpc_device_context { }; struct ggml_backend_rpc_buffer_type_context { - std::string endpoint; - uint32_t device; - std::string name; - size_t alignment; - size_t max_size; + std::string endpoint; + uint32_t device; + std::string name; + size_t alignment; + size_t max_size; + std::mutex alloc_size_mutex; + std::unordered_map alloc_size_cache; }; class rpc_dispatcher; @@ -372,6 +374,37 @@ static uint64_t fnv_hash(const uint8_t * data, size_t len, uint64_t hash = 0xcbf return hash; } +// full layout of the op and its sources, without ids, addresses, names and buffers +// used as the cache key for both supports_op and get_alloc_size +static uint64_t op_layout_key(const ggml_tensor * op) { + struct op_layout_key_tensor { + uint32_t type; + uint32_t op; + int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)]; + int64_t ne[GGML_MAX_DIMS]; + uint64_t nb[GGML_MAX_DIMS]; + }; + op_layout_key_tensor key[1 + GGML_MAX_SRC]; + memset(key, 0, sizeof(key)); + for (int i = 0; i < 1 + GGML_MAX_SRC; i++) { + const ggml_tensor * t = i == 0 ? op : op->src[i - 1]; + if (t == nullptr) { + key[i].type = UINT32_MAX; + continue; + } + key[i].type = t->type; + if (i == 0) { + key[i].op = t->op; + memcpy(key[i].op_params, t->op_params, sizeof(key[i].op_params)); + } + for (int j = 0; j < GGML_MAX_DIMS; j++) { + key[i].ne[j] = t->ne[j]; + key[i].nb[j] = t->nb[j]; + } + } + return fnv_hash((const uint8_t *)key, sizeof(key)); +} + // builds a variable-size request; the buffer must not change once queued struct rpc_writer { std::shared_ptr> buf = std::make_shared>(); @@ -1156,43 +1189,15 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty // TODO: change rpc_tensor nb to 64-bit int const size_t min_size = ggml_nbytes(tensor); - // Cache key for calls to read the alloc_size. - // We deliberately exclude src tensor dimensions from the key because: - // 1. For CPU backends, alloc_size = ggml_nbytes(output) regardless of src shapes - // 2. For GPU backends, the reservation graph uses max dimensions, so the - // cached value from reservation is always >= any subsequent request - // 3. Including src dims causes cache misses per-ubatch (e.g. growing KV cache) - // which blocks the main thread behind in-flight GRAPH_COMPUTE commands - struct alloc_size_cache_key { - uint32_t device; - uint32_t type; - uint32_t op; - int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)]; - uint32_t ne[GGML_MAX_DIMS]; - uint64_t nb[GGML_MAX_DIMS]; - }; - - alloc_size_cache_key key = {}; - key.device = buft_ctx->device; - key.type = tensor->type; - key.op = tensor->op; - memcpy(key.op_params, tensor->op_params, sizeof(key.op_params)); - for (int i = 0; i < GGML_MAX_DIMS; i++) { - key.ne[i] = (uint32_t)tensor->ne[i]; - key.nb[i] = (uint64_t)tensor->nb[i]; - } - - uint64_t cache_hash = fnv_hash((const uint8_t *)&key, sizeof(key)); - cache_hash = fnv_hash((const uint8_t *)buft_ctx->endpoint.data(), buft_ctx->endpoint.size(), cache_hash); - - // alloc sizes are immutable for a given tensor configuration - static std::mutex cache_mutex; - static std::unordered_map cache; - + // alloc sizes are immutable for a given layout of the tensor and its srcs + // the srcs must be part of the key: some backends reserve extra memory that scales with a src, + // e.g. FLASH_ATTN_EXT with the KV length or TOP_K with nelements(src0) + // ref: https://github.com/ggml-org/llama.cpp/issues/30794 + const uint64_t key = op_layout_key(tensor); { - std::lock_guard lock(cache_mutex); - auto it = cache.find(cache_hash); - if (it != cache.end()) { + std::lock_guard lock(buft_ctx->alloc_size_mutex); + auto it = buft_ctx->alloc_size_cache.find(key); + if (it != buft_ctx->alloc_size_cache.end()) { LOG_DBG3("[%s] cache hit: %s -> %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), rpc_log_format_size(it->second).c_str()); return std::max(it->second, min_size); @@ -1216,8 +1221,8 @@ static size_t ggml_backend_rpc_buffer_type_get_alloc_size(ggml_backend_buffer_ty const auto response = dispatcher->call(request); { - std::lock_guard lock(cache_mutex); - cache[cache_hash] = response.alloc_size; + std::lock_guard lock(buft_ctx->alloc_size_mutex); + buft_ctx->alloc_size_cache[key] = response.alloc_size; } LOG_DBG2("[%s] %s -> alloc_size: %s\n", __func__, rpc_log_format_tensor(tensor).c_str(), @@ -1412,11 +1417,13 @@ ggml_backend_buffer_type_t ggml_backend_rpc_buffer_type(const char * endpoint, u size_t alignment = get_alignment(dispatcher, device); size_t max_size = get_max_size(dispatcher, device); ggml_backend_rpc_buffer_type_context * buft_ctx = new ggml_backend_rpc_buffer_type_context { - /* .endpoint = */ endpoint, - /* .device = */ device, - /* .name = */ buft_name, - /* .alignment = */ alignment, - /* .max_size = */ max_size + /* .endpoint = */ endpoint, + /* .device = */ device, + /* .name = */ buft_name, + /* .alignment = */ alignment, + /* .max_size = */ max_size, + /* .alloc_size_mutex = */ {}, + /* .alloc_size_cache = */ {}, }; auto reg = ggml_backend_rpc_add_server(endpoint); ggml_backend_buffer_type_t buft = new ggml_backend_buffer_type { @@ -2891,36 +2898,6 @@ static ggml_backend_buffer_type_t ggml_backend_rpc_device_get_buffer_type(ggml_b GGML_UNUSED(dev); } -// full layout of the op and its sources, without ids, addresses, names and buffers -static uint64_t supports_op_key(const ggml_tensor * op) { - struct supports_op_key_tensor { - uint32_t type; - uint32_t op; - int32_t op_params[GGML_MAX_OP_PARAMS / sizeof(int32_t)]; - int64_t ne[GGML_MAX_DIMS]; - uint64_t nb[GGML_MAX_DIMS]; - }; - supports_op_key_tensor key[1 + GGML_MAX_SRC]; - memset(key, 0, sizeof(key)); - for (int i = 0; i < 1 + GGML_MAX_SRC; i++) { - const ggml_tensor * t = i == 0 ? op : op->src[i - 1]; - if (t == nullptr) { - key[i].type = UINT32_MAX; - continue; - } - key[i].type = t->type; - if (i == 0) { - key[i].op = t->op; - memcpy(key[i].op_params, t->op_params, sizeof(key[i].op_params)); - } - for (int j = 0; j < GGML_MAX_DIMS; j++) { - key[i].ne[j] = t->ne[j]; - key[i].nb[j] = t->nb[j]; - } - } - return fnv_hash((const uint8_t *)key, sizeof(key)); -} - // ask the server about the whole graph in a single round trip, unless every node already has an answer static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev, const struct ggml_cgraph * graph) { ggml_backend_rpc_device_context * ctx = (ggml_backend_rpc_device_context *)dev->context; @@ -2934,7 +2911,7 @@ static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev, { std::lock_guard lock(ctx->supports_op_mutex); for (int i = 0; i < graph->n_nodes; i++) { - keys[i] = supports_op_key(graph->nodes[i]); + keys[i] = op_layout_key(graph->nodes[i]); all_cached = all_cached && ctx->supports_op_cache.count(keys[i]) > 0; } } @@ -2955,7 +2932,7 @@ static void ggml_backend_rpc_device_supports_op_prefetch(ggml_backend_dev_t dev, // cached answer if the layout was seen, else ask the server about this op static bool ggml_backend_rpc_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { ggml_backend_rpc_device_context * ctx = (ggml_backend_rpc_device_context *)dev->context; - const uint64_t key = supports_op_key(op); + const uint64_t key = op_layout_key(op); { std::lock_guard lock(ctx->supports_op_mutex); auto it = ctx->supports_op_cache.find(key); diff --git a/tests/test-rpc-multi-server.cpp b/tests/test-rpc-multi-server.cpp index f253b6e144d6..ece602ec1d10 100644 --- a/tests/test-rpc-multi-server.cpp +++ b/tests/test-rpc-multi-server.cpp @@ -17,7 +17,7 @@ int main(int argc, char ** argv) { GGML_ASSERT(backend_b != nullptr); ggml_init_params params = { - /* .mem_size = */ 3*ggml_tensor_overhead() + ggml_graph_overhead_custom(1, false), + /* .mem_size = */ 10*ggml_tensor_overhead() + ggml_graph_overhead_custom(1, false), /* .mem_buffer = */ nullptr, /* .no_alloc = */ true, }; @@ -62,6 +62,35 @@ int main(int argc, char ** argv) { GGML_ASSERT(ggml_backend_buft_get_alloc_size(buft, packed) >= ggml_nbytes(packed)); GGML_ASSERT(ggml_backend_buft_get_alloc_size(buft, strided) >= ggml_nbytes(strided)); + // Two TOP_K tensors with the same output layout but different srcs must not share a cached alloc size. + // ref: https://github.com/ggml-org/llama.cpp/issues/30794 + ggml_tensor * src_small = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 8); + ggml_tensor * top_k_small = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4); + top_k_small->op = GGML_OP_TOP_K; + top_k_small->src[0] = src_small; + + ggml_tensor * src_large = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4096*8); + ggml_tensor * top_k_large = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4); + top_k_large->op = GGML_OP_TOP_K; + top_k_large->src[0] = src_large; + + // uncached baseline for the large src: a different op_params value gives a separate cache entry + ggml_tensor * top_k_large_probe = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 4); + top_k_large_probe->op = GGML_OP_TOP_K; + top_k_large_probe->src[0] = src_large; + top_k_large_probe->op_params[0] = 1; + size_t size_large_uncached = ggml_backend_buft_get_alloc_size(buft, top_k_large_probe); + + // ask for the small src first, so a cache keyed without srcs holds the smaller size + size_t size_small = ggml_backend_buft_get_alloc_size(buft, top_k_small); + size_t size_large = ggml_backend_buft_get_alloc_size(buft, top_k_large); + GGML_ASSERT(size_large >= size_large_uncached); + GGML_ASSERT(size_small <= size_large); + + // the small src must not be affected by the larger one + size_t size_small_again = ggml_backend_buft_get_alloc_size(buft, top_k_small); + GGML_ASSERT(size_small_again >= size_small); + ggml_free(ctx); ggml_backend_free(backend_b); ggml_backend_free(backend_a); diff --git a/tests/test-rpc-multi-server.sh b/tests/test-rpc-multi-server.sh index a8c72316202a..71e2eec9233a 100755 --- a/tests/test-rpc-multi-server.sh +++ b/tests/test-rpc-multi-server.sh @@ -17,7 +17,7 @@ trap cleanup EXIT wait_for_port() { local port=$1 - for _ in {1..600}; do + for _ in {1..2400}; do if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then exec 3>&- exec 3<&- @@ -28,7 +28,8 @@ wait_for_port() { return 1 } -"$server" --device CPU --host 127.0.0.1 --port "$port_a" >"$test_dir/server-a.log" 2>&1 & +# the TOP_K alloc size check needs a device whose alloc size depends on src0, e.g. Metal +"$server" --device "${TEST_RPC_DEVICE:-CPU}" --host 127.0.0.1 --port "$port_a" >"$test_dir/server-a.log" 2>&1 & pid_a=$! "$server" --device CPU --host 127.0.0.1 --port "$port_b" >"$test_dir/server-b.log" 2>&1 & pid_b=$! @@ -37,7 +38,7 @@ wait_for_port "$port_b" "$client" "$endpoint_a" "$endpoint_b" -if grep -q "invalid data ptr" "$test_dir/server-b.log"; then +if grep -q "has a data pointer but no buffer" "$test_dir/server-b.log"; then cat "$test_dir/server-b.log" exit 1 fi From 8c9895f1b54f712dcb8b06c4b0d80415952fa8a2 Mon Sep 17 00:00:00 2001 From: Rootodus <120185711+Rootodus@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:41:24 +0100 Subject: [PATCH 377/401] vulkan: add subgroup shader for pool1d (#33221) * vulkan: add subgroup shader for pool1d Assisted-by: Google AI Search --- ggml/src/ggml-vulkan/ggml-vulkan-types.h | 1 + ggml/src/ggml-vulkan/ggml-vulkan.cpp | 18 ++++++++---- .../ggml-vulkan/vulkan-shaders/pool1d.comp | 28 ++++++++++++++++--- .../vulkan-shaders/vulkan-shaders-gen.cpp | 1 + 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h index 27ce14ca5fa4..be7d5bfba64e 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h @@ -1034,6 +1034,7 @@ struct vk_device_struct { vk_pipeline pipeline_snake_f16; vk_pipeline pipeline_snake_bf16; vk_pipeline pipeline_pool1d_f32; + vk_pipeline pipeline_pool1d_subgroup_f32; vk_pipeline pipeline_pool2d_f32; vk_pipeline pipeline_pool2d_subgroup_f32; vk_pipeline pipeline_rwkv_wkv6_f32; diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index 939ddab8dc00..f0b5442b4f0c 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -4354,7 +4354,10 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { ggml_vk_create_pipeline(device, device->pipeline_snake_f16, "snake_f16", snake_f16_len, snake_f16_data, "main", 4, sizeof(vk_op_snake_push_constants), {256, 1, 1}, {}, 1); ggml_vk_create_pipeline(device, device->pipeline_snake_bf16, "snake_bf16", snake_bf16_len, snake_bf16_data, "main", 4, sizeof(vk_op_snake_push_constants), {256, 1, 1}, {}, 1); - ggml_vk_create_pipeline(device, device->pipeline_pool1d_f32, "pool1d_f32", pool1d_f32_len, pool1d_f32_data, "main", 2, sizeof(vk_op_pool1d_push_constants), {512, 1, 1}, {}, 1); + ggml_vk_create_pipeline(device, device->pipeline_pool1d_f32, "pool1d_f32", pool1d_f32_len, pool1d_f32_data, "main", 2, sizeof(vk_op_pool1d_push_constants), {1, 1, 1}, {512}, 1); + if (device->subgroup_arithmetic && device->subgroup_require_full_support) { + ggml_vk_create_pipeline(device, device->pipeline_pool1d_subgroup_f32, "pool1d_subgroup_f32", pool1d_subgroup_f32_len, pool1d_subgroup_f32_data, "main", 2, sizeof(vk_op_pool1d_push_constants), {1, 1, 1}, {128}, 1, false, true, device->subgroup_size); + } ggml_vk_create_pipeline(device, device->pipeline_pool2d_f32, "pool2d_f32", pool2d_f32_len, pool2d_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {1, 1, 1}, {512}, 1); if (device->subgroup_arithmetic && device->subgroup_require_full_support) { ggml_vk_create_pipeline(device, device->pipeline_pool2d_subgroup_f32, "pool2d_subgroup_f32", pool2d_subgroup_f32_len, pool2d_subgroup_f32_data, "main", 2, sizeof(vk_op_pool2d_push_constants), {1, 1, 1}, {128}, 1, false, true, device->subgroup_size); @@ -10948,6 +10951,9 @@ static vk_pipeline ggml_vk_op_get_pipeline(ggml_backend_vk_context * ctx, const } case GGML_OP_POOL_1D: if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + if (ctx->device->pipeline_pool1d_subgroup_f32 && dst->op_params[1] >= int32_t(ctx->device->subgroup_size)) { + return ctx->device->pipeline_pool1d_subgroup_f32; + } return ctx->device->pipeline_pool1d_f32; } return nullptr; @@ -11401,10 +11407,12 @@ static void ggml_vk_op_f32(ggml_backend_vk_context * ctx, vk_context& subctx, co } break; case GGML_OP_POOL_1D: { - const uint32_t N = dst->ne[3] * dst->ne[2]; - const uint32_t OC = dst->ne[1]; - const uint32_t OL = dst->ne[0]; - elements = { N * OC * OL, 1, 1}; + const uint32_t outputs = ggml_nelements(dst); + const uint32_t outputs_per_workgroup = pipeline == ctx->device->pipeline_pool1d_subgroup_f32 ? 128 / ctx->device->subgroup_size : 512; + const uint32_t workgroups = CEIL_DIV(outputs, outputs_per_workgroup); + const uint32_t groups_y = CEIL_DIV(workgroups, ctx->device->properties.limits.maxComputeWorkGroupCount[0]); + const uint32_t groups_x = CEIL_DIV(workgroups, groups_y); + elements = { groups_x, groups_y, 1 }; } break; case GGML_OP_POOL_2D: { diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/pool1d.comp b/ggml/src/ggml-vulkan/vulkan-shaders/pool1d.comp index bb87631ce363..804673e324dc 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/pool1d.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/pool1d.comp @@ -1,5 +1,10 @@ #version 450 +#if defined(USE_SUBGROUP) +#extension GL_KHR_shader_subgroup_basic : require +#extension GL_KHR_shader_subgroup_arithmetic : require +#endif + #include "types.glsl" #extension GL_EXT_shader_16bit_storage : require @@ -15,18 +20,27 @@ layout(push_constant) uniform parameter { int p0; } p; -#define BLOCK_SIZE 512 +layout(constant_id = 0) const uint BLOCK_SIZE = 512; #define FLT_MAX 3.402823466e+38F #define OP_POOL_MAX 0u #define OP_POOL_AVG 1u -layout (local_size_x = BLOCK_SIZE, local_size_y = 1, local_size_z = 1) in; +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) writeonly buffer D {D_TYPE data_d[];}; void main() { - const uint idx = gl_GlobalInvocationID.x; + const uint workgroup = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; +#if defined(USE_SUBGROUP) + const uint idx = workgroup * gl_NumSubgroups + gl_SubgroupID; + const int lane = int(gl_SubgroupInvocationID); + const int step = int(gl_SubgroupSize); +#else + const uint idx = workgroup * BLOCK_SIZE + gl_LocalInvocationID.x; + const int lane = 0; + const int step = 1; +#endif if (idx >= p.pelements) { return; } @@ -51,7 +65,7 @@ void main() { } #pragma unroll - for (uint i = bl; i < el; i++) { + for (int i = bl + lane; i < el; i += step) { const float cur = D_TYPE(data_a[nc * p.IL + i]); if (p.op == OP_POOL_AVG) { @@ -61,5 +75,11 @@ void main() { } } +#if defined(USE_SUBGROUP) + res = p.op == OP_POOL_AVG ? subgroupAdd(res) : subgroupMax(res); + if (!subgroupElect()) { + return; + } +#endif data_d[nc * p.OL + cur_ol] = res; } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp index 29a39be70d99..a905b7c87dda 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp @@ -1146,6 +1146,7 @@ void process_shaders() { string_to_spv("snake_bf16", "snake.comp", {{"DATA_A_BF16", "1"}, {"DATA_D_BF16", "1"}, {"A_TYPE", "uint16_t"}, {"D_TYPE", "uint16_t"}}); string_to_spv("pool1d_f32", "pool1d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); + string_to_spv("pool1d_subgroup_f32", "pool1d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"USE_SUBGROUP", "1"}})); string_to_spv("pool2d_f32", "pool2d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}})); string_to_spv("pool2d_subgroup_f32", "pool2d.comp", merge_maps(base_dict, {{"A_TYPE", "float"}, {"D_TYPE", "float"}, {"USE_SUBGROUP", "1"}})); From 59b716523f1ba73be12a9f0f51eb4c072b7fa523 Mon Sep 17 00:00:00 2001 From: Mark Todorovich Date: Thu, 3 Dec 2026 13:43:35 -0800 Subject: [PATCH 378/401] hexagon: move conv2d_dw kernels to a separate file (#32982) * hexagon: move conv2d-dw kernels to conv2d-dw-ops.c * hexagon: split conv2d-dw headers as well * hexagon: add support for f16/f32 mixed types in conv2d --------- Co-authored-by: Max Krasnyansky --- ggml/src/ggml-hexagon/htp-kparams.cpp | 23 +- ggml/src/ggml-hexagon/htp-kparams.h | 1 + ggml/src/ggml-hexagon/htp-opnode.cpp | 1 + ggml/src/ggml-hexagon/htp/CMakeLists.txt | 2 +- ggml/src/ggml-hexagon/htp/conv2d-dw-ops.c | 1286 ++++++++++++++++++++ ggml/src/ggml-hexagon/htp/conv2d-dw-ops.h | 144 +++ ggml/src/ggml-hexagon/htp/conv2d-dw5-ops.c | 295 ----- ggml/src/ggml-hexagon/htp/conv2d-ops.c | 908 -------------- ggml/src/ggml-hexagon/htp/conv2d-ops.h | 117 -- ggml/src/ggml-hexagon/htp/htp-ctx.h | 1 - 10 files changed, 1439 insertions(+), 1339 deletions(-) create mode 100644 ggml/src/ggml-hexagon/htp/conv2d-dw-ops.c create mode 100644 ggml/src/ggml-hexagon/htp/conv2d-dw-ops.h delete mode 100644 ggml/src/ggml-hexagon/htp/conv2d-dw5-ops.c diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 7762b9276e93..4af17dea21c8 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -5390,7 +5390,8 @@ static bool htp_kparams_solve_conv2d_dw( } if ((src0->type != GGML_TYPE_F16 && src0->type != GGML_TYPE_F32) || - src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + (src1->type != GGML_TYPE_F16 && src1->type != GGML_TYPE_F32) || + (dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_F32)) { return false; } @@ -5437,12 +5438,8 @@ static bool htp_kparams_solve_conv2d_dw( const uint32_t ow_u = (uint32_t) ow; const uint32_t oh_u = (uint32_t) oh; - const uint32_t row_src_bytes = cwhn - ? (w * c * (uint32_t) sizeof(float)) - : (w * (uint32_t) sizeof(float)); - const uint32_t row_dst_bytes = cwhn - ? (ow_u * c * (uint32_t) sizeof(float)) - : (ow_u * (uint32_t) sizeof(float)); + const uint32_t row_src_bytes = (cwhn ? w * c : w) * (uint32_t) ggml_type_size(src1->type); + const uint32_t row_dst_bytes = (cwhn ? ow_u * c : ow_u) * (uint32_t) ggml_type_size(dst->type); uint8_t kernel_type = HTP_CONV2D_DW_KERNEL_UNSUPPORTED; if (cwhn) { @@ -5464,7 +5461,6 @@ static bool htp_kparams_solve_conv2d_dw( } const bool fast_k3x3 = kernel_type >= HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3; - const uint32_t pad_rows = fast_k3x3 ? 4 : 0; const uint32_t pad_top_stride = fast_k3x3 ? w : 0; const size_t vtcm_budget = htp_session_vtcm_size(sess); @@ -5478,11 +5474,7 @@ static bool htp_kparams_solve_conv2d_dw( struct htp_conv2d_dw_vtcm_layout layout; while (true) { - const uint32_t max_ih_chunk = (std::min)(h, (oh_chunk - 1) * (uint32_t) s1 + (kh - 1) * (uint32_t) d1 + 1); - const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * row_src_bytes + 128; - const uint32_t max_dst_bytes = oh_chunk * row_dst_bytes + 128; - - htp_conv2d_dw_vtcm_layout_build(&layout, max_src_bytes, max_dst_bytes, w_size, n_hvx); + htp_conv2d_dw_vtcm_layout_build(&layout, w, h, c, kh, ow_u, oh_chunk, s1, d1, cwhn, fast_k3x3, w_size, n_hvx); if (layout.total_bytes <= vtcm_budget && layout.total_bytes > 0) { break; @@ -5504,10 +5496,7 @@ static bool htp_kparams_solve_conv2d_dw( n_hvx = 1; } - const uint32_t max_ih_chunk = (std::min)(h, (oh_chunk - 1) * (uint32_t) s1 + (kh - 1) * (uint32_t) d1 + 1); - const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * row_src_bytes + 128; - const uint32_t max_dst_bytes = oh_chunk * row_dst_bytes + 128; - htp_conv2d_dw_vtcm_layout_build(&layout, max_src_bytes, max_dst_bytes, w_size, n_hvx); + htp_conv2d_dw_vtcm_layout_build(&layout, w, h, c, kh, ow_u, oh_chunk, s1, d1, cwhn, fast_k3x3, w_size, n_hvx); kparams->kernel_type = kernel_type; kparams->flags = (cwhn ? HTP_CONV2D_DW_FLAG_CWHN : 0) | (src0->type == GGML_TYPE_F16 ? HTP_CONV2D_DW_FLAG_F16 : 0); diff --git a/ggml/src/ggml-hexagon/htp-kparams.h b/ggml/src/ggml-hexagon/htp-kparams.h index 58de391fd316..8b27fcc965e4 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.h +++ b/ggml/src/ggml-hexagon/htp-kparams.h @@ -9,6 +9,7 @@ #include "htp/binary-ops.h" #include "htp/concat-ops.h" #include "htp/conv2d-ops.h" +#include "htp/conv2d-dw-ops.h" #include "htp/cpy-ops.h" #include "htp/cumsum-ops.h" #include "htp/diag-ops.h" diff --git a/ggml/src/ggml-hexagon/htp-opnode.cpp b/ggml/src/ggml-hexagon/htp-opnode.cpp index 7ef3830169b4..761bf65e9d1c 100644 --- a/ggml/src/ggml-hexagon/htp-opnode.cpp +++ b/ggml/src/ggml-hexagon/htp-opnode.cpp @@ -4,6 +4,7 @@ #include "htp/argsort-ops.h" #include "htp/binary-ops.h" #include "htp/conv2d-ops.h" +#include "htp/conv2d-dw-ops.h" #include "htp/cumsum-ops.h" #include "htp/diag-ops.h" #include "htp/dsv4-hc-ops.h" diff --git a/ggml/src/ggml-hexagon/htp/CMakeLists.txt b/ggml/src/ggml-hexagon/htp/CMakeLists.txt index 5d85e4f9864e..4bbf00d34e9f 100644 --- a/ggml/src/ggml-hexagon/htp/CMakeLists.txt +++ b/ggml/src/ggml-hexagon/htp/CMakeLists.txt @@ -52,7 +52,7 @@ add_library(${HTP_LIB} SHARED argsort-ops.c im2col-ops.c conv2d-ops.c - conv2d-dw5-ops.c + conv2d-dw-ops.c roll-ops.c pool-ops.c upscale-ops.c diff --git a/ggml/src/ggml-hexagon/htp/conv2d-dw-ops.c b/ggml/src/ggml-hexagon/htp/conv2d-dw-ops.c new file mode 100644 index 000000000000..b423e5314d67 --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/conv2d-dw-ops.c @@ -0,0 +1,1286 @@ +// Depthwise 2D convolution (CONV_2D_DW) kernels for all supported filter sizes. + +#include +#include +#include + +#include "conv2d-dw-ops.h" +#include "dma-copy.h" +#include "dma-pipeline.h" +#include "dma-queue.h" +#include "hex-common.h" +#include "hex-fastdiv.h" +#include "htp-trace.h" +#include "htp-ctx.h" +#include "htp-ops.h" +#include "htp-tensor.h" +#include "htp-vtcm.h" +#include "hvx-base.h" +#include "hvx-copy.h" + +struct conv2d_dw_task_slice { + dma_addr_t src_addr; + dma_addr_t dst_addr; + uint32_t src_bytes; + uint32_t dst_bytes; + uint32_t ih_count; + uint32_t top_pad; + uint32_t bot_pad; + uint32_t oh_start; + uint32_t oh_len; + int32_t ih_first; + uint32_t c; +}; + +static inline void conv2d_dw_get_slice( + struct conv2d_dw_task_slice * slice, + uint32_t task, + const struct htp_tensor * src1, + const struct htp_tensor * dst, + const struct htp_conv2d_dw_kernel_params * kp) { + + uint32_t chunk_idx; + uint32_t n; + uint32_t c = 0; + + if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) { + n = fastdiv(task, &kp->div_n_chunks); + chunk_idx = task - n * kp->n_chunks; + } else { + const uint32_t plane = fastdiv(task, &kp->div_n_chunks); + chunk_idx = task - plane * kp->n_chunks; + n = fastdiv(plane, &kp->div_c); + c = plane - n * kp->c; + } + + const uint32_t oh_start = chunk_idx * kp->oh_chunk; + const uint32_t oh_len = MIN(kp->oh_chunk, kp->oh - oh_start); + + const int32_t ih_min = (int32_t)(oh_start * kp->s1) - kp->p1; + const int32_t ih_max = (int32_t)((oh_start + oh_len - 1) * kp->s1 + (kp->kh - 1) * kp->d1) - kp->p1; + const uint32_t ih_span = (uint32_t)(ih_max - ih_min + 1); + + const int32_t ih_first = MAX(0, ih_min); + const int32_t ih_last = MIN((int32_t)kp->h - 1, ih_max); + const uint32_t ih_count = (ih_first <= ih_last) ? (uint32_t)(ih_last - ih_first + 1) : 0; + const uint32_t top_pad = (ih_count > 0) ? (uint32_t)(ih_first - ih_min) : ih_span; + const uint32_t bot_pad = ih_span - top_pad - ih_count; + + slice->src_bytes = ih_count * kp->row_src_bytes; + slice->dst_bytes = oh_len * kp->row_dst_bytes; + slice->ih_count = ih_count; + slice->top_pad = top_pad; + slice->bot_pad = bot_pad; + slice->oh_start = oh_start; + slice->oh_len = oh_len; + slice->ih_first = ih_first; + slice->c = c; + + if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) { + slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) ih_first * src1->nb[1]; + slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) oh_start * dst->nb[1]; + } else { + slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) c * src1->nb[2] + (size_t) ih_first * src1->nb[1]; + slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) c * dst->nb[2] + (size_t) oh_start * dst->nb[1]; + } +} + +static inline HVX_Vector conv2d_dw_splat_w_f32(const void * ptr) { + return hvx_vec_splat_f32(*(const float *) ptr); +} + +static inline HVX_Vector conv2d_dw_splat_w_f16(const void * ptr) { + const HVX_Vector vh = Q6_Vh_vsplat_R(*(const uint16_t *) ptr); + const HVX_Vector v1 = Q6_Vh_vsplat_R(0x3c00); + return Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(vh, v1))); +} + +static inline HVX_Vector conv2d_dw_load_w_f32(const void * ptr) { + return hvx_vmemu(ptr); +} + +static inline HVX_Vector conv2d_dw_load_w_f16(const void * ptr) { + return Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(ptr))); +} + +static inline HVX_Vector conv2d_dw_qf32_mpy_add3( + HVX_Vector acc, + HVX_Vector x0, HVX_Vector w0, + HVX_Vector x1, HVX_Vector w1, + HVX_Vector x2, HVX_Vector w2) { + const HVX_Vector p01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, w0), Q6_Vqf32_vmpy_VsfVsf(x1, w1)); + const HVX_Vector p2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x2, w2)); + return Q6_Vqf32_vadd_Vqf32Vqf32(p01, p2); +} + +static inline void conv2d_dw_pad_vtcm_k3x3( + float * in_vtcm, + const struct conv2d_dw_task_slice * slice, + uint32_t w_in, + uint32_t extra_bot_rows) { + if (slice->top_pad > 0) { + hvx_splat_f32_a(in_vtcm, 0.0f, slice->top_pad * w_in); + } + const uint32_t tail_zero_rows = slice->bot_pad + extra_bot_rows; + if (tail_zero_rows > 0) { + hvx_splat_f32_a(in_vtcm + (size_t) (slice->top_pad + slice->ih_count) * w_in, 0.0f, tail_zero_rows * w_in); + } +} + +#define DEFINE_CONV2D_DW_WHCN_S1_K3X3(SUFFIX, SPLAT_W_FN) \ +__attribute__((noinline)) \ +static void conv2d_dw_whcn_s1_k3x3_##SUFFIX( \ + const float * restrict in_vtcm, \ + float * restrict out_vtcm, \ + const void * w_vtcm, \ + const struct conv2d_dw_task_slice * slice, \ + const struct htp_ops_context * octx, \ + const struct htp_conv2d_dw_kernel_params * kp) { \ + \ + const struct htp_tensor * src0 = octx->src[0]; \ + const size_t w_nb0 = src0->nb[0]; \ + const size_t w_nb1 = src0->nb[1]; \ + const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ + const uint32_t oh_len = slice->oh_len; \ + const uint32_t w_in = kp->w; \ + \ + conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, w_in, 0); \ + \ + const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector zero = Q6_V_vzero(); \ + \ + uint32_t ohi = 0; \ + for (; ohi + 4 <= oh_len; ohi += 4) { \ + const float * restrict r0 = in_vtcm + (size_t) ohi * w_in; \ + const float * restrict r1 = r0 + w_in; \ + const float * restrict r2 = r1 + w_in; \ + const float * restrict r3 = r2 + w_in; \ + const float * restrict r4 = r3 + w_in; \ + const float * restrict r5 = r4 + w_in; \ + \ + float * restrict out0 = out_vtcm + (size_t) (ohi + 0) * w_in; \ + float * restrict out1 = out0 + w_in; \ + float * restrict out2 = out1 + w_in; \ + float * restrict out3 = out2 + w_in; \ + \ + HVX_Vector p0 = zero, c0 = hvx_vmem(r0); \ + HVX_Vector p1 = zero, c1 = hvx_vmem(r1); \ + HVX_Vector p2 = zero, c2 = hvx_vmem(r2); \ + HVX_Vector p3 = zero, c3 = hvx_vmem(r3); \ + HVX_Vector p4 = zero, c4 = hvx_vmem(r4); \ + HVX_Vector p5 = zero, c5 = hvx_vmem(r5); \ + \ + for (uint32_t ox = 0; ox < w_in; ox += 32) { \ + const bool has_next = (ox + 32 < w_in); \ + \ + const HVX_Vector n0 = has_next ? hvx_vmem(r0 + ox + 32) : zero; \ + const HVX_Vector l0 = Q6_V_valign_VVR(c0, p0, 124); \ + const HVX_Vector rg0 = Q6_V_valign_VVR(n0, c0, 4); \ + HVX_Vector acc0 = conv2d_dw_qf32_mpy_add3(zero, l0, w00, c0, w01, rg0, w02); \ + p0 = c0; c0 = n0; \ + \ + const HVX_Vector n1 = has_next ? hvx_vmem(r1 + ox + 32) : zero; \ + const HVX_Vector l1 = Q6_V_valign_VVR(c1, p1, 124); \ + const HVX_Vector rg1 = Q6_V_valign_VVR(n1, c1, 4); \ + acc0 = conv2d_dw_qf32_mpy_add3(acc0, l1, w10, c1, w11, rg1, w12); \ + HVX_Vector acc1 = conv2d_dw_qf32_mpy_add3(zero, l1, w00, c1, w01, rg1, w02); \ + p1 = c1; c1 = n1; \ + \ + const HVX_Vector n2 = has_next ? hvx_vmem(r2 + ox + 32) : zero; \ + const HVX_Vector l2 = Q6_V_valign_VVR(c2, p2, 124); \ + const HVX_Vector rg2 = Q6_V_valign_VVR(n2, c2, 4); \ + acc0 = conv2d_dw_qf32_mpy_add3(acc0, l2, w20, c2, w21, rg2, w22); \ + hvx_vmem(out0 + ox) = Q6_Vsf_equals_Vqf32(acc0); \ + acc1 = conv2d_dw_qf32_mpy_add3(acc1, l2, w10, c2, w11, rg2, w12); \ + HVX_Vector acc2 = conv2d_dw_qf32_mpy_add3(zero, l2, w00, c2, w01, rg2, w02); \ + p2 = c2; c2 = n2; \ + \ + const HVX_Vector n3 = has_next ? hvx_vmem(r3 + ox + 32) : zero; \ + const HVX_Vector l3 = Q6_V_valign_VVR(c3, p3, 124); \ + const HVX_Vector rg3 = Q6_V_valign_VVR(n3, c3, 4); \ + acc1 = conv2d_dw_qf32_mpy_add3(acc1, l3, w20, c3, w21, rg3, w22); \ + hvx_vmem(out1 + ox) = Q6_Vsf_equals_Vqf32(acc1); \ + acc2 = conv2d_dw_qf32_mpy_add3(acc2, l3, w10, c3, w11, rg3, w12); \ + HVX_Vector acc3 = conv2d_dw_qf32_mpy_add3(zero, l3, w00, c3, w01, rg3, w02); \ + p3 = c3; c3 = n3; \ + \ + const HVX_Vector n4 = has_next ? hvx_vmem(r4 + ox + 32) : zero; \ + const HVX_Vector l4 = Q6_V_valign_VVR(c4, p4, 124); \ + const HVX_Vector rg4 = Q6_V_valign_VVR(n4, c4, 4); \ + acc2 = conv2d_dw_qf32_mpy_add3(acc2, l4, w20, c4, w21, rg4, w22); \ + hvx_vmem(out2 + ox) = Q6_Vsf_equals_Vqf32(acc2); \ + acc3 = conv2d_dw_qf32_mpy_add3(acc3, l4, w10, c4, w11, rg4, w12); \ + p4 = c4; c4 = n4; \ + \ + const HVX_Vector n5 = has_next ? hvx_vmem(r5 + ox + 32) : zero; \ + const HVX_Vector l5 = Q6_V_valign_VVR(c5, p5, 124); \ + const HVX_Vector rg5 = Q6_V_valign_VVR(n5, c5, 4); \ + acc3 = conv2d_dw_qf32_mpy_add3(acc3, l5, w20, c5, w21, rg5, w22); \ + hvx_vmem(out3 + ox) = Q6_Vsf_equals_Vqf32(acc3); \ + p5 = c5; c5 = n5; \ + } \ + } \ + \ + for (; ohi < oh_len; ++ohi) { \ + const float * restrict r0 = in_vtcm + (size_t) ohi * w_in; \ + const float * restrict r1 = r0 + w_in; \ + const float * restrict r2 = r1 + w_in; \ + float * restrict out_row = out_vtcm + (size_t) ohi * w_in; \ + \ + HVX_Vector p0 = zero, c0 = hvx_vmem(r0); \ + HVX_Vector p1 = zero, c1 = hvx_vmem(r1); \ + HVX_Vector p2 = zero, c2 = hvx_vmem(r2); \ + \ + for (uint32_t ox = 0; ox < w_in; ox += 32) { \ + const bool has_next = (ox + 32 < w_in); \ + \ + const HVX_Vector n0 = has_next ? hvx_vmem(r0 + ox + 32) : zero; \ + const HVX_Vector l0 = Q6_V_valign_VVR(c0, p0, 124); \ + const HVX_Vector rg0 = Q6_V_valign_VVR(n0, c0, 4); \ + HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, l0, w00, c0, w01, rg0, w02); \ + p0 = c0; c0 = n0; \ + \ + const HVX_Vector n1 = has_next ? hvx_vmem(r1 + ox + 32) : zero; \ + const HVX_Vector l1 = Q6_V_valign_VVR(c1, p1, 124); \ + const HVX_Vector rg1 = Q6_V_valign_VVR(n1, c1, 4); \ + acc = conv2d_dw_qf32_mpy_add3(acc, l1, w10, c1, w11, rg1, w12); \ + p1 = c1; c1 = n1; \ + \ + const HVX_Vector n2 = has_next ? hvx_vmem(r2 + ox + 32) : zero; \ + const HVX_Vector l2 = Q6_V_valign_VVR(c2, p2, 124); \ + const HVX_Vector rg2 = Q6_V_valign_VVR(n2, c2, 4); \ + acc = conv2d_dw_qf32_mpy_add3(acc, l2, w20, c2, w21, rg2, w22); \ + p2 = c2; c2 = n2; \ + \ + hvx_vmem(out_row + ox) = Q6_Vsf_equals_Vqf32(acc); \ + } \ + } \ +} + +DEFINE_CONV2D_DW_WHCN_S1_K3X3(f32, conv2d_dw_splat_w_f32) +DEFINE_CONV2D_DW_WHCN_S1_K3X3(f16, conv2d_dw_splat_w_f16) + +#define DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(SUFFIX, SPLAT_W_FN) \ +__attribute__((noinline)) \ +static void conv2d_dw_whcn_s2_k3x3_w32_##SUFFIX( \ + const float * restrict in_vtcm, \ + float * restrict out_vtcm, \ + const void * w_vtcm, \ + const struct conv2d_dw_task_slice * slice, \ + const struct htp_ops_context * octx, \ + const struct htp_conv2d_dw_kernel_params * kp) { \ + \ + (void) kp; \ + const struct htp_tensor * src0 = octx->src[0]; \ + const size_t w_nb0 = src0->nb[0]; \ + const size_t w_nb1 = src0->nb[1]; \ + const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ + const uint32_t oh_len = slice->oh_len; \ + \ + conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, 32, (oh_len & 1) ? 2 : 0); \ + \ + const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector zero = Q6_V_vzero(); \ + \ + const HVX_VectorPred q_not_lane16 = Q6_Q_or_QQn(Q6_Q_vsetq_R(64), Q6_Q_vsetq2_R(68)); \ + const float * restrict in_row = in_vtcm; \ + HVX_Vector v_prev_b2 = hvx_vmem(in_row); \ + in_row += 32; \ + \ + for (uint32_t ohi = 0; ohi < oh_len; ohi += 2) { \ + const HVX_Vector v_a0 = v_prev_b2; \ + const HVX_Vector v_a1 = hvx_vmem(in_row); \ + const HVX_Vector v_a2 = hvx_vmem(in_row + 32); \ + const HVX_Vector v_b0 = v_a2; \ + const HVX_Vector v_b1 = hvx_vmem(in_row + 64); \ + const HVX_Vector v_b2 = hvx_vmem(in_row + 96); \ + in_row += 128; \ + v_prev_b2 = v_b2; \ + \ + const HVX_VectorPair vp0 = Q6_W_vdeal_VVR(v_b0, v_a0, -4); \ + const HVX_Vector ev0 = Q6_V_lo_W(vp0); \ + const HVX_Vector od0 = Q6_V_hi_W(vp0); \ + const HVX_Vector lf0 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od0, zero, 124)); \ + HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \ + \ + const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(v_b1, v_a1, -4); \ + const HVX_Vector ev1 = Q6_V_lo_W(vp1); \ + const HVX_Vector od1 = Q6_V_hi_W(vp1); \ + const HVX_Vector lf1 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od1, zero, 124)); \ + acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \ + \ + const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(v_b2, v_a2, -4); \ + const HVX_Vector ev2 = Q6_V_lo_W(vp2); \ + const HVX_Vector od2 = Q6_V_hi_W(vp2); \ + const HVX_Vector lf2 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od2, zero, 124)); \ + acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \ + \ + hvx_vmem(out_vtcm + (size_t) ohi * 16) = Q6_Vsf_equals_Vqf32(acc); \ + } \ +} + +DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(f32, conv2d_dw_splat_w_f32) +DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(f16, conv2d_dw_splat_w_f16) + +#define DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(SUFFIX, SPLAT_W_FN) \ +__attribute__((noinline)) \ +static void conv2d_dw_whcn_s2_k3x3_w64_##SUFFIX( \ + const float * restrict in_vtcm, \ + float * restrict out_vtcm, \ + const void * w_vtcm, \ + const struct conv2d_dw_task_slice * slice, \ + const struct htp_ops_context * octx, \ + const struct htp_conv2d_dw_kernel_params * kp) { \ + \ + (void) kp; \ + const struct htp_tensor * src0 = octx->src[0]; \ + const size_t w_nb0 = src0->nb[0]; \ + const size_t w_nb1 = src0->nb[1]; \ + const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ + const uint32_t oh_len = slice->oh_len; \ + \ + conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, 64, 0); \ + \ + const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector zero = Q6_V_vzero(); \ + \ + const float * restrict in_row = in_vtcm; \ + const HVX_VectorPair vp0_init = Q6_W_vdeal_VVR(hvx_vmem(in_row + 32), hvx_vmem(in_row), -4); \ + in_row += 64; \ + HVX_Vector ev0 = Q6_V_lo_W(vp0_init); \ + HVX_Vector od0 = Q6_V_hi_W(vp0_init); \ + HVX_Vector lf0 = Q6_V_valign_VVR(od0, zero, 124); \ + \ + for (uint32_t ohi = 0; ohi < oh_len; ++ohi) { \ + const float * restrict r1_ptr = in_row; \ + const float * restrict r2_ptr = in_row + 64; \ + in_row += 128; \ + \ + HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \ + \ + const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(hvx_vmem(r1_ptr + 32), hvx_vmem(r1_ptr), -4); \ + const HVX_Vector ev1 = Q6_V_lo_W(vp1); \ + const HVX_Vector od1 = Q6_V_hi_W(vp1); \ + const HVX_Vector lf1 = Q6_V_valign_VVR(od1, zero, 124); \ + acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \ + \ + const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(hvx_vmem(r2_ptr + 32), hvx_vmem(r2_ptr), -4); \ + const HVX_Vector ev2 = Q6_V_lo_W(vp2); \ + const HVX_Vector od2 = Q6_V_hi_W(vp2); \ + const HVX_Vector lf2 = Q6_V_valign_VVR(od2, zero, 124); \ + acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \ + \ + hvx_vmem(out_vtcm + (size_t) ohi * 32) = Q6_Vsf_equals_Vqf32(acc); \ + \ + ev0 = ev2; \ + od0 = od2; \ + lf0 = lf2; \ + } \ +} + +DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(f32, conv2d_dw_splat_w_f32) +DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(f16, conv2d_dw_splat_w_f16) + +#define DEFINE_CONV2D_DW_WHCN_S2_K3X3(SUFFIX, SPLAT_W_FN) \ +__attribute__((noinline)) \ +static void conv2d_dw_whcn_s2_k3x3_##SUFFIX( \ + const float * restrict in_vtcm, \ + float * restrict out_vtcm, \ + const void * w_vtcm, \ + const struct conv2d_dw_task_slice * slice, \ + const struct htp_ops_context * octx, \ + const struct htp_conv2d_dw_kernel_params * kp) { \ + \ + const struct htp_tensor * src0 = octx->src[0]; \ + const size_t w_nb0 = src0->nb[0]; \ + const size_t w_nb1 = src0->nb[1]; \ + const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ + const uint32_t oh_len = slice->oh_len; \ + const uint32_t w_in = kp->w; \ + const uint32_t ow = kp->ow; \ + \ + conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, w_in, 0); \ + \ + const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ + const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ + const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ + const HVX_Vector zero = Q6_V_vzero(); \ + \ + for (uint32_t ohi = 0; ohi < oh_len; ++ohi) { \ + const float * restrict r0 = in_vtcm + (size_t) (2 * ohi) * w_in; \ + const float * restrict r1 = r0 + w_in; \ + const float * restrict r2 = r1 + w_in; \ + float * restrict out_row = out_vtcm + (size_t) ohi * ow; \ + \ + HVX_Vector prev_od0 = zero; \ + HVX_Vector prev_od1 = zero; \ + HVX_Vector prev_od2 = zero; \ + \ + for (uint32_t ox = 0; ox < ow; ox += 32) { \ + const uint32_t ix = 2 * ox; \ + const bool has1 = (ix + 32 < w_in); \ + \ + const HVX_VectorPair vp0 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r0 + ix + 32) : zero, hvx_vmem(r0 + ix), -4); \ + const HVX_Vector ev0 = Q6_V_lo_W(vp0); \ + const HVX_Vector od0 = Q6_V_hi_W(vp0); \ + const HVX_Vector lf0 = Q6_V_valign_VVR(od0, prev_od0, 124); \ + prev_od0 = od0; \ + HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \ + \ + const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r1 + ix + 32) : zero, hvx_vmem(r1 + ix), -4); \ + const HVX_Vector ev1 = Q6_V_lo_W(vp1); \ + const HVX_Vector od1 = Q6_V_hi_W(vp1); \ + const HVX_Vector lf1 = Q6_V_valign_VVR(od1, prev_od1, 124); \ + prev_od1 = od1; \ + acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \ + \ + const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r2 + ix + 32) : zero, hvx_vmem(r2 + ix), -4); \ + const HVX_Vector ev2 = Q6_V_lo_W(vp2); \ + const HVX_Vector od2 = Q6_V_hi_W(vp2); \ + const HVX_Vector lf2 = Q6_V_valign_VVR(od2, prev_od2, 124); \ + prev_od2 = od2; \ + acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \ + \ + if (ox + 32 <= ow) { \ + hvx_vmem(out_row + ox) = Q6_Vsf_equals_Vqf32(acc); \ + } else { \ + const uint32_t rem = ow - ox; \ + const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \ + hvx_vec_store_u(out_row + ox, rem * sizeof(float), Q6_V_vmux_QVV(q, Q6_Vsf_equals_Vqf32(acc), zero)); \ + } \ + } \ + } \ +} + +DEFINE_CONV2D_DW_WHCN_S2_K3X3(f32, conv2d_dw_splat_w_f32) +DEFINE_CONV2D_DW_WHCN_S2_K3X3(f16, conv2d_dw_splat_w_f16) + +#define DEFINE_CONV2D_DW_WHCN_S1(SUFFIX, SPLAT_W_FN) \ +__attribute__((noinline)) \ +static void conv2d_dw_whcn_s1_##SUFFIX( \ + const float * in_vtcm, \ + float * out_vtcm, \ + const void * w_vtcm, \ + const struct conv2d_dw_task_slice * slice, \ + const struct htp_ops_context * octx, \ + const struct htp_conv2d_dw_kernel_params * kp) { \ + \ + const struct htp_tensor * src0 = octx->src[0]; \ + const char * w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ + const int32_t p0 = kp->p0; \ + const int32_t p1 = kp->p1; \ + const int32_t s1 = kp->s1; \ + const int32_t d1 = kp->d1; \ + const int32_t w = (int32_t) kp->w; \ + const HVX_Vector zero = Q6_V_vzero(); \ + \ + for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \ + const uint32_t oh = slice->oh_start + ohi; \ + float * out_row = out_vtcm + (size_t) ohi * kp->ow; \ + \ + for (uint32_t ox = 0; ox < kp->ow; ox += 32) { \ + const uint32_t rem = kp->ow - ox; \ + const uint32_t nbytes = (rem < 32) ? (rem * sizeof(float)) : 128; \ + HVX_Vector acc0 = zero; \ + HVX_Vector acc1 = zero; \ + HVX_Vector acc2 = zero; \ + HVX_Vector acc3 = zero; \ + \ + for (uint32_t kh = 0; kh < kp->kh; ++kh) { \ + const int32_t ih = (int32_t) (oh * s1 + kh * d1) - p1; \ + if (ih < 0 || ih >= (int32_t) kp->h) { \ + continue; \ + } \ + const float * in_row = in_vtcm + (size_t) (ih - slice->ih_first) * kp->w; \ + const char * w_row = w_chan + (size_t) kh * src0->nb[1]; \ + \ + for (uint32_t kw = 0; kw < kp->kw; ++kw) { \ + const HVX_Vector w_v = SPLAT_W_FN(w_row + (size_t) kw * src0->nb[0]); \ + const int32_t base_iw = (int32_t) ox - p0 + (int32_t) kw; \ + HVX_Vector in_v; \ + \ + if (base_iw >= 0) { \ + in_v = hvx_vmemu(in_row + base_iw); \ + } else { \ + const int32_t pad = -base_iw; \ + const HVX_Vector v = hvx_vmemu(in_row); \ + in_v = Q6_V_valign_VVR(v, zero, 128 - (uint32_t) pad * sizeof(float)); \ + } \ + if (base_iw + 31 >= w) { \ + const int32_t valid = w - base_iw; \ + const HVX_VectorPred q = Q6_Q_vsetq_R(MAX(0, valid) * sizeof(float)); \ + in_v = Q6_V_vmux_QVV(q, in_v, zero); \ + } \ + \ + const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(in_v, w_v); \ + switch (kw & 3) { \ + case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \ + case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \ + case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \ + case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \ + } \ + } \ + } \ + \ + const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \ + const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \ + HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \ + if (rem < 32) { \ + const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \ + acc_out = Q6_V_vmux_QVV(q, acc_out, zero); \ + } \ + \ + hvx_vec_store_u(out_row + ox, nbytes, acc_out); \ + } \ + } \ +} + +DEFINE_CONV2D_DW_WHCN_S1(f32, conv2d_dw_splat_w_f32) +DEFINE_CONV2D_DW_WHCN_S1(f16, conv2d_dw_splat_w_f16) + +#define DEFINE_CONV2D_DW_WHCN_S2(SUFFIX, SPLAT_W_FN) \ +__attribute__((noinline)) \ +static void conv2d_dw_whcn_s2_##SUFFIX( \ + const float * in_vtcm, \ + float * out_vtcm, \ + const void * w_vtcm, \ + const struct conv2d_dw_task_slice * slice, \ + const struct htp_ops_context * octx, \ + const struct htp_conv2d_dw_kernel_params * kp) { \ + \ + const struct htp_tensor * src0 = octx->src[0]; \ + const char * w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ + const int32_t p0 = kp->p0; \ + const int32_t p1 = kp->p1; \ + const int32_t s1 = kp->s1; \ + const int32_t d1 = kp->d1; \ + const int32_t w = (int32_t) kp->w; \ + const HVX_Vector zero = Q6_V_vzero(); \ + \ + for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \ + const uint32_t oh = slice->oh_start + ohi; \ + float * out_row = out_vtcm + (size_t) ohi * kp->ow; \ + \ + for (uint32_t ox = 0; ox < kp->ow; ox += 32) { \ + const uint32_t rem = kp->ow - ox; \ + const uint32_t nbytes = (rem < 32) ? (rem * sizeof(float)) : 128; \ + HVX_Vector acc0 = zero; \ + HVX_Vector acc1 = zero; \ + HVX_Vector acc2 = zero; \ + HVX_Vector acc3 = zero; \ + \ + for (uint32_t kh = 0; kh < kp->kh; ++kh) { \ + const int32_t ih = (int32_t) (oh * s1 + kh * d1) - p1; \ + if (ih < 0 || ih >= (int32_t) kp->h) { \ + continue; \ + } \ + const float * in_row = in_vtcm + (size_t) (ih - slice->ih_first) * kp->w; \ + const char * w_row = w_chan + (size_t) kh * src0->nb[1]; \ + \ + for (uint32_t kw = 0; kw < kp->kw; ++kw) { \ + const HVX_Vector w_v = SPLAT_W_FN(w_row + (size_t) kw * src0->nb[0]); \ + const int32_t base_iw = (int32_t) (2 * ox) - p0 + (int32_t) kw; \ + HVX_Vector in_v; \ + \ + if (base_iw >= 0) { \ + const HVX_Vector v0 = hvx_vmemu(in_row + base_iw); \ + const HVX_Vector v1 = hvx_vmemu(in_row + base_iw + 32); \ + in_v = Q6_V_lo_W(Q6_W_vdeal_VVR(v1, v0, -4)); \ + } else { \ + const int32_t pad = -base_iw; \ + const HVX_Vector v0 = hvx_vmemu(in_row); \ + const HVX_Vector v1 = hvx_vmemu(in_row + 32); \ + const HVX_VectorPair vp = Q6_W_vdeal_VVR(v1, v0, -4); \ + if (pad & 1) { \ + const uint32_t shift_lanes = (uint32_t) (pad + 1) / 2; \ + const HVX_Vector v_odd = Q6_V_hi_W(vp); \ + in_v = Q6_V_valign_VVR(v_odd, zero, 128 - shift_lanes * sizeof(float)); \ + } else { \ + const uint32_t shift_lanes = (uint32_t) pad / 2; \ + const HVX_Vector v_even = Q6_V_lo_W(vp); \ + in_v = Q6_V_valign_VVR(v_even, zero, 128 - shift_lanes * sizeof(float)); \ + } \ + } \ + if (base_iw + 62 >= w) { \ + const int32_t valid = (w - base_iw + 1) / 2; \ + const HVX_VectorPred q = Q6_Q_vsetq_R(MAX(0, valid) * sizeof(float)); \ + in_v = Q6_V_vmux_QVV(q, in_v, zero); \ + } \ + \ + const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(in_v, w_v); \ + switch (kw & 3) { \ + case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \ + case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \ + case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \ + case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \ + } \ + } \ + } \ + \ + const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \ + const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \ + HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \ + if (rem < 32) { \ + const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \ + acc_out = Q6_V_vmux_QVV(q, acc_out, zero); \ + } \ + \ + hvx_vec_store_u(out_row + ox, nbytes, acc_out); \ + } \ + } \ +} + +DEFINE_CONV2D_DW_WHCN_S2(f32, conv2d_dw_splat_w_f32) +DEFINE_CONV2D_DW_WHCN_S2(f16, conv2d_dw_splat_w_f16) + +#define DEFINE_CONV2D_DW_CWHN(SUFFIX, LOAD_W_FN) \ +__attribute__((noinline)) \ +static void conv2d_dw_cwhn_##SUFFIX( \ + const float * in_vtcm, \ + float * out_vtcm, \ + const void * w_vtcm, \ + const struct conv2d_dw_task_slice * slice, \ + const struct htp_ops_context * octx, \ + const struct htp_conv2d_dw_kernel_params * kp) { \ + \ + const struct htp_tensor * src0 = octx->src[0]; \ + const uint32_t in_row_stride = kp->w * kp->c; \ + const uint32_t out_row_stride = kp->ow * kp->c; \ + const HVX_Vector zero = Q6_V_vzero(); \ + \ + for (uint32_t cb = 0; cb < kp->c; cb += 32) { \ + const uint32_t rem = MIN(32, kp->c - cb); \ + const char * w_base = (const char *) w_vtcm + (size_t) cb * src0->nb[3]; \ + \ + for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \ + const uint32_t oh = slice->oh_start + ohi; \ + float * out_row = out_vtcm + (size_t) ohi * out_row_stride + cb; \ + \ + for (uint32_t ow = 0; ow < kp->ow; ++ow) { \ + HVX_Vector acc0 = zero; \ + HVX_Vector acc1 = zero; \ + HVX_Vector acc2 = zero; \ + HVX_Vector acc3 = zero; \ + \ + for (uint32_t kh = 0; kh < kp->kh; ++kh) { \ + const int32_t ih = (int32_t)(oh * kp->s1 + kh * kp->d1) - kp->p1; \ + if (ih < 0 || ih >= (int32_t)kp->h) { \ + continue; \ + } \ + const float * in_row = in_vtcm + (size_t)(ih - slice->ih_first) * in_row_stride + cb; \ + const char * w_row = w_base + (size_t) kh * src0->nb[1]; \ + \ + for (uint32_t kw = 0; kw < kp->kw; ++kw) { \ + const int32_t iw = (int32_t)(ow * kp->s0 + kw * kp->d0) - kp->p0; \ + if (iw < 0 || iw >= (int32_t)kp->w) { \ + continue; \ + } \ + \ + const float * in_ptr = in_row + (size_t) iw * kp->c; \ + const char * w_ptr = w_row + (size_t) kw * src0->nb[0]; \ + const HVX_Vector v_in = hvx_vmemu(in_ptr); \ + const HVX_Vector v_w = LOAD_W_FN(w_ptr); \ + const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(v_in, v_w); \ + switch (kw & 3) { \ + case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \ + case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \ + case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \ + case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \ + } \ + } \ + } \ + \ + const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \ + const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \ + const HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \ + \ + float * dst_ptr = out_row + (size_t) ow * kp->c; \ + if (rem == 32) { \ + hvx_vmemu(dst_ptr) = acc_out; \ + } else { \ + hvx_vec_store_u(dst_ptr, rem * sizeof(float), acc_out); \ + } \ + } \ + } \ + } \ +} + +DEFINE_CONV2D_DW_CWHN(f32, conv2d_dw_load_w_f32) +DEFINE_CONV2D_DW_CWHN(f16, conv2d_dw_load_w_f16) + +typedef void (*conv2d_dw_compute_fn_t)( + const float * in_vtcm, + float * out_vtcm, + const void * w_vtcm, + const struct conv2d_dw_task_slice * slice, + const struct htp_ops_context * octx, + const struct htp_conv2d_dw_kernel_params * kp); + +static const conv2d_dw_compute_fn_t conv2d_dw_kernels[HTP_CONV2D_DW_KERNEL_COUNT][2] = { + [HTP_CONV2D_DW_KERNEL_UNSUPPORTED] = { NULL, NULL }, + [HTP_CONV2D_DW_KERNEL_CWHN] = { conv2d_dw_cwhn_f32, conv2d_dw_cwhn_f16 }, + [HTP_CONV2D_DW_KERNEL_WHCN_S1] = { conv2d_dw_whcn_s1_f32, conv2d_dw_whcn_s1_f16 }, + [HTP_CONV2D_DW_KERNEL_WHCN_S2] = { conv2d_dw_whcn_s2_f32, conv2d_dw_whcn_s2_f16 }, + [HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3] = { conv2d_dw_whcn_s1_k3x3_f32, conv2d_dw_whcn_s1_k3x3_f16 }, + [HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W32] = { conv2d_dw_whcn_s2_k3x3_w32_f32, conv2d_dw_whcn_s2_k3x3_w32_f16 }, + [HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W64] = { conv2d_dw_whcn_s2_k3x3_w64_f32, conv2d_dw_whcn_s2_k3x3_w64_f16 }, + [HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3] = { conv2d_dw_whcn_s2_k3x3_f32, conv2d_dw_whcn_s2_k3x3_f16 }, +}; + +// ---- 5x5 s1 p2 d1 WHCN kernel ---- + +typedef void (*conv_2d_dw5_prep_weights_fn)(const void * restrict, HVX_Vector * restrict); +typedef void (*conv_2d_dw5_plane_fn)(const uint8_t * restrict, const HVX_Vector * restrict, void * restrict, uint32_t, uint32_t, uint32_t); + +struct conv_2d_dw5_hvx_context { + struct htp_ops_context * octx; + struct htp_conv2d_dw5_vtcm_layout layout; + conv_2d_dw5_prep_weights_fn prep_weights_fn; + conv_2d_dw5_plane_fn plane_fn; + uint32_t weight_bytes; + uint32_t halo_offset; + uint32_t plane_start; + uint32_t plane_count; + uint32_t planes_per_thread; +}; + +// Zero both source slots once per thread; DMA only writes the interior, so the 2-pixel halo stays zero. +static __attribute__((noinline)) void conv_2d_dw5_clear(uint8_t * restrict data, uint32_t bytes) { + const HVX_Vector zero = Q6_V_vzero(); + for (uint32_t offset = 0; offset < bytes; offset += VLEN) { + *(HVX_Vector *) (data + offset) = zero; + } +} + +static inline __attribute__((always_inline)) void conv_2d_dw5_splat_weights(HVX_Vector w, HVX_Vector * restrict wsplat) { + for (uint32_t t = 0; t < 25; ++t) { + wsplat[t] = hvx_vec_repl4(Q6_V_vror_VR(w, t * sizeof(float))); + } +} + +static __attribute__((noinline)) void conv_2d_dw5_prep_weights_f16(const void * restrict wsrc, HVX_Vector * restrict wsplat) { + conv_2d_dw5_splat_weights(Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) wsrc)), wsplat); +} + +static __attribute__((noinline)) void conv_2d_dw5_prep_weights_f32(const void * restrict wsrc, HVX_Vector * restrict wsplat) { + conv_2d_dw5_splat_weights(*(const HVX_Vector *) wsrc, wsplat); +} + +// One output plane. src rows are 128B aligned with the 2-pixel left halo at the row start, so the five kx taps +// of a 32-wide output vector are valigns of two aligned loads. +static inline __attribute__((always_inline)) void conv_2d_dw5_plane_impl(const uint8_t * restrict src, + const HVX_Vector * restrict wsplat, + void * restrict dst, + uint32_t src_row_stride, + uint32_t ow, + uint32_t oh, + const bool src_f16, + const bool dst_f16) { + for (uint32_t oy = 0; oy < oh; ++oy) { + for (uint32_t ox = 0; ox < ow; ox += 2 * VLEN_FP32) { + HVX_Vector acc0 = Q6_V_vzero(); + HVX_Vector acc1 = Q6_V_vzero(); + + for (uint32_t ky = 0; ky < 5; ++ky) { + const HVX_Vector * w = wsplat + ky * 5; + HVX_Vector v0, v1, v2; + if (src_f16) { + const HVX_Vector * row = (const HVX_Vector *) (src + (oy + ky) * src_row_stride + ox * sizeof(__fp16)); + const HVX_VectorPair p0 = hvx_vec_f16_to_f32(row[0]); + v0 = Q6_V_lo_W(p0); + v1 = Q6_V_hi_W(p0); + v2 = Q6_V_lo_W(hvx_vec_f16_to_f32(row[1])); + } else { + const HVX_Vector * row = (const HVX_Vector *) (src + (oy + ky) * src_row_stride + ox * sizeof(float)); + v0 = row[0]; + v1 = row[1]; + v2 = row[2]; + } + + const HVX_Vector a01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(v0, w[0]), + Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 4), w[1])); + const HVX_Vector a23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 8), w[2]), + Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 12), w[3])); + const HVX_Vector a4 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 16), w[4])); + acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a01, a23), a4); + + const HVX_Vector b01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(v1, w[0]), + Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 4), w[1])); + const HVX_Vector b23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 8), w[2]), + Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 12), w[3])); + const HVX_Vector b4 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 16), w[4])); + acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(b01, b23), b4); + } + + const uint32_t rem = ow - ox; + if (dst_f16) { + __fp16 * out = (__fp16 *) dst + oy * ow + ox; + const HVX_Vector out_f16 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(acc1, acc0))); + hvx_vec_store_u(out, MIN(rem, VLEN_FP16) * sizeof(__fp16), out_f16); + } else { + float * out = (float *) dst + oy * ow + ox; + hvx_vec_store_u(out, MIN(rem, VLEN_FP32) * sizeof(float), Q6_Vsf_equals_Vqf32(acc0)); + if (rem > VLEN_FP32) { + hvx_vec_store_u(out + VLEN_FP32, MIN(rem - VLEN_FP32, VLEN_FP32) * sizeof(float), + Q6_Vsf_equals_Vqf32(acc1)); + } + } + } + } +} + +static __attribute__((noinline)) void conv_2d_dw5_plane_f32_f32(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { + conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, false, false); +} + +static __attribute__((noinline)) void conv_2d_dw5_plane_f32_f16(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { + conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, false, true); +} + +static __attribute__((noinline)) void conv_2d_dw5_plane_f16_f32(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { + conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, true, false); +} + +static __attribute__((noinline)) void conv_2d_dw5_plane_f16_f16(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { + conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, true, true); +} + +struct conv_2d_dw5_pipe_state { + dma_addr_t w_data; + dma_addr_t in_data; + dma_addr_t out_data; + HVX_Vector * wsplat; + conv_2d_dw5_prep_weights_fn prep_weights_fn; + conv_2d_dw5_plane_fn plane_fn; + uint32_t plane; + uint32_t last; + uint32_t c_next; + uint32_t channels; + uint32_t ih; + uint32_t ow; + uint32_t oh; + uint32_t stride; + uint32_t in_row; + uint32_t in_plane; + uint32_t out_row; + uint32_t out_plane; + uint32_t w_plane; + uint32_t weight_bytes; + uint32_t halo_offset; +}; + +static bool conv_2d_dw5_next_task(void * ctx, struct dma_pipe_task * task) { + struct conv_2d_dw5_pipe_state * s = (struct conv_2d_dw5_pipe_state *) ctx; + if (s->plane >= s->last) { + return false; + } + task->row = s->plane; + task->aux = s->c_next; + s->plane++; + s->c_next = (s->c_next + 1 == s->channels) ? 0 : s->c_next + 1; + return true; +} + +static void conv_2d_dw5_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) { + const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx; + dma_queue_push(dma_q, dma_make_data(in0_spad, s->w_data + (dma_addr_t) task->aux * s->w_plane), + VLEN, s->w_plane, s->weight_bytes, 1); + dma_queue_push(dma_q, dma_make_data(in1_spad, s->in_data + (dma_addr_t) task->row * s->in_plane), + s->stride, s->in_row, s->in_row, s->ih); +} + +static void conv_2d_dw5_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) { + (void) task; + const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx; + s->prep_weights_fn(in0_spad, s->wsplat); + s->plane_fn((const uint8_t *) in1_spad - s->halo_offset, s->wsplat, out_spad, s->stride, s->ow, s->oh); +} + +static void conv_2d_dw5_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx; + dma_queue_push(dma_q, dma_make_data(s->out_data + (dma_addr_t) task->row * s->out_plane, out_spad), + s->out_row, s->out_row, s->out_row, s->oh); +} + +// Planes are processed in memory order (plane = n * C + c). Each plane is three DMAs: weights in, src in, dst out. +// Two buffers per stream: plane i+1 is in flight while plane i is computed. +static void conv_2d_dw5_hvx_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + const struct conv_2d_dw5_hvx_context * ctx = (const struct conv_2d_dw5_hvx_context *) data; + const struct htp_ops_context * octx = ctx->octx; + const struct htp_conv2d_dw5_vtcm_layout * L = &ctx->layout; + const struct htp_tensor * weight = octx->src[0]; + const struct htp_tensor * input = octx->src[1]; + const struct htp_tensor * output = octx->dst; + + const uint32_t first = ctx->plane_start + ith * ctx->planes_per_thread; + const uint32_t last = MIN(first + ctx->planes_per_thread, ctx->plane_start + ctx->plane_count); + if (first >= last) { + return; + } + + uint8_t * vtcm = octx->ctx->vtcm_base; + uint8_t * src_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_src) + ith * 2 * L->src_slot_bytes; + uint8_t * weight_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_weight) + ith * HTP_CONV2D_DW5_W_BYTES; + uint8_t * dst_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_dst) + ith * 2 * L->dst_slot_bytes; + const uint32_t halo_offset = ctx->halo_offset; + + void * in0_buf[2] = { weight_base, weight_base + VLEN }; + void * in1_buf[2] = { src_base + halo_offset, src_base + L->src_slot_bytes + halo_offset }; + void * out_buf[2] = { dst_base, dst_base + L->dst_slot_bytes }; + + conv_2d_dw5_clear(src_base, 2 * L->src_slot_bytes); + + struct conv_2d_dw5_pipe_state s = { + .w_data = weight->data, + .in_data = input->data, + .out_data = output->data, + .wsplat = (HVX_Vector *) (weight_base + 2 * VLEN), + .prep_weights_fn = ctx->prep_weights_fn, + .plane_fn = ctx->plane_fn, + .plane = first, + .last = last, + .c_next = first % input->ne[2], + .channels = input->ne[2], + .ih = input->ne[1], + .ow = output->ne[0], + .oh = output->ne[1], + .stride = L->src_row_stride, + .in_row = input->nb[1], + .in_plane = input->nb[2], + .out_row = output->nb[1], + .out_plane = output->nb[2], + .w_plane = weight->nb[3], + .weight_bytes = ctx->weight_bytes, + .halo_offset = halo_offset, + }; + + dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf, + conv_2d_dw5_next_task, conv_2d_dw5_push_in, conv_2d_dw5_compute, conv_2d_dw5_push_out); + + FARF(HIGH, "conv2d-dw-hvx-dma-5x5 %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n", ith, nth, input->ne[0], + input->ne[1], input->ne[2], input->ne[3], output->ne[0], output->ne[1], output->ne[2], output->ne[3], first, + last); +} + +static int op_conv_2d_dw5(struct htp_ops_context * octx) { + // Tensor shapes, types and VTCM sizing were validated by the host (htp_kparams_solve_conv2d_dw). + const struct htp_conv2d_dw_kernel_params * kp = (const struct htp_conv2d_dw_kernel_params *) octx->kernel_params; + + uint32_t plane_start = 0; + uint32_t plane_count = kp->total_tasks; + + if (octx->ctx->mdev.count > 1) { + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + plane_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + plane_start = range.start; + plane_count = range.count; + } + if (plane_count == 0) { + return HTP_STATUS_OK; + } + + static const conv_2d_dw5_plane_fn plane_fns[2][2] = { + { conv_2d_dw5_plane_f32_f32, conv_2d_dw5_plane_f32_f16 }, + { conv_2d_dw5_plane_f16_f32, conv_2d_dw5_plane_f16_f16 }, + }; + + const bool w_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0; + const bool src_f16 = (octx->src[1]->type == HTP_TYPE_F16); + const bool dst_f16 = (octx->dst->type == HTP_TYPE_F16); + const size_t src_es = src_f16 ? sizeof(__fp16) : sizeof(float); + const size_t dst_es = dst_f16 ? sizeof(__fp16) : sizeof(float); + const uint32_t weight_bytes = 25 * (w_f16 ? sizeof(__fp16) : sizeof(float)); + + struct htp_conv2d_dw5_vtcm_layout layout; + htp_conv2d_dw5_vtcm_layout_build(&layout, kp->w, kp->h, src_es, dst_es, kp->n_hvx); + + const uint32_t n_threads = MIN(kp->n_hvx, plane_count); + const uint32_t planes_per_thread = (plane_count + n_threads - 1) / n_threads; + struct conv_2d_dw5_hvx_context ctx = { + .octx = octx, + .layout = layout, + .prep_weights_fn = w_f16 ? conv_2d_dw5_prep_weights_f16 : conv_2d_dw5_prep_weights_f32, + .plane_fn = plane_fns[src_f16][dst_f16], + .weight_bytes = weight_bytes, + .halo_offset = 2 * layout.src_row_stride + 2 * src_es, + .plane_start = plane_start, + .plane_count = plane_count, + .planes_per_thread = planes_per_thread, + }; + + work_queue_run(octx->ctx->hvx_queue, conv_2d_dw5_hvx_thread, &ctx, n_threads); + return HTP_STATUS_OK; +} + +typedef void (*conv2d_dw_cvt_fn_t)(float * buf, uint32_t n_elems); + +// Expand n_elems f16 values to f32 in-place walking backwards (128B aligned buf with f32 capacity). +static __attribute__((noinline)) void conv2d_dw_expand_f16_to_f32_inplace(float * buf, uint32_t n_elems) { + const uint32_t full = n_elems & ~63u; + const uint32_t rem = n_elems - full; + if (rem > 0) { + const HVX_Vector v = hvx_vmem((const __fp16 *) buf + full); + const HVX_VectorPair p = hvx_vec_f16_to_f32(v); + if (rem <= VLEN_FP32) { + hvx_vec_store_a(buf + full, rem * sizeof(float), Q6_V_lo_W(p)); + } else { + hvx_vmem(buf + full) = Q6_V_lo_W(p); + hvx_vec_store_a(buf + full + VLEN_FP32, (rem - VLEN_FP32) * sizeof(float), Q6_V_hi_W(p)); + } + } + for (int32_t i = (int32_t) full - 64; i >= 0; i -= 64) { + const HVX_Vector v = hvx_vmem((const __fp16 *) buf + i); + const HVX_VectorPair p = hvx_vec_f16_to_f32(v); + hvx_vmem(buf + i + VLEN_FP32) = Q6_V_hi_W(p); + hvx_vmem(buf + i) = Q6_V_lo_W(p); + } +} + +// Pack n_elems f32 values to f16 in-place walking forwards (128B aligned buf). +static __attribute__((noinline)) void conv2d_dw_pack_f32_to_f16_inplace(float * buf, uint32_t n_elems) { + uint32_t i = 0; + for (; i + 64 <= n_elems; i += 64) { + const HVX_Vector v0 = hvx_vmem(buf + i); + const HVX_Vector v1 = hvx_vmem(buf + i + VLEN_FP32); + hvx_vmem((__fp16 *) buf + i) = hvx_vec_f32_to_f16(v0, v1); + } + const uint32_t rem = n_elems - i; + if (rem > 0) { + const HVX_Vector v0 = hvx_vmem(buf + i); + const HVX_Vector v1 = (rem > VLEN_FP32) ? hvx_vmem(buf + i + VLEN_FP32) : Q6_V_vzero(); + hvx_vec_store_a((__fp16 *) buf + i, rem * sizeof(__fp16), hvx_vec_f32_to_f16(v0, v1)); + } +} + +struct conv2d_dw_dma_context { + struct htp_ops_context * octx; + const struct htp_conv2d_dw_kernel_params * kp; + struct htp_conv2d_dw_vtcm_layout layout; + const void * w_vtcm; + conv2d_dw_compute_fn_t compute_fn; + conv2d_dw_cvt_fn_t expand_in_fn; + conv2d_dw_cvt_fn_t pack_out_fn; + uint32_t task_start; + uint32_t task_count; + uint32_t tasks_per_hvx; +}; + +struct conv2d_dw_pipe_state { + const struct htp_ops_context * octx; + const struct htp_conv2d_dw_kernel_params * kp; + const struct htp_tensor * src1; + const struct htp_tensor * dst; + const void * w_vtcm; + conv2d_dw_compute_fn_t compute_fn; + conv2d_dw_cvt_fn_t expand_in_fn; + conv2d_dw_cvt_fn_t pack_out_fn; + uint8_t * src_base[2]; + uint32_t src_spad_half; + uint32_t dst_spad_half; + uint32_t pad_top_stride; + uint32_t task; + uint32_t last; + struct conv2d_dw_task_slice sl[2]; + struct conv2d_dw_task_slice out_sl; +}; + +static bool conv2d_dw_next_task(void * ctx, struct dma_pipe_task * task) { + struct conv2d_dw_pipe_state * s = (struct conv2d_dw_pipe_state *) ctx; + if (s->task >= s->last) { + return false; + } + task->row = s->task++; + return true; +} + +static void conv2d_dw_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in_spad) { + struct conv2d_dw_pipe_state * s = (struct conv2d_dw_pipe_state *) ctx; + const uint32_t slot = ((uint8_t *) in_spad >= s->src_base[1]) ? 1 : 0; + float * srcb = (float *) s->src_base[slot]; + + conv2d_dw_get_slice(&s->sl[slot], task->row, s->src1, s->dst, s->kp); + + float * src_dst = srcb + (size_t) s->sl[slot].top_pad * s->pad_top_stride; + dma_queue_push(dma_q, + dma_make_data(src_dst, s->sl[slot].src_addr), + s->src_spad_half, s->sl[slot].src_bytes, + s->sl[slot].src_bytes, s->sl[slot].src_bytes > 0 ? 1 : 0); +} + +static void conv2d_dw_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in_spad) { + (void) task; + struct conv2d_dw_pipe_state * s = (struct conv2d_dw_pipe_state *) ctx; + const uint32_t slot = ((uint8_t *) in_spad >= s->src_base[1]) ? 1 : 0; + float * srcb = (float *) s->src_base[slot]; + float * dstb = (float *) out_spad; + const struct conv2d_dw_task_slice * sl = &s->sl[slot]; + + if (s->expand_in_fn && sl->src_bytes > 0) { + s->expand_in_fn((float *) in_spad, sl->src_bytes / sizeof(__fp16)); + } + s->compute_fn(srcb, dstb, s->w_vtcm, sl, s->octx, s->kp); + if (s->pack_out_fn && sl->dst_bytes > 0) { + s->pack_out_fn(dstb, sl->dst_bytes / sizeof(__fp16)); + } + s->out_sl = *sl; +} + +static void conv2d_dw_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { + (void) task; + const struct conv2d_dw_pipe_state * s = (const struct conv2d_dw_pipe_state *) ctx; + dma_queue_push(dma_q, + dma_make_data(s->out_sl.dst_addr, out_spad), + s->out_sl.dst_bytes, s->dst_spad_half, + s->out_sl.dst_bytes, s->out_sl.dst_bytes > 0 ? 1 : 0); +} + +static void conv2d_dw_dma_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { + const struct conv2d_dw_dma_context * ctx = (const struct conv2d_dw_dma_context *) data; + const struct htp_ops_context * octx = ctx->octx; + const struct htp_conv2d_dw_kernel_params * kp = ctx->kp; + const struct htp_conv2d_dw_vtcm_layout * L = &ctx->layout; + const struct htp_tensor * dst = octx->dst; + + const uint32_t first = ctx->task_start + ith * ctx->tasks_per_hvx; + const uint32_t last = MIN(first + ctx->tasks_per_hvx, ctx->task_start + ctx->task_count); + if (first >= last) { + return; + } + + (void) nth; + + const uint32_t src_spad_half = (uint32_t) L->src_spad_half_size; + const uint32_t dst_spad_half = (uint32_t) L->dst_spad_half_size; + + uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base; + uint8_t * src_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_src) + ith * L->src_bytes_per_hvx; + uint8_t * dst_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_dst) + ith * L->dst_bytes_per_hvx; + + void * in_buf[2] = { src_spad, src_spad + src_spad_half }; + void * out_buf[2] = { dst_spad, dst_spad + dst_spad_half }; + + struct conv2d_dw_pipe_state s = { + .octx = octx, + .kp = kp, + .src1 = octx->src[1], + .dst = dst, + .w_vtcm = ctx->w_vtcm, + .compute_fn = ctx->compute_fn, + .expand_in_fn = ctx->expand_in_fn, + .pack_out_fn = ctx->pack_out_fn, + .src_base = { src_spad, src_spad + src_spad_half }, + .src_spad_half = src_spad_half, + .dst_spad_half = dst_spad_half, + .pad_top_stride = kp->pad_top_stride, + .task = first, + .last = last, + }; + + dma_pipe_io_run(th->dma_q, th->trace, &s, in_buf, out_buf, + conv2d_dw_next_task, conv2d_dw_push_in, conv2d_dw_compute, conv2d_dw_push_out); + + FARF(HIGH, "conv2d_dw-f32-dma %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n", + ith, nth, kp->w, kp->h, kp->c, dst->ne[3], kp->ow, kp->oh, kp->c, dst->ne[3], first, last); +} + +int op_conv_2d_dw(struct htp_ops_context * octx) { + const struct htp_conv2d_dw_kernel_params * kp = + (const struct htp_conv2d_dw_kernel_params *) octx->kernel_params; + + if (kp->total_tasks == 0) { + return HTP_STATUS_OK; + } + + if (kp->kernel_type <= HTP_CONV2D_DW_KERNEL_UNSUPPORTED || + kp->kernel_type >= HTP_CONV2D_DW_KERNEL_COUNT) { + return HTP_STATUS_NO_SUPPORT; + } + + if (kp->kernel_type == HTP_CONV2D_DW_KERNEL_WHCN_5X5_DMA) { + return op_conv_2d_dw5(octx); + } + + const struct htp_tensor * src0 = octx->src[0]; + const bool cwhn = (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) != 0; + const bool is_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0; + const uint32_t elem_size = is_f16 ? sizeof(__fp16) : sizeof(float); + const uint32_t w_size = src0->size; + + struct htp_conv2d_dw_vtcm_layout layout; + htp_conv2d_dw_vtcm_layout_build(&layout, kp->w, kp->h, kp->c, kp->kh, kp->ow, kp->oh_chunk, + kp->s1, kp->d1, cwhn, kp->pad_top_stride > 0, w_size, kp->n_hvx); + + uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base; + void * w_vtcm = VTCM_LAYOUT_PTR(void, vtcm_base, layout.off_w); + + struct htp_tensor w_vtcm_tensor = *src0; + w_vtcm_tensor.data = (dma_addr_t) w_vtcm; + + if (src0->nb[0] == elem_size) { + dma_cpy_sametype_sameshape(octx->ctx->dma[0], &w_vtcm_tensor, src0, elem_size); + } else { + dma_sync_read(octx->ctx->dma[0], w_vtcm, src0->data, w_size); + } + dma_queue_flush(octx->ctx->dma[0]); + + uint32_t task_start = 0; + uint32_t task_count = kp->total_tasks; + if (octx->ctx->mdev.count > 1) { + const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( + task_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); + task_start = range.start; + task_count = range.count; + } + if (task_count == 0) { + return HTP_STATUS_OK; + } + + const uint32_t nth = MIN(kp->n_hvx, task_count); + const uint32_t tasks_per_hvx = (task_count + nth - 1) / nth; + + struct conv2d_dw_dma_context ctx = { + .octx = octx, + .kp = kp, + .layout = layout, + .w_vtcm = w_vtcm, + .compute_fn = conv2d_dw_kernels[kp->kernel_type][is_f16 ? 1 : 0], + .expand_in_fn = (octx->src[1]->type == HTP_TYPE_F16) ? conv2d_dw_expand_f16_to_f32_inplace : NULL, + .pack_out_fn = (octx->dst->type == HTP_TYPE_F16) ? conv2d_dw_pack_f32_to_f16_inplace : NULL, + .task_start = task_start, + .task_count = task_count, + .tasks_per_hvx = tasks_per_hvx, + }; + + work_queue_run(octx->ctx->hvx_queue, conv2d_dw_dma_thread, &ctx, nth); + return HTP_STATUS_OK; +} diff --git a/ggml/src/ggml-hexagon/htp/conv2d-dw-ops.h b/ggml/src/ggml-hexagon/htp/conv2d-dw-ops.h new file mode 100644 index 000000000000..e8126e0e03ea --- /dev/null +++ b/ggml/src/ggml-hexagon/htp/conv2d-dw-ops.h @@ -0,0 +1,144 @@ +#ifndef HTP_CONV2D_DW_OPS_H +#define HTP_CONV2D_DW_OPS_H + +#include +#include + +#include "hex-common.h" +#include "hex-fastdiv.h" +#include "htp-ops.h" +#include "htp-vtcm.h" + +enum htp_conv2d_dw_kernel_type { + HTP_CONV2D_DW_KERNEL_UNSUPPORTED = 0, + HTP_CONV2D_DW_KERNEL_CWHN, // CWHN channel-contiguous layout + HTP_CONV2D_DW_KERNEL_WHCN_S1, // WHCN general stride-1 + HTP_CONV2D_DW_KERNEL_WHCN_S2, // WHCN general stride-2 + HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3, // WHCN aligned w%32==0, 3x3 s=1 p=1 d=1 + HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W32, // WHCN w=32->ow=16, 3x3 s=2 p=1 d=1 (2 rows per vector) + HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W64, // WHCN w=64->ow=32, 3x3 s=2 p=1 d=1 (1 vector rolling kh) + HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3, // WHCN aligned w%32==0 (w>=96), 3x3 s=2 p=1 d=1 + HTP_CONV2D_DW_KERNEL_WHCN_5X5_DMA, // WHCN 5x5 s=1 p=2 d=1, DMA row halo + HTP_CONV2D_DW_KERNEL_COUNT, +}; + +enum htp_conv2d_dw_flags { + HTP_CONV2D_DW_FLAG_CWHN = (1u << 0), + HTP_CONV2D_DW_FLAG_F16 = (1u << 1), +}; + +// WHCN_5X5_DMA VTCM layout shared by host and NPU: per-thread weight area (2 f16 slots + 25 f32 splats, rounded +// up) and the source slot tail for the valign over-read past the last row. +#define HTP_CONV2D_DW5_W_BYTES (32 * 128) +#define HTP_CONV2D_DW5_SRC_TAIL (3 * 128) + +struct htp_conv2d_dw_kernel_params { + uint8_t kernel_type; + uint8_t flags; // bitmask of enum htp_conv2d_dw_flags + uint8_t n_hvx; + + uint32_t total_tasks; + uint32_t vtcm_size; + uint32_t w; + uint32_t h; + uint32_t c; + uint32_t kw; + uint32_t kh; + uint32_t ow; + uint32_t oh; + int32_t s0; + int32_t s1; + int32_t p0; + int32_t p1; + int32_t d0; + int32_t d1; + uint32_t oh_chunk; + uint32_t n_chunks; + uint32_t row_src_bytes; + uint32_t row_dst_bytes; + uint32_t pad_top_stride; + struct fastdiv_values div_c; + struct fastdiv_values div_n_chunks; +}; + +#if defined(__cplusplus) +static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob"); +#else +_Static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob"); +#endif + +struct htp_conv2d_dw_vtcm_layout { + size_t total_bytes; + size_t off_w; + size_t off_src; + size_t off_dst; + size_t src_spad_half_size; + size_t dst_spad_half_size; + size_t src_bytes_per_hvx; + size_t dst_bytes_per_hvx; +}; + +static inline void htp_conv2d_dw_vtcm_layout_build( + struct htp_conv2d_dw_vtcm_layout * L, + uint32_t w, + uint32_t h, + uint32_t c, + uint32_t kh, + uint32_t ow, + uint32_t oh_chunk, + int32_t s1, + int32_t d1, + bool cwhn, + bool has_pad_rows, + uint32_t w_size, + uint32_t n_hvx +) { + const uint32_t pad_rows = has_pad_rows ? 4 : 0; + const uint32_t row_src_f32 = (cwhn ? w * c : w) * (uint32_t) sizeof(float); + const uint32_t row_dst_f32 = (cwhn ? ow * c : ow) * (uint32_t) sizeof(float); + const uint32_t max_ih_chunk = MIN(h, (oh_chunk - 1) * (uint32_t) s1 + (kh - 1) * (uint32_t) d1 + 1); + const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * row_src_f32 + 128; + const uint32_t max_dst_bytes = oh_chunk * row_dst_f32 + 128; + + L->src_spad_half_size = hex_round_up(max_src_bytes + 256, 128); + L->dst_spad_half_size = hex_round_up(max_dst_bytes + 128, 128); + L->src_bytes_per_hvx = 2 * L->src_spad_half_size; + L->dst_bytes_per_hvx = 2 * L->dst_spad_half_size; + + size_t off = 0; + VTCM_LAYOUT_ALLOC(off, off_w, hex_round_up(w_size, 128)); + VTCM_LAYOUT_ALLOC(off, off_src, L->src_bytes_per_hvx * n_hvx); + VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx); + L->total_bytes = off; +} + +struct htp_conv2d_dw5_vtcm_layout { + size_t total_bytes; + size_t off_src; + size_t off_weight; + size_t off_dst; + size_t src_row_stride; + size_t src_slot_bytes; + size_t dst_slot_bytes; +}; + +static inline void htp_conv2d_dw5_vtcm_layout_build( + struct htp_conv2d_dw5_vtcm_layout * L, + uint32_t w, + uint32_t h, + size_t src_es, + size_t dst_es, + uint32_t n_hvx +) { + L->src_row_stride = hex_align_up((size_t) (w + 4) * src_es, 128); + L->src_slot_bytes = hex_align_up((size_t) (h + 4) * L->src_row_stride + HTP_CONV2D_DW5_SRC_TAIL, 128); + L->dst_slot_bytes = hex_align_up((size_t) w * h * dst_es, 128); + + size_t off = 0; + VTCM_LAYOUT_ALLOC(off, off_src, (size_t) 2 * n_hvx * L->src_slot_bytes); + VTCM_LAYOUT_ALLOC(off, off_weight, (size_t) n_hvx * HTP_CONV2D_DW5_W_BYTES); + VTCM_LAYOUT_ALLOC(off, off_dst, (size_t) 2 * n_hvx * L->dst_slot_bytes); + L->total_bytes = off; +} + +#endif // HTP_CONV2D_DW_OPS_H diff --git a/ggml/src/ggml-hexagon/htp/conv2d-dw5-ops.c b/ggml/src/ggml-hexagon/htp/conv2d-dw5-ops.c deleted file mode 100644 index d5af8eb0ba73..000000000000 --- a/ggml/src/ggml-hexagon/htp/conv2d-dw5-ops.c +++ /dev/null @@ -1,295 +0,0 @@ -// HVX + DMA kernel for 5x5 stride-1 pad-2 dilation-1 depthwise conv (f16/f32 weights, inputs, and outputs). - -#include "conv2d-ops.h" -#include "dma-pipeline.h" -#include "hex-common.h" -#include "htp-ctx.h" -#include "htp-ops.h" -#include "htp-tensor.h" -#include "hvx-base.h" -#include "hvx-copy.h" - -#include - -typedef void (*conv_2d_dw5_prep_weights_fn)(const void * restrict, HVX_Vector * restrict); -typedef void (*conv_2d_dw5_plane_fn)(const uint8_t * restrict, const HVX_Vector * restrict, void * restrict, uint32_t, uint32_t, uint32_t); - -struct conv_2d_dw5_hvx_context { - struct htp_ops_context * octx; - struct htp_conv2d_dw5_vtcm_layout layout; - conv_2d_dw5_prep_weights_fn prep_weights_fn; - conv_2d_dw5_plane_fn plane_fn; - uint32_t weight_bytes; - uint32_t halo_offset; - uint32_t plane_start; - uint32_t plane_count; - uint32_t planes_per_thread; -}; - -// Zero both source slots once per thread; DMA only writes the interior, so the 2-pixel halo stays zero. -static __attribute__((noinline)) void conv_2d_dw5_clear(uint8_t * restrict data, uint32_t bytes) { - const HVX_Vector zero = Q6_V_vzero(); - for (uint32_t offset = 0; offset < bytes; offset += VLEN) { - *(HVX_Vector *) (data + offset) = zero; - } -} - -static inline __attribute__((always_inline)) void conv_2d_dw5_splat_weights(HVX_Vector w, HVX_Vector * restrict wsplat) { - for (uint32_t t = 0; t < 25; ++t) { - wsplat[t] = hvx_vec_repl4(Q6_V_vror_VR(w, t * sizeof(float))); - } -} - -static __attribute__((noinline)) void conv_2d_dw5_prep_weights_f16(const void * restrict wsrc, HVX_Vector * restrict wsplat) { - conv_2d_dw5_splat_weights(Q6_V_lo_W(hvx_vec_f16_to_f32(*(const HVX_Vector *) wsrc)), wsplat); -} - -static __attribute__((noinline)) void conv_2d_dw5_prep_weights_f32(const void * restrict wsrc, HVX_Vector * restrict wsplat) { - conv_2d_dw5_splat_weights(*(const HVX_Vector *) wsrc, wsplat); -} - -// One output plane. src rows are 128B aligned with the 2-pixel left halo at the row start, so the five kx taps -// of a 32-wide output vector are valigns of two aligned loads. -static inline __attribute__((always_inline)) void conv_2d_dw5_plane_impl(const uint8_t * restrict src, - const HVX_Vector * restrict wsplat, - void * restrict dst, - uint32_t src_row_stride, - uint32_t ow, - uint32_t oh, - const bool src_f16, - const bool dst_f16) { - for (uint32_t oy = 0; oy < oh; ++oy) { - for (uint32_t ox = 0; ox < ow; ox += 2 * VLEN_FP32) { - HVX_Vector acc0 = Q6_V_vzero(); - HVX_Vector acc1 = Q6_V_vzero(); - - for (uint32_t ky = 0; ky < 5; ++ky) { - const HVX_Vector * w = wsplat + ky * 5; - HVX_Vector v0, v1, v2; - if (src_f16) { - const HVX_Vector * row = (const HVX_Vector *) (src + (oy + ky) * src_row_stride + ox * sizeof(__fp16)); - const HVX_VectorPair p0 = hvx_vec_f16_to_f32(row[0]); - v0 = Q6_V_lo_W(p0); - v1 = Q6_V_hi_W(p0); - v2 = Q6_V_lo_W(hvx_vec_f16_to_f32(row[1])); - } else { - const HVX_Vector * row = (const HVX_Vector *) (src + (oy + ky) * src_row_stride + ox * sizeof(float)); - v0 = row[0]; - v1 = row[1]; - v2 = row[2]; - } - - const HVX_Vector a01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(v0, w[0]), - Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 4), w[1])); - const HVX_Vector a23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 8), w[2]), - Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 12), w[3])); - const HVX_Vector a4 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v1, v0, 16), w[4])); - acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(a01, a23), a4); - - const HVX_Vector b01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(v1, w[0]), - Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 4), w[1])); - const HVX_Vector b23 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 8), w[2]), - Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 12), w[3])); - const HVX_Vector b4 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, Q6_Vqf32_vmpy_VsfVsf(Q6_V_valign_VVR(v2, v1, 16), w[4])); - acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(b01, b23), b4); - } - - const uint32_t rem = ow - ox; - if (dst_f16) { - __fp16 * out = (__fp16 *) dst + oy * ow + ox; - const HVX_Vector out_f16 = Q6_Vh_vdeal_Vh(Q6_Vhf_equals_Wqf32(Q6_W_vcombine_VV(acc1, acc0))); - hvx_vec_store_u(out, MIN(rem, VLEN_FP16) * sizeof(__fp16), out_f16); - } else { - float * out = (float *) dst + oy * ow + ox; - hvx_vec_store_u(out, MIN(rem, VLEN_FP32) * sizeof(float), Q6_Vsf_equals_Vqf32(acc0)); - if (rem > VLEN_FP32) { - hvx_vec_store_u(out + VLEN_FP32, MIN(rem - VLEN_FP32, VLEN_FP32) * sizeof(float), - Q6_Vsf_equals_Vqf32(acc1)); - } - } - } - } -} - -static __attribute__((noinline)) void conv_2d_dw5_plane_f32_f32(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { - conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, false, false); -} - -static __attribute__((noinline)) void conv_2d_dw5_plane_f32_f16(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { - conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, false, true); -} - -static __attribute__((noinline)) void conv_2d_dw5_plane_f16_f32(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { - conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, true, false); -} - -static __attribute__((noinline)) void conv_2d_dw5_plane_f16_f16(const uint8_t * restrict src, const HVX_Vector * restrict wsplat, void * restrict dst, uint32_t src_row_stride, uint32_t ow, uint32_t oh) { - conv_2d_dw5_plane_impl(src, wsplat, dst, src_row_stride, ow, oh, true, true); -} - -struct conv_2d_dw5_pipe_state { - dma_addr_t w_data; - dma_addr_t in_data; - dma_addr_t out_data; - HVX_Vector * wsplat; - conv_2d_dw5_prep_weights_fn prep_weights_fn; - conv_2d_dw5_plane_fn plane_fn; - uint32_t plane; - uint32_t last; - uint32_t c_next; - uint32_t channels; - uint32_t ih; - uint32_t ow; - uint32_t oh; - uint32_t stride; - uint32_t in_row; - uint32_t in_plane; - uint32_t out_row; - uint32_t out_plane; - uint32_t w_plane; - uint32_t weight_bytes; - uint32_t halo_offset; -}; - -static bool conv_2d_dw5_next_task(void * ctx, struct dma_pipe_task * task) { - struct conv_2d_dw5_pipe_state * s = (struct conv_2d_dw5_pipe_state *) ctx; - if (s->plane >= s->last) { - return false; - } - task->row = s->plane; - task->aux = s->c_next; - s->plane++; - s->c_next = (s->c_next + 1 == s->channels) ? 0 : s->c_next + 1; - return true; -} - -static void conv_2d_dw5_push_in(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * in0_spad, void * in1_spad) { - const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx; - dma_queue_push(dma_q, dma_make_data(in0_spad, s->w_data + (dma_addr_t) task->aux * s->w_plane), - VLEN, s->w_plane, s->weight_bytes, 1); - dma_queue_push(dma_q, dma_make_data(in1_spad, s->in_data + (dma_addr_t) task->row * s->in_plane), - s->stride, s->in_row, s->in_row, s->ih); -} - -static void conv_2d_dw5_compute(void * ctx, const struct dma_pipe_task * task, void * out_spad, void * in0_spad, void * in1_spad) { - (void) task; - const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx; - s->prep_weights_fn(in0_spad, s->wsplat); - s->plane_fn((const uint8_t *) in1_spad - s->halo_offset, s->wsplat, out_spad, s->stride, s->ow, s->oh); -} - -static void conv_2d_dw5_push_out(dma_queue * dma_q, void * ctx, const struct dma_pipe_task * task, void * out_spad) { - const struct conv_2d_dw5_pipe_state * s = (const struct conv_2d_dw5_pipe_state *) ctx; - dma_queue_push(dma_q, dma_make_data(s->out_data + (dma_addr_t) task->row * s->out_plane, out_spad), - s->out_row, s->out_row, s->out_row, s->oh); -} - -// Planes are processed in memory order (plane = n * C + c). Each plane is three DMAs: weights in, src in, dst out. -// Two buffers per stream: plane i+1 is in flight while plane i is computed. -static void conv_2d_dw5_hvx_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - const struct conv_2d_dw5_hvx_context * ctx = (const struct conv_2d_dw5_hvx_context *) data; - const struct htp_ops_context * octx = ctx->octx; - const struct htp_conv2d_dw5_vtcm_layout * L = &ctx->layout; - const struct htp_tensor * weight = octx->src[0]; - const struct htp_tensor * input = octx->src[1]; - const struct htp_tensor * output = octx->dst; - - const uint32_t first = ctx->plane_start + ith * ctx->planes_per_thread; - const uint32_t last = MIN(first + ctx->planes_per_thread, ctx->plane_start + ctx->plane_count); - if (first >= last) { - return; - } - - uint8_t * vtcm = octx->ctx->vtcm_base; - uint8_t * src_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_src) + ith * 2 * L->src_slot_bytes; - uint8_t * weight_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_weight) + ith * HTP_CONV2D_DW5_W_BYTES; - uint8_t * dst_base = VTCM_LAYOUT_PTR(uint8_t, vtcm, L->off_dst) + ith * 2 * L->dst_slot_bytes; - const uint32_t halo_offset = ctx->halo_offset; - - void * in0_buf[2] = { weight_base, weight_base + VLEN }; - void * in1_buf[2] = { src_base + halo_offset, src_base + L->src_slot_bytes + halo_offset }; - void * out_buf[2] = { dst_base, dst_base + L->dst_slot_bytes }; - - conv_2d_dw5_clear(src_base, 2 * L->src_slot_bytes); - - struct conv_2d_dw5_pipe_state s = { - .w_data = weight->data, - .in_data = input->data, - .out_data = output->data, - .wsplat = (HVX_Vector *) (weight_base + 2 * VLEN), - .prep_weights_fn = ctx->prep_weights_fn, - .plane_fn = ctx->plane_fn, - .plane = first, - .last = last, - .c_next = first % input->ne[2], - .channels = input->ne[2], - .ih = input->ne[1], - .ow = output->ne[0], - .oh = output->ne[1], - .stride = L->src_row_stride, - .in_row = input->nb[1], - .in_plane = input->nb[2], - .out_row = output->nb[1], - .out_plane = output->nb[2], - .w_plane = weight->nb[3], - .weight_bytes = ctx->weight_bytes, - .halo_offset = halo_offset, - }; - - dma_pipe_io2_run(th->dma_q, th->trace, &s, in0_buf, in1_buf, out_buf, - conv_2d_dw5_next_task, conv_2d_dw5_push_in, conv_2d_dw5_compute, conv_2d_dw5_push_out); - - FARF(HIGH, "conv2d-dw-hvx-dma-5x5 %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n", ith, nth, input->ne[0], - input->ne[1], input->ne[2], input->ne[3], output->ne[0], output->ne[1], output->ne[2], output->ne[3], first, - last); -} - -int op_conv_2d_dw5(struct htp_ops_context * octx) { - // Tensor shapes, types and VTCM sizing were validated by the host (htp_kparams_solve_conv2d_dw). - const struct htp_conv2d_dw_kernel_params * kp = (const struct htp_conv2d_dw_kernel_params *) octx->kernel_params; - - uint32_t plane_start = 0; - uint32_t plane_count = kp->total_tasks; - - if (octx->ctx->mdev.count > 1) { - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - plane_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); - plane_start = range.start; - plane_count = range.count; - } - if (plane_count == 0) { - return HTP_STATUS_OK; - } - - static const conv_2d_dw5_plane_fn plane_fns[2][2] = { - { conv_2d_dw5_plane_f32_f32, conv_2d_dw5_plane_f32_f16 }, - { conv_2d_dw5_plane_f16_f32, conv_2d_dw5_plane_f16_f16 }, - }; - - const bool w_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0; - const bool src_f16 = (octx->src[1]->type == HTP_TYPE_F16); - const bool dst_f16 = (octx->dst->type == HTP_TYPE_F16); - const size_t src_es = src_f16 ? sizeof(__fp16) : sizeof(float); - const size_t dst_es = dst_f16 ? sizeof(__fp16) : sizeof(float); - const uint32_t weight_bytes = 25 * (w_f16 ? sizeof(__fp16) : sizeof(float)); - - struct htp_conv2d_dw5_vtcm_layout layout; - htp_conv2d_dw5_vtcm_layout_build(&layout, kp->w, kp->h, src_es, dst_es, kp->n_hvx); - - const uint32_t n_threads = MIN(kp->n_hvx, plane_count); - const uint32_t planes_per_thread = (plane_count + n_threads - 1) / n_threads; - struct conv_2d_dw5_hvx_context ctx = { - .octx = octx, - .layout = layout, - .prep_weights_fn = w_f16 ? conv_2d_dw5_prep_weights_f16 : conv_2d_dw5_prep_weights_f32, - .plane_fn = plane_fns[src_f16][dst_f16], - .weight_bytes = weight_bytes, - .halo_offset = 2 * layout.src_row_stride + 2 * src_es, - .plane_start = plane_start, - .plane_count = plane_count, - .planes_per_thread = planes_per_thread, - }; - - work_queue_run(octx->ctx->hvx_queue, conv_2d_dw5_hvx_thread, &ctx, n_threads); - return HTP_STATUS_OK; -} diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.c b/ggml/src/ggml-hexagon/htp/conv2d-ops.c index b2b5a6c2eb88..41fc50323e45 100644 --- a/ggml/src/ggml-hexagon/htp/conv2d-ops.c +++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.c @@ -5,7 +5,6 @@ #define GGML_COMMON_DECL_C #include "ggml-common.h" #include "conv2d-ops.h" -#include "dma-copy.h" #include "dma-queue.h" #include "hex-common.h" #include "hex-fastdiv.h" @@ -2369,910 +2368,3 @@ int op_conv_2d(struct htp_ops_context * octx) { return HTP_STATUS_NO_SUPPORT; } - -struct conv2d_dw_task_slice { - dma_addr_t src_addr; - dma_addr_t dst_addr; - uint32_t src_bytes; - uint32_t dst_bytes; - uint32_t ih_count; - uint32_t top_pad; - uint32_t bot_pad; - uint32_t oh_start; - uint32_t oh_len; - int32_t ih_first; - uint32_t c; -}; - -static inline void conv2d_dw_get_slice( - struct conv2d_dw_task_slice * slice, - uint32_t task, - const struct htp_tensor * src1, - const struct htp_tensor * dst, - const struct htp_conv2d_dw_kernel_params * kp) { - - uint32_t chunk_idx; - uint32_t n; - uint32_t c = 0; - - if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) { - n = fastdiv(task, &kp->div_n_chunks); - chunk_idx = task - n * kp->n_chunks; - } else { - const uint32_t plane = fastdiv(task, &kp->div_n_chunks); - chunk_idx = task - plane * kp->n_chunks; - n = fastdiv(plane, &kp->div_c); - c = plane - n * kp->c; - } - - const uint32_t oh_start = chunk_idx * kp->oh_chunk; - const uint32_t oh_len = MIN(kp->oh_chunk, kp->oh - oh_start); - - const int32_t ih_min = (int32_t)(oh_start * kp->s1) - kp->p1; - const int32_t ih_max = (int32_t)((oh_start + oh_len - 1) * kp->s1 + (kp->kh - 1) * kp->d1) - kp->p1; - const uint32_t ih_span = (uint32_t)(ih_max - ih_min + 1); - - const int32_t ih_first = MAX(0, ih_min); - const int32_t ih_last = MIN((int32_t)kp->h - 1, ih_max); - const uint32_t ih_count = (ih_first <= ih_last) ? (uint32_t)(ih_last - ih_first + 1) : 0; - const uint32_t top_pad = (ih_count > 0) ? (uint32_t)(ih_first - ih_min) : ih_span; - const uint32_t bot_pad = ih_span - top_pad - ih_count; - - slice->src_bytes = ih_count * kp->row_src_bytes; - slice->dst_bytes = oh_len * kp->row_dst_bytes; - slice->ih_count = ih_count; - slice->top_pad = top_pad; - slice->bot_pad = bot_pad; - slice->oh_start = oh_start; - slice->oh_len = oh_len; - slice->ih_first = ih_first; - slice->c = c; - - if (kp->flags & HTP_CONV2D_DW_FLAG_CWHN) { - slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) ih_first * src1->nb[1]; - slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) oh_start * dst->nb[1]; - } else { - slice->src_addr = src1->data + (size_t) n * src1->nb[3] + (size_t) c * src1->nb[2] + (size_t) ih_first * src1->nb[1]; - slice->dst_addr = dst->data + (size_t) n * dst->nb[3] + (size_t) c * dst->nb[2] + (size_t) oh_start * dst->nb[1]; - } -} - -static inline HVX_Vector conv2d_dw_splat_w_f32(const void * ptr) { - return hvx_vec_splat_f32(*(const float *) ptr); -} - -static inline HVX_Vector conv2d_dw_splat_w_f16(const void * ptr) { - const HVX_Vector vh = Q6_Vh_vsplat_R(*(const uint16_t *) ptr); - const HVX_Vector v1 = Q6_Vh_vsplat_R(0x3c00); - return Q6_Vsf_equals_Vqf32(Q6_V_lo_W(Q6_Wqf32_vmpy_VhfVhf(vh, v1))); -} - -static inline HVX_Vector conv2d_dw_load_w_f32(const void * ptr) { - return hvx_vmemu(ptr); -} - -static inline HVX_Vector conv2d_dw_load_w_f16(const void * ptr) { - return Q6_V_lo_W(hvx_vec_f16_to_f32(hvx_vmemu(ptr))); -} - -static inline HVX_Vector conv2d_dw_qf32_mpy_add3( - HVX_Vector acc, - HVX_Vector x0, HVX_Vector w0, - HVX_Vector x1, HVX_Vector w1, - HVX_Vector x2, HVX_Vector w2) { - const HVX_Vector p01 = Q6_Vqf32_vadd_Vqf32Vqf32(Q6_Vqf32_vmpy_VsfVsf(x0, w0), Q6_Vqf32_vmpy_VsfVsf(x1, w1)); - const HVX_Vector p2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc, Q6_Vqf32_vmpy_VsfVsf(x2, w2)); - return Q6_Vqf32_vadd_Vqf32Vqf32(p01, p2); -} - -static inline void conv2d_dw_pad_vtcm_k3x3( - float * in_vtcm, - const struct conv2d_dw_task_slice * slice, - uint32_t w_in, - uint32_t extra_bot_rows) { - if (slice->top_pad > 0) { - hvx_splat_f32_a(in_vtcm, 0.0f, slice->top_pad * w_in); - } - const uint32_t tail_zero_rows = slice->bot_pad + extra_bot_rows; - if (tail_zero_rows > 0) { - hvx_splat_f32_a(in_vtcm + (size_t) (slice->top_pad + slice->ih_count) * w_in, 0.0f, tail_zero_rows * w_in); - } -} - -#define DEFINE_CONV2D_DW_WHCN_S1_K3X3(SUFFIX, SPLAT_W_FN) \ -__attribute__((noinline)) \ -static void conv2d_dw_whcn_s1_k3x3_##SUFFIX( \ - const float * restrict in_vtcm, \ - float * restrict out_vtcm, \ - const void * w_vtcm, \ - const struct conv2d_dw_task_slice * slice, \ - const struct htp_ops_context * octx, \ - const struct htp_conv2d_dw_kernel_params * kp) { \ - \ - const struct htp_tensor * src0 = octx->src[0]; \ - const size_t w_nb0 = src0->nb[0]; \ - const size_t w_nb1 = src0->nb[1]; \ - const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ - const uint32_t oh_len = slice->oh_len; \ - const uint32_t w_in = kp->w; \ - \ - conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, w_in, 0); \ - \ - const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector zero = Q6_V_vzero(); \ - \ - uint32_t ohi = 0; \ - for (; ohi + 4 <= oh_len; ohi += 4) { \ - const float * restrict r0 = in_vtcm + (size_t) ohi * w_in; \ - const float * restrict r1 = r0 + w_in; \ - const float * restrict r2 = r1 + w_in; \ - const float * restrict r3 = r2 + w_in; \ - const float * restrict r4 = r3 + w_in; \ - const float * restrict r5 = r4 + w_in; \ - \ - float * restrict out0 = out_vtcm + (size_t) (ohi + 0) * w_in; \ - float * restrict out1 = out0 + w_in; \ - float * restrict out2 = out1 + w_in; \ - float * restrict out3 = out2 + w_in; \ - \ - HVX_Vector p0 = zero, c0 = hvx_vmem(r0); \ - HVX_Vector p1 = zero, c1 = hvx_vmem(r1); \ - HVX_Vector p2 = zero, c2 = hvx_vmem(r2); \ - HVX_Vector p3 = zero, c3 = hvx_vmem(r3); \ - HVX_Vector p4 = zero, c4 = hvx_vmem(r4); \ - HVX_Vector p5 = zero, c5 = hvx_vmem(r5); \ - \ - for (uint32_t ox = 0; ox < w_in; ox += 32) { \ - const bool has_next = (ox + 32 < w_in); \ - \ - const HVX_Vector n0 = has_next ? hvx_vmem(r0 + ox + 32) : zero; \ - const HVX_Vector l0 = Q6_V_valign_VVR(c0, p0, 124); \ - const HVX_Vector rg0 = Q6_V_valign_VVR(n0, c0, 4); \ - HVX_Vector acc0 = conv2d_dw_qf32_mpy_add3(zero, l0, w00, c0, w01, rg0, w02); \ - p0 = c0; c0 = n0; \ - \ - const HVX_Vector n1 = has_next ? hvx_vmem(r1 + ox + 32) : zero; \ - const HVX_Vector l1 = Q6_V_valign_VVR(c1, p1, 124); \ - const HVX_Vector rg1 = Q6_V_valign_VVR(n1, c1, 4); \ - acc0 = conv2d_dw_qf32_mpy_add3(acc0, l1, w10, c1, w11, rg1, w12); \ - HVX_Vector acc1 = conv2d_dw_qf32_mpy_add3(zero, l1, w00, c1, w01, rg1, w02); \ - p1 = c1; c1 = n1; \ - \ - const HVX_Vector n2 = has_next ? hvx_vmem(r2 + ox + 32) : zero; \ - const HVX_Vector l2 = Q6_V_valign_VVR(c2, p2, 124); \ - const HVX_Vector rg2 = Q6_V_valign_VVR(n2, c2, 4); \ - acc0 = conv2d_dw_qf32_mpy_add3(acc0, l2, w20, c2, w21, rg2, w22); \ - hvx_vmem(out0 + ox) = Q6_Vsf_equals_Vqf32(acc0); \ - acc1 = conv2d_dw_qf32_mpy_add3(acc1, l2, w10, c2, w11, rg2, w12); \ - HVX_Vector acc2 = conv2d_dw_qf32_mpy_add3(zero, l2, w00, c2, w01, rg2, w02); \ - p2 = c2; c2 = n2; \ - \ - const HVX_Vector n3 = has_next ? hvx_vmem(r3 + ox + 32) : zero; \ - const HVX_Vector l3 = Q6_V_valign_VVR(c3, p3, 124); \ - const HVX_Vector rg3 = Q6_V_valign_VVR(n3, c3, 4); \ - acc1 = conv2d_dw_qf32_mpy_add3(acc1, l3, w20, c3, w21, rg3, w22); \ - hvx_vmem(out1 + ox) = Q6_Vsf_equals_Vqf32(acc1); \ - acc2 = conv2d_dw_qf32_mpy_add3(acc2, l3, w10, c3, w11, rg3, w12); \ - HVX_Vector acc3 = conv2d_dw_qf32_mpy_add3(zero, l3, w00, c3, w01, rg3, w02); \ - p3 = c3; c3 = n3; \ - \ - const HVX_Vector n4 = has_next ? hvx_vmem(r4 + ox + 32) : zero; \ - const HVX_Vector l4 = Q6_V_valign_VVR(c4, p4, 124); \ - const HVX_Vector rg4 = Q6_V_valign_VVR(n4, c4, 4); \ - acc2 = conv2d_dw_qf32_mpy_add3(acc2, l4, w20, c4, w21, rg4, w22); \ - hvx_vmem(out2 + ox) = Q6_Vsf_equals_Vqf32(acc2); \ - acc3 = conv2d_dw_qf32_mpy_add3(acc3, l4, w10, c4, w11, rg4, w12); \ - p4 = c4; c4 = n4; \ - \ - const HVX_Vector n5 = has_next ? hvx_vmem(r5 + ox + 32) : zero; \ - const HVX_Vector l5 = Q6_V_valign_VVR(c5, p5, 124); \ - const HVX_Vector rg5 = Q6_V_valign_VVR(n5, c5, 4); \ - acc3 = conv2d_dw_qf32_mpy_add3(acc3, l5, w20, c5, w21, rg5, w22); \ - hvx_vmem(out3 + ox) = Q6_Vsf_equals_Vqf32(acc3); \ - p5 = c5; c5 = n5; \ - } \ - } \ - \ - for (; ohi < oh_len; ++ohi) { \ - const float * restrict r0 = in_vtcm + (size_t) ohi * w_in; \ - const float * restrict r1 = r0 + w_in; \ - const float * restrict r2 = r1 + w_in; \ - float * restrict out_row = out_vtcm + (size_t) ohi * w_in; \ - \ - HVX_Vector p0 = zero, c0 = hvx_vmem(r0); \ - HVX_Vector p1 = zero, c1 = hvx_vmem(r1); \ - HVX_Vector p2 = zero, c2 = hvx_vmem(r2); \ - \ - for (uint32_t ox = 0; ox < w_in; ox += 32) { \ - const bool has_next = (ox + 32 < w_in); \ - \ - const HVX_Vector n0 = has_next ? hvx_vmem(r0 + ox + 32) : zero; \ - const HVX_Vector l0 = Q6_V_valign_VVR(c0, p0, 124); \ - const HVX_Vector rg0 = Q6_V_valign_VVR(n0, c0, 4); \ - HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, l0, w00, c0, w01, rg0, w02); \ - p0 = c0; c0 = n0; \ - \ - const HVX_Vector n1 = has_next ? hvx_vmem(r1 + ox + 32) : zero; \ - const HVX_Vector l1 = Q6_V_valign_VVR(c1, p1, 124); \ - const HVX_Vector rg1 = Q6_V_valign_VVR(n1, c1, 4); \ - acc = conv2d_dw_qf32_mpy_add3(acc, l1, w10, c1, w11, rg1, w12); \ - p1 = c1; c1 = n1; \ - \ - const HVX_Vector n2 = has_next ? hvx_vmem(r2 + ox + 32) : zero; \ - const HVX_Vector l2 = Q6_V_valign_VVR(c2, p2, 124); \ - const HVX_Vector rg2 = Q6_V_valign_VVR(n2, c2, 4); \ - acc = conv2d_dw_qf32_mpy_add3(acc, l2, w20, c2, w21, rg2, w22); \ - p2 = c2; c2 = n2; \ - \ - hvx_vmem(out_row + ox) = Q6_Vsf_equals_Vqf32(acc); \ - } \ - } \ -} - -DEFINE_CONV2D_DW_WHCN_S1_K3X3(f32, conv2d_dw_splat_w_f32) -DEFINE_CONV2D_DW_WHCN_S1_K3X3(f16, conv2d_dw_splat_w_f16) - -#define DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(SUFFIX, SPLAT_W_FN) \ -__attribute__((noinline)) \ -static void conv2d_dw_whcn_s2_k3x3_w32_##SUFFIX( \ - const float * restrict in_vtcm, \ - float * restrict out_vtcm, \ - const void * w_vtcm, \ - const struct conv2d_dw_task_slice * slice, \ - const struct htp_ops_context * octx, \ - const struct htp_conv2d_dw_kernel_params * kp) { \ - \ - (void) kp; \ - const struct htp_tensor * src0 = octx->src[0]; \ - const size_t w_nb0 = src0->nb[0]; \ - const size_t w_nb1 = src0->nb[1]; \ - const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ - const uint32_t oh_len = slice->oh_len; \ - \ - conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, 32, (oh_len & 1) ? 2 : 0); \ - \ - const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector zero = Q6_V_vzero(); \ - \ - const HVX_VectorPred q_not_lane16 = Q6_Q_or_QQn(Q6_Q_vsetq_R(64), Q6_Q_vsetq2_R(68)); \ - const float * restrict in_row = in_vtcm; \ - HVX_Vector v_prev_b2 = hvx_vmem(in_row); \ - in_row += 32; \ - \ - for (uint32_t ohi = 0; ohi < oh_len; ohi += 2) { \ - const HVX_Vector v_a0 = v_prev_b2; \ - const HVX_Vector v_a1 = hvx_vmem(in_row); \ - const HVX_Vector v_a2 = hvx_vmem(in_row + 32); \ - const HVX_Vector v_b0 = v_a2; \ - const HVX_Vector v_b1 = hvx_vmem(in_row + 64); \ - const HVX_Vector v_b2 = hvx_vmem(in_row + 96); \ - in_row += 128; \ - v_prev_b2 = v_b2; \ - \ - const HVX_VectorPair vp0 = Q6_W_vdeal_VVR(v_b0, v_a0, -4); \ - const HVX_Vector ev0 = Q6_V_lo_W(vp0); \ - const HVX_Vector od0 = Q6_V_hi_W(vp0); \ - const HVX_Vector lf0 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od0, zero, 124)); \ - HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \ - \ - const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(v_b1, v_a1, -4); \ - const HVX_Vector ev1 = Q6_V_lo_W(vp1); \ - const HVX_Vector od1 = Q6_V_hi_W(vp1); \ - const HVX_Vector lf1 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od1, zero, 124)); \ - acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \ - \ - const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(v_b2, v_a2, -4); \ - const HVX_Vector ev2 = Q6_V_lo_W(vp2); \ - const HVX_Vector od2 = Q6_V_hi_W(vp2); \ - const HVX_Vector lf2 = Q6_V_vand_QV(q_not_lane16, Q6_V_valign_VVR(od2, zero, 124)); \ - acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \ - \ - hvx_vmem(out_vtcm + (size_t) ohi * 16) = Q6_Vsf_equals_Vqf32(acc); \ - } \ -} - -DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(f32, conv2d_dw_splat_w_f32) -DEFINE_CONV2D_DW_WHCN_S2_K3X3_W32(f16, conv2d_dw_splat_w_f16) - -#define DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(SUFFIX, SPLAT_W_FN) \ -__attribute__((noinline)) \ -static void conv2d_dw_whcn_s2_k3x3_w64_##SUFFIX( \ - const float * restrict in_vtcm, \ - float * restrict out_vtcm, \ - const void * w_vtcm, \ - const struct conv2d_dw_task_slice * slice, \ - const struct htp_ops_context * octx, \ - const struct htp_conv2d_dw_kernel_params * kp) { \ - \ - (void) kp; \ - const struct htp_tensor * src0 = octx->src[0]; \ - const size_t w_nb0 = src0->nb[0]; \ - const size_t w_nb1 = src0->nb[1]; \ - const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ - const uint32_t oh_len = slice->oh_len; \ - \ - conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, 64, 0); \ - \ - const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector zero = Q6_V_vzero(); \ - \ - const float * restrict in_row = in_vtcm; \ - const HVX_VectorPair vp0_init = Q6_W_vdeal_VVR(hvx_vmem(in_row + 32), hvx_vmem(in_row), -4); \ - in_row += 64; \ - HVX_Vector ev0 = Q6_V_lo_W(vp0_init); \ - HVX_Vector od0 = Q6_V_hi_W(vp0_init); \ - HVX_Vector lf0 = Q6_V_valign_VVR(od0, zero, 124); \ - \ - for (uint32_t ohi = 0; ohi < oh_len; ++ohi) { \ - const float * restrict r1_ptr = in_row; \ - const float * restrict r2_ptr = in_row + 64; \ - in_row += 128; \ - \ - HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \ - \ - const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(hvx_vmem(r1_ptr + 32), hvx_vmem(r1_ptr), -4); \ - const HVX_Vector ev1 = Q6_V_lo_W(vp1); \ - const HVX_Vector od1 = Q6_V_hi_W(vp1); \ - const HVX_Vector lf1 = Q6_V_valign_VVR(od1, zero, 124); \ - acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \ - \ - const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(hvx_vmem(r2_ptr + 32), hvx_vmem(r2_ptr), -4); \ - const HVX_Vector ev2 = Q6_V_lo_W(vp2); \ - const HVX_Vector od2 = Q6_V_hi_W(vp2); \ - const HVX_Vector lf2 = Q6_V_valign_VVR(od2, zero, 124); \ - acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \ - \ - hvx_vmem(out_vtcm + (size_t) ohi * 32) = Q6_Vsf_equals_Vqf32(acc); \ - \ - ev0 = ev2; \ - od0 = od2; \ - lf0 = lf2; \ - } \ -} - -DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(f32, conv2d_dw_splat_w_f32) -DEFINE_CONV2D_DW_WHCN_S2_K3X3_W64(f16, conv2d_dw_splat_w_f16) - -#define DEFINE_CONV2D_DW_WHCN_S2_K3X3(SUFFIX, SPLAT_W_FN) \ -__attribute__((noinline)) \ -static void conv2d_dw_whcn_s2_k3x3_##SUFFIX( \ - const float * restrict in_vtcm, \ - float * restrict out_vtcm, \ - const void * w_vtcm, \ - const struct conv2d_dw_task_slice * slice, \ - const struct htp_ops_context * octx, \ - const struct htp_conv2d_dw_kernel_params * kp) { \ - \ - const struct htp_tensor * src0 = octx->src[0]; \ - const size_t w_nb0 = src0->nb[0]; \ - const size_t w_nb1 = src0->nb[1]; \ - const char * restrict w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ - const uint32_t oh_len = slice->oh_len; \ - const uint32_t w_in = kp->w; \ - const uint32_t ow = kp->ow; \ - \ - conv2d_dw_pad_vtcm_k3x3((float *) in_vtcm, slice, w_in, 0); \ - \ - const HVX_Vector w00 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w01 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w02 = SPLAT_W_FN(w_chan + 0 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w10 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w11 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w12 = SPLAT_W_FN(w_chan + 1 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector w20 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 0 * w_nb0); \ - const HVX_Vector w21 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 1 * w_nb0); \ - const HVX_Vector w22 = SPLAT_W_FN(w_chan + 2 * w_nb1 + 2 * w_nb0); \ - const HVX_Vector zero = Q6_V_vzero(); \ - \ - for (uint32_t ohi = 0; ohi < oh_len; ++ohi) { \ - const float * restrict r0 = in_vtcm + (size_t) (2 * ohi) * w_in; \ - const float * restrict r1 = r0 + w_in; \ - const float * restrict r2 = r1 + w_in; \ - float * restrict out_row = out_vtcm + (size_t) ohi * ow; \ - \ - HVX_Vector prev_od0 = zero; \ - HVX_Vector prev_od1 = zero; \ - HVX_Vector prev_od2 = zero; \ - \ - for (uint32_t ox = 0; ox < ow; ox += 32) { \ - const uint32_t ix = 2 * ox; \ - const bool has1 = (ix + 32 < w_in); \ - \ - const HVX_VectorPair vp0 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r0 + ix + 32) : zero, hvx_vmem(r0 + ix), -4); \ - const HVX_Vector ev0 = Q6_V_lo_W(vp0); \ - const HVX_Vector od0 = Q6_V_hi_W(vp0); \ - const HVX_Vector lf0 = Q6_V_valign_VVR(od0, prev_od0, 124); \ - prev_od0 = od0; \ - HVX_Vector acc = conv2d_dw_qf32_mpy_add3(zero, lf0, w00, ev0, w01, od0, w02); \ - \ - const HVX_VectorPair vp1 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r1 + ix + 32) : zero, hvx_vmem(r1 + ix), -4); \ - const HVX_Vector ev1 = Q6_V_lo_W(vp1); \ - const HVX_Vector od1 = Q6_V_hi_W(vp1); \ - const HVX_Vector lf1 = Q6_V_valign_VVR(od1, prev_od1, 124); \ - prev_od1 = od1; \ - acc = conv2d_dw_qf32_mpy_add3(acc, lf1, w10, ev1, w11, od1, w12); \ - \ - const HVX_VectorPair vp2 = Q6_W_vdeal_VVR(has1 ? hvx_vmem(r2 + ix + 32) : zero, hvx_vmem(r2 + ix), -4); \ - const HVX_Vector ev2 = Q6_V_lo_W(vp2); \ - const HVX_Vector od2 = Q6_V_hi_W(vp2); \ - const HVX_Vector lf2 = Q6_V_valign_VVR(od2, prev_od2, 124); \ - prev_od2 = od2; \ - acc = conv2d_dw_qf32_mpy_add3(acc, lf2, w20, ev2, w21, od2, w22); \ - \ - if (ox + 32 <= ow) { \ - hvx_vmem(out_row + ox) = Q6_Vsf_equals_Vqf32(acc); \ - } else { \ - const uint32_t rem = ow - ox; \ - const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \ - hvx_vec_store_u(out_row + ox, rem * sizeof(float), Q6_V_vmux_QVV(q, Q6_Vsf_equals_Vqf32(acc), zero)); \ - } \ - } \ - } \ -} - -DEFINE_CONV2D_DW_WHCN_S2_K3X3(f32, conv2d_dw_splat_w_f32) -DEFINE_CONV2D_DW_WHCN_S2_K3X3(f16, conv2d_dw_splat_w_f16) - -#define DEFINE_CONV2D_DW_WHCN_S1(SUFFIX, SPLAT_W_FN) \ -__attribute__((noinline)) \ -static void conv2d_dw_whcn_s1_##SUFFIX( \ - const float * in_vtcm, \ - float * out_vtcm, \ - const void * w_vtcm, \ - const struct conv2d_dw_task_slice * slice, \ - const struct htp_ops_context * octx, \ - const struct htp_conv2d_dw_kernel_params * kp) { \ - \ - const struct htp_tensor * src0 = octx->src[0]; \ - const char * w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ - const int32_t p0 = kp->p0; \ - const int32_t p1 = kp->p1; \ - const int32_t s1 = kp->s1; \ - const int32_t d1 = kp->d1; \ - const int32_t w = (int32_t) kp->w; \ - const HVX_Vector zero = Q6_V_vzero(); \ - \ - for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \ - const uint32_t oh = slice->oh_start + ohi; \ - float * out_row = out_vtcm + (size_t) ohi * kp->ow; \ - \ - for (uint32_t ox = 0; ox < kp->ow; ox += 32) { \ - const uint32_t rem = kp->ow - ox; \ - const uint32_t nbytes = (rem < 32) ? (rem * sizeof(float)) : 128; \ - HVX_Vector acc0 = zero; \ - HVX_Vector acc1 = zero; \ - HVX_Vector acc2 = zero; \ - HVX_Vector acc3 = zero; \ - \ - for (uint32_t kh = 0; kh < kp->kh; ++kh) { \ - const int32_t ih = (int32_t) (oh * s1 + kh * d1) - p1; \ - if (ih < 0 || ih >= (int32_t) kp->h) { \ - continue; \ - } \ - const float * in_row = in_vtcm + (size_t) (ih - slice->ih_first) * kp->w; \ - const char * w_row = w_chan + (size_t) kh * src0->nb[1]; \ - \ - for (uint32_t kw = 0; kw < kp->kw; ++kw) { \ - const HVX_Vector w_v = SPLAT_W_FN(w_row + (size_t) kw * src0->nb[0]); \ - const int32_t base_iw = (int32_t) ox - p0 + (int32_t) kw; \ - HVX_Vector in_v; \ - \ - if (base_iw >= 0) { \ - in_v = hvx_vmemu(in_row + base_iw); \ - } else { \ - const int32_t pad = -base_iw; \ - const HVX_Vector v = hvx_vmemu(in_row); \ - in_v = Q6_V_valign_VVR(v, zero, 128 - (uint32_t) pad * sizeof(float)); \ - } \ - if (base_iw + 31 >= w) { \ - const int32_t valid = w - base_iw; \ - const HVX_VectorPred q = Q6_Q_vsetq_R(MAX(0, valid) * sizeof(float)); \ - in_v = Q6_V_vmux_QVV(q, in_v, zero); \ - } \ - \ - const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(in_v, w_v); \ - switch (kw & 3) { \ - case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \ - case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \ - case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \ - case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \ - } \ - } \ - } \ - \ - const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \ - const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \ - HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \ - if (rem < 32) { \ - const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \ - acc_out = Q6_V_vmux_QVV(q, acc_out, zero); \ - } \ - \ - hvx_vec_store_u(out_row + ox, nbytes, acc_out); \ - } \ - } \ -} - -DEFINE_CONV2D_DW_WHCN_S1(f32, conv2d_dw_splat_w_f32) -DEFINE_CONV2D_DW_WHCN_S1(f16, conv2d_dw_splat_w_f16) - -#define DEFINE_CONV2D_DW_WHCN_S2(SUFFIX, SPLAT_W_FN) \ -__attribute__((noinline)) \ -static void conv2d_dw_whcn_s2_##SUFFIX( \ - const float * in_vtcm, \ - float * out_vtcm, \ - const void * w_vtcm, \ - const struct conv2d_dw_task_slice * slice, \ - const struct htp_ops_context * octx, \ - const struct htp_conv2d_dw_kernel_params * kp) { \ - \ - const struct htp_tensor * src0 = octx->src[0]; \ - const char * w_chan = (const char *) w_vtcm + (size_t) slice->c * src0->nb[3]; \ - const int32_t p0 = kp->p0; \ - const int32_t p1 = kp->p1; \ - const int32_t s1 = kp->s1; \ - const int32_t d1 = kp->d1; \ - const int32_t w = (int32_t) kp->w; \ - const HVX_Vector zero = Q6_V_vzero(); \ - \ - for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \ - const uint32_t oh = slice->oh_start + ohi; \ - float * out_row = out_vtcm + (size_t) ohi * kp->ow; \ - \ - for (uint32_t ox = 0; ox < kp->ow; ox += 32) { \ - const uint32_t rem = kp->ow - ox; \ - const uint32_t nbytes = (rem < 32) ? (rem * sizeof(float)) : 128; \ - HVX_Vector acc0 = zero; \ - HVX_Vector acc1 = zero; \ - HVX_Vector acc2 = zero; \ - HVX_Vector acc3 = zero; \ - \ - for (uint32_t kh = 0; kh < kp->kh; ++kh) { \ - const int32_t ih = (int32_t) (oh * s1 + kh * d1) - p1; \ - if (ih < 0 || ih >= (int32_t) kp->h) { \ - continue; \ - } \ - const float * in_row = in_vtcm + (size_t) (ih - slice->ih_first) * kp->w; \ - const char * w_row = w_chan + (size_t) kh * src0->nb[1]; \ - \ - for (uint32_t kw = 0; kw < kp->kw; ++kw) { \ - const HVX_Vector w_v = SPLAT_W_FN(w_row + (size_t) kw * src0->nb[0]); \ - const int32_t base_iw = (int32_t) (2 * ox) - p0 + (int32_t) kw; \ - HVX_Vector in_v; \ - \ - if (base_iw >= 0) { \ - const HVX_Vector v0 = hvx_vmemu(in_row + base_iw); \ - const HVX_Vector v1 = hvx_vmemu(in_row + base_iw + 32); \ - in_v = Q6_V_lo_W(Q6_W_vdeal_VVR(v1, v0, -4)); \ - } else { \ - const int32_t pad = -base_iw; \ - const HVX_Vector v0 = hvx_vmemu(in_row); \ - const HVX_Vector v1 = hvx_vmemu(in_row + 32); \ - const HVX_VectorPair vp = Q6_W_vdeal_VVR(v1, v0, -4); \ - if (pad & 1) { \ - const uint32_t shift_lanes = (uint32_t) (pad + 1) / 2; \ - const HVX_Vector v_odd = Q6_V_hi_W(vp); \ - in_v = Q6_V_valign_VVR(v_odd, zero, 128 - shift_lanes * sizeof(float)); \ - } else { \ - const uint32_t shift_lanes = (uint32_t) pad / 2; \ - const HVX_Vector v_even = Q6_V_lo_W(vp); \ - in_v = Q6_V_valign_VVR(v_even, zero, 128 - shift_lanes * sizeof(float)); \ - } \ - } \ - if (base_iw + 62 >= w) { \ - const int32_t valid = (w - base_iw + 1) / 2; \ - const HVX_VectorPred q = Q6_Q_vsetq_R(MAX(0, valid) * sizeof(float)); \ - in_v = Q6_V_vmux_QVV(q, in_v, zero); \ - } \ - \ - const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(in_v, w_v); \ - switch (kw & 3) { \ - case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \ - case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \ - case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \ - case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \ - } \ - } \ - } \ - \ - const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \ - const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \ - HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \ - if (rem < 32) { \ - const HVX_VectorPred q = Q6_Q_vsetq_R(rem * sizeof(float)); \ - acc_out = Q6_V_vmux_QVV(q, acc_out, zero); \ - } \ - \ - hvx_vec_store_u(out_row + ox, nbytes, acc_out); \ - } \ - } \ -} - -DEFINE_CONV2D_DW_WHCN_S2(f32, conv2d_dw_splat_w_f32) -DEFINE_CONV2D_DW_WHCN_S2(f16, conv2d_dw_splat_w_f16) - -#define DEFINE_CONV2D_DW_CWHN(SUFFIX, LOAD_W_FN) \ -__attribute__((noinline)) \ -static void conv2d_dw_cwhn_##SUFFIX( \ - const float * in_vtcm, \ - float * out_vtcm, \ - const void * w_vtcm, \ - const struct conv2d_dw_task_slice * slice, \ - const struct htp_ops_context * octx, \ - const struct htp_conv2d_dw_kernel_params * kp) { \ - \ - const struct htp_tensor * src0 = octx->src[0]; \ - const uint32_t in_row_stride = kp->w * kp->c; \ - const uint32_t out_row_stride = kp->ow * kp->c; \ - const HVX_Vector zero = Q6_V_vzero(); \ - \ - for (uint32_t cb = 0; cb < kp->c; cb += 32) { \ - const uint32_t rem = MIN(32, kp->c - cb); \ - const char * w_base = (const char *) w_vtcm + (size_t) cb * src0->nb[3]; \ - \ - for (uint32_t ohi = 0; ohi < slice->oh_len; ++ohi) { \ - const uint32_t oh = slice->oh_start + ohi; \ - float * out_row = out_vtcm + (size_t) ohi * out_row_stride + cb; \ - \ - for (uint32_t ow = 0; ow < kp->ow; ++ow) { \ - HVX_Vector acc0 = zero; \ - HVX_Vector acc1 = zero; \ - HVX_Vector acc2 = zero; \ - HVX_Vector acc3 = zero; \ - \ - for (uint32_t kh = 0; kh < kp->kh; ++kh) { \ - const int32_t ih = (int32_t)(oh * kp->s1 + kh * kp->d1) - kp->p1; \ - if (ih < 0 || ih >= (int32_t)kp->h) { \ - continue; \ - } \ - const float * in_row = in_vtcm + (size_t)(ih - slice->ih_first) * in_row_stride + cb; \ - const char * w_row = w_base + (size_t) kh * src0->nb[1]; \ - \ - for (uint32_t kw = 0; kw < kp->kw; ++kw) { \ - const int32_t iw = (int32_t)(ow * kp->s0 + kw * kp->d0) - kp->p0; \ - if (iw < 0 || iw >= (int32_t)kp->w) { \ - continue; \ - } \ - \ - const float * in_ptr = in_row + (size_t) iw * kp->c; \ - const char * w_ptr = w_row + (size_t) kw * src0->nb[0]; \ - const HVX_Vector v_in = hvx_vmemu(in_ptr); \ - const HVX_Vector v_w = LOAD_W_FN(w_ptr); \ - const HVX_Vector prod = Q6_Vqf32_vmpy_VsfVsf(v_in, v_w); \ - switch (kw & 3) { \ - case 0: acc0 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, prod); break; \ - case 1: acc1 = Q6_Vqf32_vadd_Vqf32Vqf32(acc1, prod); break; \ - case 2: acc2 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, prod); break; \ - case 3: acc3 = Q6_Vqf32_vadd_Vqf32Vqf32(acc3, prod); break; \ - } \ - } \ - } \ - \ - const HVX_Vector acc01 = Q6_Vqf32_vadd_Vqf32Vqf32(acc0, acc1); \ - const HVX_Vector acc23 = Q6_Vqf32_vadd_Vqf32Vqf32(acc2, acc3); \ - const HVX_Vector acc_out = Q6_Vsf_equals_Vqf32(Q6_Vqf32_vadd_Vqf32Vqf32(acc01, acc23)); \ - \ - float * dst_ptr = out_row + (size_t) ow * kp->c; \ - if (rem == 32) { \ - hvx_vmemu(dst_ptr) = acc_out; \ - } else { \ - hvx_vec_store_u(dst_ptr, rem * sizeof(float), acc_out); \ - } \ - } \ - } \ - } \ -} - -DEFINE_CONV2D_DW_CWHN(f32, conv2d_dw_load_w_f32) -DEFINE_CONV2D_DW_CWHN(f16, conv2d_dw_load_w_f16) - -typedef void (*conv2d_dw_compute_fn_t)( - const float * in_vtcm, - float * out_vtcm, - const void * w_vtcm, - const struct conv2d_dw_task_slice * slice, - const struct htp_ops_context * octx, - const struct htp_conv2d_dw_kernel_params * kp); - -static const conv2d_dw_compute_fn_t conv2d_dw_kernels[HTP_CONV2D_DW_KERNEL_COUNT][2] = { - [HTP_CONV2D_DW_KERNEL_UNSUPPORTED] = { NULL, NULL }, - [HTP_CONV2D_DW_KERNEL_CWHN] = { conv2d_dw_cwhn_f32, conv2d_dw_cwhn_f16 }, - [HTP_CONV2D_DW_KERNEL_WHCN_S1] = { conv2d_dw_whcn_s1_f32, conv2d_dw_whcn_s1_f16 }, - [HTP_CONV2D_DW_KERNEL_WHCN_S2] = { conv2d_dw_whcn_s2_f32, conv2d_dw_whcn_s2_f16 }, - [HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3] = { conv2d_dw_whcn_s1_k3x3_f32, conv2d_dw_whcn_s1_k3x3_f16 }, - [HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W32] = { conv2d_dw_whcn_s2_k3x3_w32_f32, conv2d_dw_whcn_s2_k3x3_w32_f16 }, - [HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W64] = { conv2d_dw_whcn_s2_k3x3_w64_f32, conv2d_dw_whcn_s2_k3x3_w64_f16 }, - [HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3] = { conv2d_dw_whcn_s2_k3x3_f32, conv2d_dw_whcn_s2_k3x3_f16 }, -}; - -struct conv2d_dw_dma_context { - struct htp_ops_context * octx; - const struct htp_conv2d_dw_kernel_params * kp; - struct htp_conv2d_dw_vtcm_layout layout; - const void * w_vtcm; - conv2d_dw_compute_fn_t compute_fn; - uint32_t task_start; - uint32_t task_count; - uint32_t tasks_per_hvx; -}; - -static void conv2d_dw_dma_thread(const htp_thread_t * th, unsigned int nth, unsigned int ith, void * data) { - const struct conv2d_dw_dma_context * ctx = (const struct conv2d_dw_dma_context *) data; - const struct htp_ops_context * octx = ctx->octx; - const struct htp_conv2d_dw_kernel_params * kp = ctx->kp; - const struct htp_conv2d_dw_vtcm_layout * L = &ctx->layout; - const struct htp_tensor * src1 = octx->src[1]; - const struct htp_tensor * dst = octx->dst; - conv2d_dw_compute_fn_t compute_fn = ctx->compute_fn; - - const uint32_t first = ctx->task_start + ith * ctx->tasks_per_hvx; - const uint32_t last = MIN(first + ctx->tasks_per_hvx, ctx->task_start + ctx->task_count); - if (first >= last) { - return; - } - - (void) nth; - - struct htp_thread_trace * tr = th->trace; - dma_queue * dma_q = th->dma_q; - - const uint32_t src_spad_half = (uint32_t) L->src_spad_half_size; - const uint32_t dst_spad_half = (uint32_t) L->dst_spad_half_size; - const uint32_t pad_top_stride = kp->pad_top_stride; - - uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base; - uint8_t * src_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_src) + ith * L->src_bytes_per_hvx; - uint8_t * dst_spad = VTCM_LAYOUT_PTR(uint8_t, vtcm_base, L->off_dst) + ith * L->dst_bytes_per_hvx; - - float * srcb2[2] = { (float *) src_spad, (float *) (src_spad + src_spad_half) }; - float * dstb2[2] = { (float *) dst_spad, (float *) (dst_spad + dst_spad_half) }; - struct conv2d_dw_task_slice sl2[2]; - - const uint32_t total = last - first; - - for (uint32_t i = 0; i < total && i < 2; ++i) { - conv2d_dw_get_slice(&sl2[i], first + i, src1, dst, kp); - - dma_queue_push(dma_q, - dma_make_data(dst->data, dstb2[i]), - sl2[i].dst_bytes, dst_spad_half, - sl2[i].dst_bytes, 0); - - float * src_dst = srcb2[i] + (size_t) sl2[i].top_pad * pad_top_stride; - dma_queue_push(dma_q, - dma_make_data(src_dst, sl2[i].src_addr), - src_spad_half, sl2[i].src_bytes, - sl2[i].src_bytes, sl2[i].src_bytes > 0 ? 1 : 0); - } - - for (uint32_t i = 0; i < total; ++i) { - const uint32_t task = first + i; - const uint32_t buf = i & 1u; - float * srcb = srcb2[buf]; - float * dstb = dstb2[buf]; - - dma_queue_pop(dma_q); - dma_queue_pop(dma_q); - - htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) task); - compute_fn(srcb, dstb, ctx->w_vtcm, &sl2[buf], octx, kp); - htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_COMP, (uint16_t) task); - - dma_queue_push(dma_q, - dma_make_data(sl2[buf].dst_addr, dstb), - sl2[buf].dst_bytes, dst_spad_half, - sl2[buf].dst_bytes, sl2[buf].dst_bytes > 0 ? 1 : 0); - - if (i + 2 < total) { - conv2d_dw_get_slice(&sl2[buf], task + 2, src1, dst, kp); - - float * src_dst = srcb + (size_t) sl2[buf].top_pad * pad_top_stride; - dma_queue_push(dma_q, - dma_make_data(src_dst, sl2[buf].src_addr), - src_spad_half, sl2[buf].src_bytes, - sl2[buf].src_bytes, sl2[buf].src_bytes > 0 ? 1 : 0); - } - } - - dma_queue_flush(dma_q); - - FARF(HIGH, "conv2d_dw-f32-dma %d/%d: %ux%ux%ux%u -> %ux%ux%ux%u (%u:%u)\n", - ith, nth, kp->w, kp->h, kp->c, dst->ne[3], kp->ow, kp->oh, kp->c, dst->ne[3], first, last); -} - -int op_conv_2d_dw(struct htp_ops_context * octx) { - const struct htp_conv2d_dw_kernel_params * kp = - (const struct htp_conv2d_dw_kernel_params *) octx->kernel_params; - - if (kp->total_tasks == 0) { - return HTP_STATUS_OK; - } - - if (kp->kernel_type <= HTP_CONV2D_DW_KERNEL_UNSUPPORTED || - kp->kernel_type >= HTP_CONV2D_DW_KERNEL_COUNT) { - return HTP_STATUS_NO_SUPPORT; - } - - if (kp->kernel_type == HTP_CONV2D_DW_KERNEL_WHCN_5X5_DMA) { - return op_conv_2d_dw5(octx); - } - - const uint32_t pad_rows = (kp->pad_top_stride > 0) ? 4 : 0; - const uint32_t max_ih_chunk = MIN(kp->h, (kp->oh_chunk - 1) * (uint32_t) kp->s1 + (kp->kh - 1) * (uint32_t) kp->d1 + 1); - const uint32_t max_src_bytes = (max_ih_chunk + pad_rows) * kp->row_src_bytes + 128; - const uint32_t max_dst_bytes = kp->oh_chunk * kp->row_dst_bytes + 128; - - const struct htp_tensor * src0 = octx->src[0]; - const bool is_f16 = (kp->flags & HTP_CONV2D_DW_FLAG_F16) != 0; - const uint32_t elem_size = is_f16 ? sizeof(__fp16) : sizeof(float); - const uint32_t w_size = src0->size; - - struct htp_conv2d_dw_vtcm_layout layout; - htp_conv2d_dw_vtcm_layout_build(&layout, max_src_bytes, max_dst_bytes, w_size, kp->n_hvx); - - uint8_t * vtcm_base = (uint8_t *) octx->ctx->vtcm_base; - void * w_vtcm = VTCM_LAYOUT_PTR(void, vtcm_base, layout.off_w); - - struct htp_tensor w_vtcm_tensor = *src0; - w_vtcm_tensor.data = (dma_addr_t) w_vtcm; - - if (src0->nb[0] == elem_size) { - dma_cpy_sametype_sameshape(octx->ctx->dma[0], &w_vtcm_tensor, src0, elem_size); - } else { - dma_sync_read(octx->ctx->dma[0], w_vtcm, src0->data, w_size); - } - dma_queue_flush(octx->ctx->dma[0]); - - uint32_t task_start = 0; - uint32_t task_count = kp->total_tasks; - if (octx->ctx->mdev.count > 1) { - const struct htp_tensor_mdev_range range = htp_tensor_mdev_partition( - task_count, 1, octx->ctx->mdev.idx, octx->ctx->mdev.count, &octx->ctx->mdev.count_div); - task_start = range.start; - task_count = range.count; - } - if (task_count == 0) { - return HTP_STATUS_OK; - } - - const uint32_t nth = MIN(kp->n_hvx, task_count); - const uint32_t tasks_per_hvx = (task_count + nth - 1) / nth; - - struct conv2d_dw_dma_context ctx = { - .octx = octx, - .kp = kp, - .layout = layout, - .w_vtcm = w_vtcm, - .compute_fn = conv2d_dw_kernels[kp->kernel_type][is_f16 ? 1 : 0], - .task_start = task_start, - .task_count = task_count, - .tasks_per_hvx = tasks_per_hvx, - }; - - work_queue_run(octx->ctx->hvx_queue, conv2d_dw_dma_thread, &ctx, nth); - return HTP_STATUS_OK; -} diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.h b/ggml/src/ggml-hexagon/htp/conv2d-ops.h index 473d0fe6df9c..9e66c5471ba2 100644 --- a/ggml/src/ggml-hexagon/htp/conv2d-ops.h +++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.h @@ -88,123 +88,6 @@ static_assert(sizeof(struct htp_conv2d_kernel_params) <= 128, "htp_conv2d_kernel _Static_assert(sizeof(struct htp_conv2d_kernel_params) <= 128, "htp_conv2d_kernel_params is too large for kernel_params blob"); #endif -enum htp_conv2d_dw_kernel_type { - HTP_CONV2D_DW_KERNEL_UNSUPPORTED = 0, - HTP_CONV2D_DW_KERNEL_CWHN, // CWHN channel-contiguous layout - HTP_CONV2D_DW_KERNEL_WHCN_S1, // WHCN general stride-1 - HTP_CONV2D_DW_KERNEL_WHCN_S2, // WHCN general stride-2 - HTP_CONV2D_DW_KERNEL_WHCN_S1_K3X3, // WHCN aligned w%32==0, 3x3 s=1 p=1 d=1 - HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W32, // WHCN w=32->ow=16, 3x3 s=2 p=1 d=1 (2 rows per vector) - HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3_W64, // WHCN w=64->ow=32, 3x3 s=2 p=1 d=1 (1 vector rolling kh) - HTP_CONV2D_DW_KERNEL_WHCN_S2_K3X3, // WHCN aligned w%32==0 (w>=96), 3x3 s=2 p=1 d=1 - HTP_CONV2D_DW_KERNEL_WHCN_5X5_DMA, // WHCN 5x5 s=1 p=2 d=1, DMA row halo - HTP_CONV2D_DW_KERNEL_COUNT, -}; - -enum htp_conv2d_dw_flags { - HTP_CONV2D_DW_FLAG_CWHN = (1u << 0), - HTP_CONV2D_DW_FLAG_F16 = (1u << 1), -}; - -// WHCN_5X5_DMA VTCM layout shared by host and NPU: per-thread weight area (2 f16 slots + 25 f32 splats, rounded -// up) and the source slot tail for the valign over-read past the last row. -#define HTP_CONV2D_DW5_W_BYTES (32 * 128) -#define HTP_CONV2D_DW5_SRC_TAIL (3 * 128) - -struct htp_conv2d_dw_kernel_params { - uint8_t kernel_type; - uint8_t flags; // bitmask of enum htp_conv2d_dw_flags - uint8_t n_hvx; - - uint32_t total_tasks; - uint32_t vtcm_size; - uint32_t w; - uint32_t h; - uint32_t c; - uint32_t kw; - uint32_t kh; - uint32_t ow; - uint32_t oh; - int32_t s0; - int32_t s1; - int32_t p0; - int32_t p1; - int32_t d0; - int32_t d1; - uint32_t oh_chunk; - uint32_t n_chunks; - uint32_t row_src_bytes; - uint32_t row_dst_bytes; - uint32_t pad_top_stride; - struct fastdiv_values div_c; - struct fastdiv_values div_n_chunks; -}; - -#if defined(__cplusplus) -static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob"); -#else -_Static_assert(sizeof(struct htp_conv2d_dw_kernel_params) <= 128, "htp_conv2d_dw_kernel_params is too large for kernel_params blob"); -#endif - -struct htp_conv2d_dw_vtcm_layout { - size_t total_bytes; - size_t off_w; - size_t off_src; - size_t off_dst; - size_t src_spad_half_size; - size_t dst_spad_half_size; - size_t src_bytes_per_hvx; - size_t dst_bytes_per_hvx; -}; - -static inline void htp_conv2d_dw_vtcm_layout_build( - struct htp_conv2d_dw_vtcm_layout * L, - uint32_t max_src_bytes, - uint32_t max_dst_bytes, - uint32_t w_size, - uint32_t n_hvx -) { - L->src_spad_half_size = hex_round_up(max_src_bytes + 256, 128); - L->dst_spad_half_size = hex_round_up(max_dst_bytes + 128, 128); - L->src_bytes_per_hvx = 2 * L->src_spad_half_size; - L->dst_bytes_per_hvx = 2 * L->dst_spad_half_size; - - size_t off = 0; - VTCM_LAYOUT_ALLOC(off, off_w, hex_round_up(w_size, 128)); - VTCM_LAYOUT_ALLOC(off, off_src, L->src_bytes_per_hvx * n_hvx); - VTCM_LAYOUT_ALLOC(off, off_dst, L->dst_bytes_per_hvx * n_hvx); - L->total_bytes = off; -} - -struct htp_conv2d_dw5_vtcm_layout { - size_t total_bytes; - size_t off_src; - size_t off_weight; - size_t off_dst; - size_t src_row_stride; - size_t src_slot_bytes; - size_t dst_slot_bytes; -}; - -static inline void htp_conv2d_dw5_vtcm_layout_build( - struct htp_conv2d_dw5_vtcm_layout * L, - uint32_t w, - uint32_t h, - size_t src_es, - size_t dst_es, - uint32_t n_hvx -) { - L->src_row_stride = hex_align_up((size_t) (w + 4) * src_es, 128); - L->src_slot_bytes = hex_align_up((size_t) (h + 4) * L->src_row_stride + HTP_CONV2D_DW5_SRC_TAIL, 128); - L->dst_slot_bytes = hex_align_up((size_t) w * h * dst_es, 128); - - size_t off = 0; - VTCM_LAYOUT_ALLOC(off, off_src, (size_t) 2 * n_hvx * L->src_slot_bytes); - VTCM_LAYOUT_ALLOC(off, off_weight, (size_t) n_hvx * HTP_CONV2D_DW5_W_BYTES); - VTCM_LAYOUT_ALLOC(off, off_dst, (size_t) 2 * n_hvx * L->dst_slot_bytes); - L->total_bytes = off; -} - struct htp_conv2d_vtcm_layout { size_t total_bytes; size_t off_scales; diff --git a/ggml/src/ggml-hexagon/htp/htp-ctx.h b/ggml/src/ggml-hexagon/htp/htp-ctx.h index 7ceb77a72e81..b514f633e59a 100644 --- a/ggml/src/ggml-hexagon/htp/htp-ctx.h +++ b/ggml/src/ggml-hexagon/htp/htp-ctx.h @@ -185,7 +185,6 @@ int op_im2col(struct htp_ops_context * octx); int op_im2col_3d(struct htp_ops_context * octx); int op_conv_2d(struct htp_ops_context * octx); int op_conv_2d_dw(struct htp_ops_context * octx); -int op_conv_2d_dw5(struct htp_ops_context * octx); int op_pool_2d(struct htp_ops_context * octx); int op_pool_1d(struct htp_ops_context * octx); int op_allreduce(struct htp_ops_context * octx); From 72a780e6a6b5e64aee96379f67765760003d7948 Mon Sep 17 00:00:00 2001 From: Mark Todorovich Date: Thu, 3 Dec 2026 21:54:31 -0800 Subject: [PATCH 379/401] hexagon: CONV_2D/3D Cin chunking and cost-based tile solver (#32989) * hexagon: CONV_2D/3D Cin chunking and cost-based tile solver - stage input channels in chunks - stage per (channel, kd) channel stride > 24-bit 2D DMA stride limit - split weight packing into work items - replace first-fit tile selection with a solver - use fastdiv for the dilation division in the per-channel stage path * hexagon: conv-2d/3d rebase and fixes (guards for corner cases, etc) * hexagon: add mixed f16/f32 inputs, improve spad allocation and cleanup kparams * hexagon: conv-2d remove replace all divs and further cleanup kparams --------- Co-authored-by: Max Krasnyansky --- ggml/src/ggml-hexagon/htp-kparams.cpp | 310 +++++++++------ ggml/src/ggml-hexagon/htp/conv2d-ops.c | 524 +++++++++++++++++++------ ggml/src/ggml-hexagon/htp/conv2d-ops.h | 88 ++++- 3 files changed, 659 insertions(+), 263 deletions(-) diff --git a/ggml/src/ggml-hexagon/htp-kparams.cpp b/ggml/src/ggml-hexagon/htp-kparams.cpp index 4af17dea21c8..41ec31b64f63 100644 --- a/ggml/src/ggml-hexagon/htp-kparams.cpp +++ b/ggml/src/ggml-hexagon/htp-kparams.cpp @@ -4833,16 +4833,18 @@ static bool htp_kparams_conv2d_win( const uint32_t OH = dst->ne[1]; const uint32_t N = dst->ne[3]; const size_t es = ggml_type_size(src0->type); + const size_t x_es = ggml_type_size(src1->type); + const size_t y_es = ggml_type_size(dst->type); - if (s0 != 1 || s1 != 1 || p0 < 0 || p1 < 0 || dst->nb[0] != sizeof(float)) { + if (s0 != 1 || s1 != 1 || p0 < 0 || p1 < 0 || dst->nb[0] != y_es) { return false; } - if (dst->nb[1] < OW * sizeof(float) || (Cout > 1 && dst->nb[2] < OW * sizeof(float))) { + if (dst->nb[1] < OW * y_es || (Cout > 1 && dst->nb[2] < OW * y_es)) { return false; } - const bool whcn = src1->nb[0] == sizeof(float) && src1->nb[1] >= IW * sizeof(float) && (Cin == 1 || src1->nb[2] >= IH * src1->nb[1]); - const bool cwhn = !whcn && src1->nb[2] == sizeof(float) && src1->nb[0] == Cin * sizeof(float) && src1->nb[1] >= IW * src1->nb[0]; + const bool whcn = src1->nb[0] == x_es && src1->nb[1] >= IW * x_es && (Cin == 1 || src1->nb[2] >= IH * src1->nb[1]); + const bool cwhn = !whcn && src1->nb[2] == x_es && src1->nb[0] == Cin * x_es && src1->nb[1] >= IW * src1->nb[0]; if (!whcn && !cwhn) { return false; } @@ -4865,11 +4867,11 @@ static bool htp_kparams_conv2d_win( const uint32_t IHS = IH + 2 * p1; const uint32_t n_wt = fold ? KH : T; const uint32_t moff = (KH - 1) * d1 * SR + (fold ? 0 : (KW - 1) * d0); - const uint32_t halo = moff / 32 + 1; - const uint32_t n_rt = (Cout + 31) / 32; - const uint64_t n_q = (uint64_t) (N * IHS - (IHS - OH) - 1) * SR + OW; - const uint32_t nth = kp->n_hvx; - const size_t tile = 2048; + const uint32_t halo = moff / 32 + 1; + const uint32_t n_rt = (Cout + 31) / 32; + const uint64_t n_q = (uint64_t) (N * IHS - (IHS - OH) - 1) * SR + OW; + const uint32_t max_hvx = kp->n_hvx; + const size_t tile = 2048; if ((uint64_t) N * IHS * SR + moff + 64 >= (1ull << 31)) { return false; @@ -4916,7 +4918,7 @@ static bool htp_kparams_conv2d_win( rt_block = (rt_block + 1) / 2; } - size_t stage = 0, thr = 0, act = 0, out = 0, w_size = 0, total = 0; + size_t stage = 0, spad_per_hvx = 0, act = 0, out = 0, w_size = 0, total = 0; uint32_t n_bc = 0; while (true) { n_bc = ct + halo; @@ -4926,12 +4928,14 @@ static bool htp_kparams_conv2d_win( stage = (size_t) Cin * ((seg_b * 32 + OW - 1) / OW + 1) * IW * sizeof(float) + 256; } stage = hex_round_up(stage, 128); - thr = hex_round_up((std::max)(2 * stage + (size_t) HTP_CONV2D_WIN_OBUF * 32 * seg_t * 32 * sizeof(float), wscr), tile); + struct htp_conv2d_win_spad_layout sl; + htp_conv2d_win_spad_layout_build(&sl, stage, seg_t, wscr); + spad_per_hvx = sl.total_bytes; w_size = (size_t) rt_block * n_wt * n_cc * tile; act = (size_t) n_cc * n_bc * tile; out = (size_t) rt_block * ct * tile; struct htp_conv2d_vtcm_layout L; - htp_conv2d_vtcm_layout_build(&L, rt_block, w_size, act, out, thr, nth); + htp_conv2d_vtcm_layout_build(&L, rt_block, w_size, act, out, spad_per_hvx, max_hvx); total = L.total_bytes; if (total <= htp_session_vtcm_size(sess)) { break; @@ -4950,9 +4954,9 @@ static bool htp_kparams_conv2d_win( } } - uint32_t n_hvx = nth; + uint32_t n_hvx = max_hvx; // Keep the fold schedule, where output traffic can dominate input packing. - if (!fold && rt_block < n_rt && ct > 0 && nth > 0) { + if (!fold && rt_block < n_rt) { const uint32_t old_rt = rt_block; const uint32_t ct_max = (std::min)((std::min)((std::max)(4 * halo, (n_tiles + 3) / 4), 512u), n_tiles); const size_t budget = htp_session_vtcm_size(sess); @@ -4960,33 +4964,32 @@ static bool htp_kparams_conv2d_win( const size_t c_chunk = 8; const uint32_t tail = n_tiles % ct; const size_t work = - (size_t) (n_tiles / ct) * ((ct + halo + nth - 1) / nth) + (tail ? (tail + halo + nth - 1) / nth : 0); + (size_t) (n_tiles / ct) * ((ct + halo + max_hvx - 1) / max_hvx) + (tail ? (tail + halo + max_hvx - 1) / max_hvx : 0); size_t best_cost = (size_t) ((n_rt + rt_block - 1) / rt_block) * (n_cc * work + c_chunk * (n_tiles / ct + (tail != 0))); bool found = false; // Keep output DMA segments. Try larger kernel blocks to avoid rebuilding input croutons. for (uint32_t rb = n_rt; rb > old_rt && !found; rb = (rb + 1) / 2) { - for (uint32_t nt = nth; nt > 0; nt /= 2) { + for (uint32_t nh = max_hvx; nh > 0; nh /= 2) { for (uint32_t sb = 8; sb > 0; sb /= 2) { const size_t input_stage = hex_round_up(cwhn ? (size_t) sb * 32 * Cin * sizeof(float) + 256 : (size_t) n_ch * sb * 32 * sizeof(float), 128); - const size_t scratch = hex_round_up( - (std::max)(2 * input_stage + (size_t) HTP_CONV2D_WIN_OBUF * 32 * seg_t * 32 * sizeof(float), - wscr), - tile); - if (n_cc == 0 || n_wt > budget / tile / n_cc / rb || halo > budget / tile / n_cc || - scratch > budget / nt) { + struct htp_conv2d_win_spad_layout sl; + htp_conv2d_win_spad_layout_build(&sl, input_stage, seg_t, wscr); + const size_t spad = sl.total_bytes; + if (n_wt > budget / tile / n_cc / rb || halo > budget / tile / n_cc || + spad > budget / nh) { continue; } const size_t weights = (size_t) rb * n_wt * n_cc * tile; htp_conv2d_vtcm_layout fixed; - htp_conv2d_vtcm_layout_build(&fixed, rb, weights, (size_t) n_cc * halo * tile, 0, scratch, nt); + htp_conv2d_vtcm_layout_build(&fixed, rb, weights, (size_t) n_cc * halo * tile, 0, spad, nh); if (fixed.total_bytes >= budget) { continue; } const size_t per_ct = 2 * ((size_t) n_cc + rb) * tile; const uint32_t cap = (uint32_t) (std::min)((size_t) ct_max, (budget - fixed.total_bytes) / per_ct); - const uint32_t aligned = (cap + halo) / nt * nt; + const uint32_t aligned = (cap + halo) / nh * nh; const uint32_t candidates[2] = { cap, aligned > halo ? aligned - halo : 0 }; for (uint32_t i = 0; i < 2; i++) { const uint32_t candidate = candidates[i]; @@ -4997,30 +5000,30 @@ static bool htp_kparams_conv2d_win( continue; } const uint32_t rem = n_tiles % candidate; - const size_t input_work = (size_t) (n_tiles / candidate) * ((candidate + halo + nt - 1) / nt) + (rem ? (rem + halo + nt - 1) / nt : 0); + const size_t input_work = (size_t) (n_tiles / candidate) * ((candidate + halo + nh - 1) / nh) + (rem ? (rem + halo + nh - 1) / nh : 0); const size_t chunks = n_tiles / candidate + (rem != 0); const size_t cost = (size_t) ((n_rt + rb - 1) / rb) * (n_cc * input_work + c_chunk * chunks); if (cost < best_cost) { const size_t input = (size_t) n_cc * (candidate + halo) * tile; const size_t output = (size_t) rb * candidate * tile; htp_conv2d_vtcm_layout L; - htp_conv2d_vtcm_layout_build(&L, rb, weights, input, output, scratch, nt); + htp_conv2d_vtcm_layout_build(&L, rb, weights, input, output, spad, nh); if (L.total_bytes > budget) { continue; } - found = true; - best_cost = cost; - rt_block = rb; - ct = candidate; - seg_b = sb; - n_hvx = nt; - stage = input_stage; - thr = scratch; - act = input; - out = output; - w_size = weights; - total = L.total_bytes; - n_bc = candidate + halo; + found = true; + best_cost = cost; + rt_block = rb; + ct = candidate; + seg_b = sb; + n_hvx = nh; + stage = input_stage; + spad_per_hvx = spad; + act = input; + out = output; + w_size = weights; + total = L.total_bytes; + n_bc = candidate + halo; } } } @@ -5044,7 +5047,7 @@ static bool htp_kparams_conv2d_win( kp->ct_chunk = ct; kp->rt_block = rt_block; kp->stage_size = stage; - kp->thr_size = thr; + kp->spad_per_hvx = spad_per_hvx; kp->vtcm_size = total; kp->window.fold = fold; kp->window.n_cc = n_cc; @@ -5053,9 +5056,10 @@ static bool htp_kparams_conv2d_win( kp->window.ihs = IHS; kp->window.max_off = moff; kp->window.n_bc = n_bc; - kp->window.seg_b = seg_b; - kp->window.seg_t = seg_t; - kp->window.w_cs = w_cs; + kp->window.seg_b = (uint16_t) seg_b; + kp->window.seg_t = (uint16_t) seg_t; + kp->window.w_cs = (uint16_t) w_cs; + kp->window.w_n_seg = (uint16_t) (w_rows ? n_cs : n_tg); kp->window.div_sr = init_fastdiv_values(SR); kp->window.div_ihs = init_fastdiv_values(IHS); kp->window.div_kw = init_fastdiv_values(KW); @@ -5089,7 +5093,7 @@ static bool htp_conv_normalize_geom(const struct ggml_tensor * dst, struct htp_c if (kh_w < 1 || kh_w > 255 || k_w < 1 || k_w > (1 << 24) || ct_w < 1 || ct_w > UINT32_MAX) { return false; } - if (s0 <= 0 || d0 <= 0 || dst->nb[0] != sizeof(float)) { + if (s0 <= 0 || d0 <= 0 || dst->nb[0] != ggml_type_size(dst->type)) { return false; } @@ -5129,8 +5133,9 @@ static bool htp_kparams_conv2d_tiled( // kernel k order must match the staged input: (cin, kh, kw) for WHCN input, (kh, kw, cin) for CWHN input. // Kernel is either k-contiguous rows per cout (WHCN only) or cout-contiguous with a uniform k stride. - const bool whcn = g.is3d || src1->nb[0] == sizeof(float); - const bool cwhn = !whcn && src1->nb[2] == sizeof(float) && src1->nb[0] == g.Cin * sizeof(float); + const size_t x_es = ggml_type_size(src1->type); + const bool whcn = g.is3d || src1->nb[0] == x_es; + const bool cwhn = !whcn && src1->nb[2] == x_es && src1->nb[0] == g.Cin * x_es; const bool co_c = g.Cout == 1 || src0->nb[3] == g.es; const bool w_rows = g.is3d || (whcn && src0->nb[0] == g.es && (g.KH == 1 || src0->nb[1] == g.KW * g.es) && (g.Cin == 1 || src0->nb[2] == g.KW * g.KH * g.es)); const size_t ks = whcn ? src0->nb[0] : src0->nb[2]; @@ -5144,6 +5149,9 @@ static bool htp_kparams_conv2d_tiled( return false; } kmajor = kmajor && !w_rows; + if (kmajor && ks > UINT32_MAX) { + return false; + } const uint32_t K = g.KW * g.KH * g.Cin; const uint32_t kg = !cwhn ? K : g.d0 == 1 ? g.KW * g.Cin : g.Cin; @@ -5154,77 +5162,140 @@ static bool htp_kparams_conv2d_tiled( const uint32_t n_rt = (g.Cout + 31) / 32; const uint32_t n_owt = (g.OW + 31) / 32; const uint32_t n_ct = g.N * g.OH * n_owt; - const uint32_t wk = (std::min)(k_pad, 512u); + const uint32_t KW = g.KW, KH = g.KH, Cin = g.Cin, s0 = g.s0, d0 = g.d0; + // channel stride over the 24-bit 2D DMA limit: stage one DMA per (channel, kd) instead of the sync per-row fallback + const uint32_t KD = g.is3d ? src0->ne[2] : 1; + const size_t x_nb_c = g.is3d ? src1->nb[3] : src1->nb[2]; + const bool stage_pc = whcn && x_nb_c > 0x00FFFFFFu; + const uint32_t cc_max = stage_pc ? (std::max)(1u, 255 / KD) : 32768; const uint32_t max_hvx = htp_session_n_hvx(sess); - const size_t tile = 2048; - - uint32_t rt_block = n_rt; - uint32_t ct = 0; - uint32_t seg = 0; - uint32_t nth = 0; + const size_t tile = 2048; + const size_t budget = htp_session_vtcm_size(sess); + // cost model constants in 0.1 ns, fitted to v81 measurements: pack per k tile, DMA per descriptor and per row, per chunk, unpack + const uint64_t c_pack = 710; + const uint64_t c_desc = 885; + const uint64_t c_row = 113; + const uint64_t c_chunk = 75850; + const uint64_t c_unp = 2500; + + uint32_t rt_block = 0, ct = 0, seg = 0, cc = Cin, n_hvx = 0, wk = 0; uint32_t n_stage = 1; uint32_t sr = 0; - size_t stage = 0, thr_size = 0; - size_t best_cost = SIZE_MAX; - const size_t wpack = kmajor ? 2 * (size_t) wk * 64 * sizeof(float) + 96 * 128 : 2 * (size_t) 32 * wk * (sizeof(float) + sizeof(uint16_t)); - const size_t budget = htp_session_vtcm_size(sess); - // Approximate chunk overhead in patch K-tile work units. - const size_t c_chunk = 8; - - // Keep the kernel resident to avoid regenerating the input for each rt block. - // Balance patch work per thread and chunk overhead before reducing rt. - for (uint32_t rb = n_rt; rb > 0 && ct == 0; rb = rb > 1 ? (rb + 1) / 2 : 0) { - for (uint32_t nt = max_hvx; nt > 0; nt /= 2) { + size_t stage = 0, spad_per_hvx = 0; + uint64_t best_cost = UINT64_MAX; + + // pick the config with the lowest estimated time among all that fit VTCM + for (uint32_t rb = n_rt; rb > 0; rb = rb > 1 ? (rb + 1) / 2 : 0) { + const uint64_t n_rp = (n_rt + rb - 1) / rb; + for (uint32_t nh = max_hvx; nh > 0; nh /= 2) { for (uint32_t sg = (std::min)(8u, n_owt); sg > 0; --sg) { // Keep the unused final stride lane for full-vector loads during packing. - const uint64_t wb = (uint64_t) 32 * sg * g.s0 + (uint64_t) (g.KW - 1) * g.d0; + const uint64_t wb = (uint64_t) 32 * sg * s0 + (uint64_t) (KW - 1) * d0; if (wb > budget / sizeof(float) || wb > INT32_MAX) { continue; } - const uint64_t width = cwhn ? wb * g.Cin : wb; + const uint64_t width = cwhn ? wb * Cin : wb; if (width > budget / sizeof(float) || width > UINT32_MAX - 63) { continue; } - const uint32_t row = hex_round_up((uint32_t) width, cwhn ? 64 : 32); - const uint64_t rows = cwhn ? g.KH : (uint64_t) g.Cin * g.KH; - if (rows > budget / ((uint64_t) row * sizeof(float))) { - continue; - } - const size_t input_stage = cwhn ? (size_t) g.KH * row * sizeof(float) : (size_t) g.Cin * g.KH * row * sizeof(float); - const size_t output_stage = 2 * 32 * (size_t) sg * 32 * sizeof(float); - const size_t transpose = cwhn ? input_stage / 2 + 256 + 64 * 128 : 0; - const size_t scratch = hex_round_up((std::max)(input_stage + output_stage + transpose, wpack), tile); - htp_conv2d_vtcm_layout fixed; - htp_conv2d_vtcm_layout_build(&fixed, rb, (size_t) rb * n_kt * tile, 0, 0, scratch, nt); - if (fixed.total_bytes >= budget) { + const uint32_t row = hex_round_up((uint32_t) width, cwhn ? 64 : 32); + const size_t per = (size_t) KH * row * sizeof(float); + if (per > budget) { continue; } - // Each spatial tile adds two activation tiles and two output tiles per rt. - const size_t per_ct = 2 * ((size_t) n_kt + rb) * tile; - const uint32_t nc = (uint32_t) (std::min)((size_t) (std::min)(n_ct, 64u), (budget - fixed.total_bytes) / per_ct); - const uint32_t candidates[2] = { nc, nc / nt * nt }; - for (uint32_t i = 0; i < 2; i++) { - const uint32_t candidate = candidates[i]; - if (candidate == 0 || (i > 0 && candidate == candidates[0])) { + // channel chunk: all channels or the most that fit HTP_CONV2D_STAGE_MAX, step k range even unless whole K + uint32_t cc_cap = (uint32_t) (std::max)((size_t) 1, (std::min)({ (size_t) Cin, HTP_CONV2D_STAGE_MAX / per, (size_t) cc_max })); + if (cc_cap < Cin && (cc_cap * KW * KH) % 2) { + if (cc_cap > 1) { + cc_cap--; + } else if (cc_max >= 2) { + cc_cap = 2; + } + } + const uint32_t ccs[2] = { Cin, cwhn ? Cin : cc_cap }; + for (uint32_t j = 0; j < 2; j++) { + const uint32_t c = ccs[j]; + if ((j > 0 && c == ccs[0]) || (!cwhn && c > cc_max) || (!cwhn && c < Cin && ((c * KW * KH) & 1))) { continue; } - const uint32_t per_hvx = (candidate + nt - 1) / nt; - if (sg > per_hvx) { + if (!cwhn && c > budget / per) { continue; } - const size_t work = (size_t) (n_ct / candidate) * per_hvx + (n_ct % candidate + nt - 1) / nt; - const size_t chunks = n_ct / candidate + (n_ct % candidate != 0); - const size_t cost = work * n_kt + c_chunk * chunks; - if (cost < best_cost) { - best_cost = cost; - rt_block = rb; - ct = candidate; - seg = sg; - nth = nt; - sr = row; - stage = input_stage; - thr_size = scratch; + const uint32_t n_cc = (Cin + c - 1) / c; + const uint32_t n_dma = stage_pc ? c * KD : KH; + const size_t rows = cwhn ? KH : (size_t) c * KH; + + const size_t input_stage = cwhn ? per : (size_t) c * per; + + // second stage buffer overlaps next DMA with this pack; skip it for large stages + for (uint32_t ns = 2; ns > 0; ns--) { + if (ns == 2 && (input_stage > HTP_CONV2D_STAGE_MAX || 2 * n_dma > 255)) { + continue; + } + // weight pack scratch shares the per-HVX spad region, take the largest k step that does not grow it + uint32_t w_k = (std::min)(k_pad, 512u); + struct htp_conv2d_tiled_spad_layout sl; + while (true) { + htp_conv2d_tiled_spad_layout_build(&sl, input_stage, ns, sg, cwhn, kmajor, w_k); + if (w_k <= 64 || sl.wpack_bytes <= sl.stages_bytes) { + break; + } + w_k = (std::max)(64u, w_k / 2 / 64 * 64); + } + const size_t spad = sl.total_bytes; + if (spad > budget / nh) { + continue; + } + htp_conv2d_vtcm_layout fixed; + htp_conv2d_vtcm_layout_build(&fixed, rb, (size_t) rb * n_kt * tile, 0, 0, spad, nh); + if (fixed.total_bytes >= budget) { + continue; + } + + // Each col tile adds two activation tiles and two output tiles per rt + const size_t per_ct = 2 * ((size_t) n_kt + rb) * tile; + const uint32_t nc = (uint32_t) (std::min)((size_t) (std::min)(n_ct, 64u), (budget - fixed.total_bytes) / per_ct); + const uint32_t candidates[2] = { nc, nc / nh * nh }; + for (uint32_t i = 0; i < 2; i++) { + const uint32_t cand = candidates[i]; + if (cand == 0 || (i > 0 && cand == candidates[0])) { + continue; + } + if (sg > (cand + nh - 1) / nh) { + continue; + } + // chunk of m col tiles: HVX lanes take tpt each, idle lanes split the channel chunks + const auto chunk_cost = [&](uint32_t m) -> uint64_t { + const uint32_t tpt = (m + nh - 1) / nh; + const uint32_t n_tt = (m + tpt - 1) / tpt; + const uint32_t n_cs = (std::min)(n_cc, nh / n_tt); + const uint32_t cpt = (n_cc + n_cs - 1) / n_cs; + const uint64_t steps = (uint64_t) ((tpt + sg - 1) / sg) * cpt; + const uint64_t pack = (c_pack * tpt * cpt * n_kt + n_cc - 1) / n_cc; + const uint64_t dma = c_desc * n_dma + c_row * rows; + const uint64_t pstep = (pack + steps - 1) / steps; + const uint64_t in = steps * dma + pack; + const uint64_t full = dma + (steps - 1) * (std::max)(dma, pstep) + pstep; + const uint64_t unp = c_unp * rb * tpt; + return (ns == 2 ? (in + full) / 2 : in) + unp + c_chunk; + }; + const uint64_t wwork = c_pack * (((uint64_t) rb * n_kt + nh - 1) / nh); + const uint64_t cost = n_rp * (wwork + (uint64_t) (n_ct / cand) * chunk_cost(cand) + (n_ct % cand ? chunk_cost(n_ct % cand) : 0)); + if (cost < best_cost) { + best_cost = cost; + rt_block = rb; + ct = cand; + seg = sg; + n_hvx = nh; + cc = c; + wk = w_k; + n_stage = ns; + sr = row; + stage = input_stage; + spad_per_hvx = spad; + } + } } } } @@ -5237,33 +5308,20 @@ static bool htp_kparams_conv2d_tiled( const size_t w_size = (size_t) rt_block * n_kt * tile; const size_t act_size = (size_t) ct * n_kt * tile; const size_t out_size = (size_t) rt_block * ct * tile; - const size_t ostage = 2 * 32 * (size_t) seg * 32 * sizeof(float); - const size_t prow = cwhn ? stage / 2 + 256 + 64 * 128 : 0; struct htp_conv2d_vtcm_layout L; - htp_conv2d_vtcm_layout_build(&L, rt_block, w_size, act_size, out_size, thr_size, nth); - size_t total = L.total_bytes; - - // Second stage buffer: DMA of the next segment overlaps HVX pack of this one. - // Skip large stages. They already fill VTCM, and the extra DMA slows HMX. - { - const size_t thr2 = hex_round_up((std::max)(2 * stage + ostage + prow, wpack), tile); - struct htp_conv2d_vtcm_layout L2; - htp_conv2d_vtcm_layout_build(&L2, rt_block, w_size, act_size, out_size, thr2, nth); - if (stage <= 128 * 1024 && 2 * g.KH <= 255 && L2.total_bytes <= htp_session_vtcm_size(sess)) { - n_stage = 2; - thr_size = thr2; - total = L2.total_bytes; - } - } + htp_conv2d_vtcm_layout_build(&L, rt_block, w_size, act_size, out_size, spad_per_hvx, n_hvx); + const size_t total = L.total_bytes; kp->kernel_type = (uint8_t) HTP_CONV2D_KERNEL_HMX_TILED; - kp->flags = (cwhn ? HTP_CONV2D_FLAG_CWHN : 0) | (kmajor ? HTP_CONV2D_FLAG_W_KMAJOR : 0); - kp->n_hvx = (uint8_t) nth; + kp->flags = (cwhn ? HTP_CONV2D_FLAG_CWHN : 0) | + (kmajor ? HTP_CONV2D_FLAG_W_KMAJOR : 0) | + (stage_pc ? HTP_CONV2D_FLAG_STAGE_PC : 0); + kp->n_hvx = (uint8_t) n_hvx; kp->n_row_tiles = n_rt; kp->ct_chunk = ct; kp->rt_block = rt_block; kp->stage_size = stage; - kp->thr_size = thr_size; + kp->spad_per_hvx = spad_per_hvx; kp->vtcm_size = total; kp->tiled.w_kstride = ks; kp->tiled.k_size = K; @@ -5272,14 +5330,18 @@ static bool htp_kparams_conv2d_tiled( kp->tiled.n_groups = n_grp; kp->tiled.n_k_tiles = n_kt; kp->tiled.n_ow_tiles = n_owt; - kp->tiled.seg_tiles = seg; + kp->tiled.seg_tiles = (uint16_t) seg; kp->tiled.stage_row = sr; - kp->tiled.n_stage = n_stage; + kp->tiled.n_stage = (uint16_t) n_stage; + kp->tiled.cin_chunk = cc; + kp->tiled.n_cin_chunks = (Cin + cc - 1) / cc; + kp->tiled.kd = KD; kp->tiled.wk_chunk = wk; kp->tiled.div_ow_tiles = init_fastdiv_values(n_owt); kp->tiled.div_oh = init_fastdiv_values(g.OH); kp->tiled.div_khr = init_fastdiv_values(src0->ne[1]); kp->tiled.div_ohr = init_fastdiv_values(dst->ne[1]); + kp->tiled.div_d1 = init_fastdiv_values(ggml_get_op_params_i32(dst, g.is3d ? 7 : 5)); return true; } @@ -5313,7 +5375,8 @@ static bool htp_kparams_solve_conv2d( const struct ggml_tensor * dst = op; if ((src0->type != GGML_TYPE_F16 && src0->type != GGML_TYPE_F32) || - src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + (src1->type != GGML_TYPE_F16 && src1->type != GGML_TYPE_F32) || + (dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_F32)) { return false; } @@ -5539,7 +5602,8 @@ static bool htp_kparams_solve_conv3d( const struct ggml_tensor * dst = op; if ((src0->type != GGML_TYPE_F16 && src0->type != GGML_TYPE_F32) || - src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + (src1->type != GGML_TYPE_F16 && src1->type != GGML_TYPE_F32) || + (dst->type != GGML_TYPE_F16 && dst->type != GGML_TYPE_F32)) { return false; } diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.c b/ggml/src/ggml-hexagon/htp/conv2d-ops.c index 41fc50323e45..ee696d4ed300 100644 --- a/ggml/src/ggml-hexagon/htp/conv2d-ops.c +++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.c @@ -171,6 +171,15 @@ static void conv_geom_init(struct htp_conv_geom * g, const struct htp_ops_contex } } +struct htp_conv2d_chunk_plan { + uint32_t tpt; + uint32_t n_tt; + uint32_t n_cs; + uint32_t cc_q; + uint32_t cc_r; + struct fastdiv_values div_n_tt; +}; + struct htp_conv2d_hmx_context { struct htp_ops_context * octx; const struct htp_conv2d_kernel_params * kp; @@ -180,15 +189,21 @@ struct htp_conv2d_hmx_context { __fp16 * w_tiles; __fp16 * act[2]; __fp16 * out[2]; - uint8_t * thr_base; + uint8_t * spad_base; uint32_t t_base; uint32_t t_end; uint32_t rt0; uint32_t n_rt; int32_t pack_chunk; int32_t unpack_chunk; - uint32_t pack_tpt; + int32_t last_chunk; uint32_t unpack_tpt; + uint32_t wpack_n_kp; + uint32_t wpack_ks_q; + uint32_t wpack_ks_r; + struct fastdiv_values wpack_div_n_kp; + struct htp_conv2d_chunk_plan plan[2]; // 0: full chunk, 1: tail chunk + const struct htp_conv2d_chunk_plan * pack_plan; }; // col tiles [t0, t1) of chunk c for thread ith, returns first col tile of the chunk @@ -215,12 +230,12 @@ static void conv2d_hmx_wpack_thread(const htp_thread_t * th, unsigned int nth, u const uint32_t es = is_f16 ? sizeof(__fp16) : sizeof(float); dma_queue * dmaq = th->dma_q; - uint8_t * thr = hc->thr_base + (size_t) ith * kp->thr_size; + uint8_t * spad = hc->spad_base + (size_t) ith * kp->spad_per_hvx; const size_t w_buf_size = (size_t) WK * 32 * sizeof(__fp16); const size_t w_raw_size = (size_t) WK * 32 * sizeof(float); const size_t w_step = w_buf_size + w_raw_size; - __fp16 * wbuf[2] = { (__fp16 *) thr, (__fp16 *) (thr + w_step) }; + __fp16 * wbuf[2] = { (__fp16 *) spad, (__fp16 *) (spad + w_step) }; float * wraw[2] = { (float *) ((uint8_t *) wbuf[0] + w_buf_size), (float *) ((uint8_t *) wbuf[1] + w_buf_size) }; uint8_t * wdma[2] = { is_f16 ? (uint8_t *) wbuf[0] : (uint8_t *) wraw[0], @@ -230,19 +245,30 @@ static void conv2d_hmx_wpack_thread(const htp_thread_t * th, unsigned int nth, u struct htp_thread_trace * tr = th->trace; - for (uint32_t rt = ith; rt < hc->n_rt; rt += nth) { - const uint32_t co0 = (hc->rt0 + rt) * 32; - const uint32_t nco = MIN(32, Cout - co0); + // work items are (rt, k range) so deep K keeps all threads busy when rt_block is small + const uint32_t n_kp = hc->wpack_n_kp; + const uint32_t ks_q = hc->wpack_ks_q; + const uint32_t ks_r = hc->wpack_ks_r; + + for (uint32_t it = ith; it < hc->n_rt * n_kp; it += nth) { + const uint32_t rt = fastdiv(it, &hc->wpack_div_n_kp); + const uint32_t kpi = it - rt * n_kp; + const uint32_t co0 = (hc->rt0 + rt) * 32; + const uint32_t nco = MIN(32, Cout - co0); + const uint32_t ks0 = kpi * ks_q + MIN(kpi, ks_r); + const uint32_t ks1 = ks0 + ks_q + (kpi < ks_r ? 1 : 0); + const uint32_t kbeg = ks0 * WK; + const uint32_t kend = MIN(ks1 * WK, k_pad); uint32_t bi = 0; - for (uint32_t i = 0; i < 2 && i * WK < k_pad; i++) { - const uint32_t kc = i * WK; + for (uint32_t i = 0; i < 2 && kbeg + i * WK < kend; i++) { + const uint32_t kc = kbeg + i * WK; const uint32_t kv = MIN(WK, K - kc); dma_queue_push(dmaq, dma_make_data(wdma[i], kernel->data + (size_t) co0 * hc->g->w_nb_co + (size_t) kc * es), WK * es, hc->g->w_nb_co, kv * es, nco); } - for (uint32_t kc = 0; kc < k_pad; kc += WK) { + for (uint32_t kc = kbeg; kc < kend; kc += WK) { const uint32_t kv = MIN(WK, K - kc); const uint32_t hd = MIN(WK, k_pad - kc); @@ -270,7 +296,7 @@ static void conv2d_hmx_wpack_thread(const htp_thread_t * th, unsigned int nth, u htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_W_PREP, (uint16_t) kc); const uint32_t next_kc = kc + 2 * WK; - if (next_kc < k_pad) { + if (next_kc < kend) { const uint32_t next_kv = MIN(WK, K - next_kc); dma_queue_push(dmaq, dma_make_data(wdma[bi], kernel->data + (size_t) co0 * hc->g->w_nb_co + (size_t) next_kc * es), WK * es, hc->g->w_nb_co, next_kv * es, nco); @@ -280,26 +306,76 @@ static void conv2d_hmx_wpack_thread(const htp_thread_t * th, unsigned int nth, u } } +// Backwards in-place f16 -> f32 expansion in VTCM (buf has f32 capacity). +static __attribute__((noinline)) void conv2d_hmx_expand_f16_to_f32_inplace(float * buf, uint32_t n_elems) { + const uint32_t full = n_elems & ~63u; + const uint32_t rem = n_elems - full; + if (rem > 0) { + const HVX_Vector v = hvx_vmemu((const __fp16 *) buf + full); + const HVX_VectorPair p = hvx_vec_f16_to_f32(v); + if (rem <= VLEN_FP32) { + hvx_vec_store_u(buf + full, rem * sizeof(float), Q6_V_lo_W(p)); + } else { + hvx_vec_store_u(buf + full, VLEN, Q6_V_lo_W(p)); + hvx_vec_store_u(buf + full + VLEN_FP32, (rem - VLEN_FP32) * sizeof(float), Q6_V_hi_W(p)); + } + } + for (int32_t i = (int32_t) full - 64; i >= 0; i -= 64) { + const HVX_Vector v = hvx_vmemu((const __fp16 *) buf + i); + const HVX_VectorPair p = hvx_vec_f16_to_f32(v); + hvx_vec_store_u(buf + i + VLEN_FP32, VLEN, Q6_V_hi_W(p)); + hvx_vec_store_u(buf + i, VLEN, Q6_V_lo_W(p)); + } +} + +static __attribute__((noinline)) void conv2d_hmx_expand_rows_f16_to_f32(float * stage, uint32_t row_stride, uint32_t row_elems, uint32_t n_rows) { + for (uint32_t r = 0; r < n_rows; r++) { + conv2d_hmx_expand_f16_to_f32_inplace(stage + (size_t) r * row_stride, row_elems); + } +} + +// Pack n_rows of row_elems f32 values at f32 row stride row_stride into f16 in-place (preserving 128B row alignment). +static __attribute__((noinline)) void conv2d_hmx_pack_rows_f32_to_f16(float * ob, uint32_t row_stride, uint32_t row_elems, uint32_t n_rows) { + for (uint32_t r = 0; r < n_rows; r++) { + const float * src = ob + (size_t) r * row_stride; + __fp16 * dst = (__fp16 *) (ob + (size_t) r * row_stride); + uint32_t i = 0; + for (; i + 64 <= row_elems; i += 64) { + const HVX_Vector v0 = hvx_vmem(src + i); + const HVX_Vector v1 = hvx_vmem(src + i + VLEN_FP32); + hvx_vmem(dst + i) = conv2d_f32_to_f16(v0, v1); + } + const uint32_t rem = row_elems - i; + if (rem > 0) { + const HVX_Vector v0 = hvx_vmem(src + i); + const HVX_Vector v1 = (rem > VLEN_FP32) ? hvx_vmem(src + i + VLEN_FP32) : Q6_V_vzero(); + hvx_vec_store_a(dst + i, rem * sizeof(__fp16), conv2d_f32_to_f16(v0, v1)); + } + } +} + // Stage Cin*KH input rows for G col tiles: stage[(cin*KH + kh)*SR + j] = x[n][cin][ih(kh)][ow0*s0 - p0 + j], zero outside // For conv_3d, kh = kd * KHr + kh' and oh = od * OHr + oh' are unfolded here static void conv2d_hmx_stage(const struct htp_ops_context * octx, const struct htp_conv2d_kernel_params * kp, const struct htp_conv_geom * g, dma_queue * dmaq, float * stage, uint32_t n, uint32_t oh, - uint32_t ow0, uint32_t G) { + uint32_t ow0, uint32_t G, uint32_t c0, uint32_t cc) { const struct htp_tensor * kernel = octx->src[0]; const struct htp_tensor * input = octx->src[1]; - const uint32_t KW = kernel->ne[0]; - const uint32_t KH = g->KH; - const uint32_t Cin = g->Cin; - const int32_t IW = input->ne[0]; - const int32_t IH = input->ne[1]; - const int32_t s0 = g->s0; - const int32_t s1 = g->s1; - const int32_t p0 = g->p0; - const int32_t p1 = g->p1; - const int32_t d0 = g->d0; - const int32_t d1 = g->d1; - const uint32_t SR = kp->tiled.stage_row; + const uint32_t KW = kernel->ne[0]; + const uint32_t KH = g->KH; + const uint32_t Cin = cc; + const int32_t IW = input->ne[0]; + const int32_t IH = input->ne[1]; + const int32_t s0 = g->s0; + const int32_t s1 = g->s1; + const int32_t p0 = g->p0; + const int32_t p1 = g->p1; + const int32_t d0 = g->d0; + const int32_t d1 = g->d1; + const uint32_t SR = kp->tiled.stage_row; + const uint32_t x_es = input->type == HTP_TYPE_F16 ? sizeof(__fp16) : sizeof(float); + const HVX_Vector zero = Q6_V_vzero(); const int32_t Wb = 32 * G * s0 + (KW - 1) * d0; const int32_t iw0 = (int32_t) ow0 * s0 - p0; @@ -317,24 +393,93 @@ static void conv2d_hmx_stage(const struct htp_ops_context * octx, const struct h if (id < 0 || id >= (int32_t) g->ID || ih < 0 || ih >= IH || hi <= lo) { for (uint32_t c = 0; c < Cin; c++) { - hvx_splat_f32_u(rows + (size_t) c * KH * SR, 0.0f, Wb); + hvx_splat_u(rows + (size_t) c * KH * SR, zero, Wb, x_es); } dma_queue_push(dmaq, dma_make_data(rows, 0), 0, 0, 0, 0); continue; } - const dma_addr_t src = input->data + (size_t) n * g->x_nb_n + (size_t) id * g->x_nb_d + (size_t) ih * input->nb[1] + (size_t) (iw0 + lo) * sizeof(float); - dma_queue_push(dmaq, dma_make_data(rows + lo, src), (size_t) KH * SR * sizeof(float), g->x_nb_c, - (size_t) (hi - lo) * sizeof(float), Cin); + const dma_addr_t src = input->data + (size_t) n * g->x_nb_n + (size_t) id * g->x_nb_d + (size_t) ih * input->nb[1] + (size_t) (iw0 + lo) * x_es + (size_t) c0 * g->x_nb_c; + dma_queue_push(dmaq, dma_make_data((uint8_t *) rows + (size_t) lo * x_es, src), (size_t) KH * SR * sizeof(float), g->x_nb_c, + (size_t) (hi - lo) * x_es, Cin); if (lo > 0 || hi < Wb) { for (uint32_t c = 0; c < Cin; c++) { - float * row = rows + (size_t) c * KH * SR; + uint8_t * row = (uint8_t *) (rows + (size_t) c * KH * SR); if (lo > 0) { - hvx_splat_f32_u(row, 0.0f, lo); + hvx_splat_u(row, zero, lo, x_es); } if (hi < Wb) { - hvx_splat_f32_u(row + hi, 0.0f, Wb - hi); + hvx_splat_u(row + (size_t) hi * x_es, zero, Wb - hi, x_es); + } + } + } + } +} + +// Same layout as conv2d_hmx_stage, but one DMA per (c, kd) for channel strides over the 2D DMA limit +static void conv2d_hmx_stage_pc(const struct htp_ops_context * octx, const struct htp_conv2d_kernel_params * kp, + const struct htp_conv_geom * g, dma_queue * dmaq, float * stage, uint32_t n, uint32_t oh, + uint32_t ow0, uint32_t G, uint32_t c0, uint32_t cc) { + const struct htp_tensor * kernel = octx->src[0]; + const struct htp_tensor * input = octx->src[1]; + + const uint32_t KW = kernel->ne[0]; + const uint32_t KH = g->KH; + const uint32_t KHr = g->KHr; + const uint32_t KD = kp->tiled.kd; + const int32_t IW = input->ne[0]; + const int32_t IH = input->ne[1]; + const int32_t s0 = g->s0; + const int32_t s1 = g->s1; + const int32_t d0 = g->d0; + const int32_t d1 = g->d1; + const uint32_t SR = kp->tiled.stage_row; + const uint32_t x_es = input->type == HTP_TYPE_F16 ? sizeof(__fp16) : sizeof(float); + const HVX_Vector zero = Q6_V_vzero(); + + const int32_t Wb = 32 * G * s0 + (KW - 1) * d0; + const int32_t iw0 = (int32_t) ow0 * s0 - g->p0; + const int32_t lo = MAX(0, -iw0); + const int32_t hi = MIN(Wb, IW - iw0); + + const uint32_t od = fastdiv(oh, &kp->tiled.div_ohr); + oh -= od * g->OHr; + + // kh rows [kb, ke) have ih = b + kh * d1 in [0, IH) + const int32_t b = (int32_t) oh * s1 - g->p1; + const int32_t kb = MIN((int32_t) KHr, b >= 0 ? 0 : (int32_t) fastdiv(-b + d1 - 1, &kp->tiled.div_d1)); + const int32_t ke = MAX(kb, MIN((int32_t) KHr, IH - b <= 0 ? 0 : (int32_t) fastdiv(IH - b + d1 - 1, &kp->tiled.div_d1))); + + for (uint32_t c = 0; c < cc; c++) { + for (uint32_t kd = 0; kd < KD; kd++) { + const int32_t id = (int32_t) od * g->s2 + (int32_t) kd * g->d2 - g->p2; + float * rows = stage + ((size_t) c * KH + kd * KHr) * SR; + + if (id < 0 || id >= (int32_t) g->ID || kb >= ke || hi <= lo) { + for (uint32_t kh = 0; kh < KHr; kh++) { + hvx_splat_u(rows + (size_t) kh * SR, zero, Wb, x_es); + } + dma_queue_push(dmaq, dma_make_data(rows, 0), 0, 0, 0, 0); + continue; + } + + const dma_addr_t src = input->data + (size_t) n * g->x_nb_n + (size_t) (c0 + c) * g->x_nb_c + (size_t) id * g->x_nb_d + + (size_t) (b + kb * d1) * input->nb[1] + (size_t) (iw0 + lo) * x_es; + dma_queue_push(dmaq, dma_make_data((uint8_t *) (rows + (size_t) kb * SR) + (size_t) lo * x_es, src), + (size_t) SR * sizeof(float), (size_t) d1 * input->nb[1], (size_t) (hi - lo) * x_es, ke - kb); + + for (int32_t kh = 0; kh < (int32_t) KHr; kh++) { + uint8_t * row = (uint8_t *) (rows + (size_t) kh * SR); + if (kh < kb || kh >= ke) { + hvx_splat_u(row, zero, Wb, x_es); + continue; + } + if (lo > 0) { + hvx_splat_u(row, zero, lo, x_es); + } + if (hi < Wb) { + hvx_splat_u(row + (size_t) hi * x_es, zero, Wb - hi, x_es); } } } @@ -409,43 +554,50 @@ static void conv2d_hmx_stage_cwhn(const struct htp_ops_context * octx, const str const int32_t d1 = octx->op_params[5]; const uint32_t SR = kp->tiled.stage_row; - const int32_t Wb = 32 * G * s0 + (KW - 1) * d0; - const int32_t iw0 = (int32_t) ow0 * s0 - p0; - const int32_t lo = MAX(0, -iw0); - const int32_t hi = MIN(Wb, IW - iw0); + const int32_t Wb = 32 * G * s0 + (KW - 1) * d0; + const int32_t iw0 = (int32_t) ow0 * s0 - p0; + const int32_t lo = MAX(0, -iw0); + const int32_t hi = MIN(Wb, IW - iw0); + const uint32_t x_es = input->type == HTP_TYPE_F16 ? sizeof(__fp16) : sizeof(float); + const HVX_Vector zero = Q6_V_vzero(); for (uint32_t kh = 0; kh < KH; kh++) { const int32_t ih = (int32_t) oh * s1 + (int32_t) kh * d1 - p1; - float * row = stage + (size_t) kh * SR; + uint8_t * row = (uint8_t *) (stage + (size_t) kh * SR); if (ih < 0 || ih >= IH || hi <= lo) { - hvx_splat_f32_u(row, 0.0f, Wb * Cin); + hvx_splat_u(row, zero, Wb * Cin, x_es); dma_queue_push(dmaq, dma_make_data(row, 0), 0, 0, 0, 0); continue; } const dma_addr_t src = input->data + (size_t) n * input->nb[3] + (size_t) ih * input->nb[1] + (size_t) (iw0 + lo) * input->nb[0]; - const size_t size = (size_t) (hi - lo) * Cin * sizeof(float); - dma_queue_push(dmaq, dma_make_data(row + lo * Cin, src), size, size, size, 1); + const size_t size = (size_t) (hi - lo) * Cin * x_es; + dma_queue_push(dmaq, dma_make_data(row + (size_t) lo * Cin * x_es, src), size, size, size, 1); if (lo > 0) { - hvx_splat_f32_u(row, 0.0f, lo * Cin); + hvx_splat_u(row, zero, lo * Cin, x_es); } if (hi < Wb) { - hvx_splat_f32_u(row + hi * Cin, 0.0f, (Wb - hi) * Cin); + hvx_splat_u(row + (size_t) hi * Cin * x_es, zero, (Wb - hi) * Cin, x_es); } } } -static void conv2d_hmx_cwhn_f16(__fp16 * restrict dst, const float * restrict src, uint32_t KH, uint32_t SR, uint32_t n) { +static void conv2d_hmx_cwhn_f16(__fp16 * restrict dst, const float * restrict src, uint32_t KH, uint32_t SR, uint32_t n, bool src_f16) { for (uint32_t kh = 0; kh < KH; kh++) { - hvx_copy_f16_f32_aa((uint8_t *) (dst + (size_t) kh * SR), (const uint8_t *) (src + (size_t) kh * SR), n); + if (src_f16) { + hvx_copy_f16_aa((uint8_t *) (dst + (size_t) kh * SR), (const uint8_t *) (src + (size_t) kh * SR), n); + } else { + hvx_copy_f16_f32_aa((uint8_t *) (dst + (size_t) kh * SR), (const uint8_t *) (src + (size_t) kh * SR), n); + } } } // Stage the segment of col tiles starting at t, returns its number of col tiles static uint32_t conv2d_hmx_issue_seg(const struct htp_ops_context * octx, const struct htp_conv2d_kernel_params * kp, - const struct htp_conv_geom * g, dma_queue * dmaq, float * stage, uint32_t t, uint32_t t1) { + const struct htp_conv_geom * g, dma_queue * dmaq, float * stage, uint32_t t, uint32_t t1, + uint32_t c0, uint32_t cc) { const uint32_t OH = g->OH; const uint32_t n_owt = kp->tiled.n_ow_tiles; const uint32_t row = fastdiv(t, &kp->tiled.div_ow_tiles); @@ -456,8 +608,10 @@ static uint32_t conv2d_hmx_issue_seg(const struct htp_ops_context * octx, const if (kp->flags & HTP_CONV2D_FLAG_CWHN) { conv2d_hmx_stage_cwhn(octx, kp, dmaq, stage, n, oh, owt * 32, G); + } else if (kp->flags & HTP_CONV2D_FLAG_STAGE_PC) { + conv2d_hmx_stage_pc(octx, kp, g, dmaq, stage, n, oh, owt * 32, G, c0, cc); } else { - conv2d_hmx_stage(octx, kp, g, dmaq, stage, n, oh, owt * 32, G); + conv2d_hmx_stage(octx, kp, g, dmaq, stage, n, oh, owt * 32, G, c0, cc); } return G; } @@ -719,8 +873,8 @@ static void conv2d_hmx_wpack_kmajor_thread(const htp_thread_t * th, unsigned int dma_queue * dmaq = th->dma_q; const size_t w_raw_size = (size_t) WK * 64 * sizeof(float); - uint8_t * wraws[2] = { hc->thr_base + (size_t) ith * kp->thr_size, - hc->thr_base + (size_t) ith * kp->thr_size + w_raw_size }; + uint8_t * wraws[2] = { hc->spad_base + (size_t) ith * kp->spad_per_hvx, + hc->spad_base + (size_t) ith * kp->spad_per_hvx + w_raw_size }; HVX_Vector * vin = (HVX_Vector *) (wraws[1] + w_raw_size); HVX_Vector * scratch = vin + 32; HVX_Vector * sink = scratch + 32; @@ -786,78 +940,125 @@ static void conv2d_hmx_pack(const struct htp_conv2d_hmx_context * hc, const htp_ const uint32_t d0 = (uint32_t) hc->g->d0; const uint32_t n_vec = kp->tiled.n_k_tiles * (HMX_FP16_TILE_N_ELMS / 64); - dma_queue * dmaq = th->dma_q; - uint8_t * thr = hc->thr_base + (size_t) ith * kp->thr_size; + const bool cwhn = (kp->flags & HTP_CONV2D_FLAG_CWHN) != 0; + const bool kmajor = (kp->flags & HTP_CONV2D_FLAG_W_KMAJOR) != 0; + const bool src_f16 = octx->src[1]->type == HTP_TYPE_F16; + const uint32_t n_stage = kp->tiled.n_stage; + + struct htp_conv2d_tiled_spad_layout sl; + htp_conv2d_tiled_spad_layout_build(&sl, kp->stage_size, n_stage, kp->tiled.seg_tiles, cwhn, kmajor, kp->tiled.wk_chunk); + + dma_queue * dmaq = th->dma_q; + uint8_t * spad = hc->spad_base + (size_t) ith * kp->spad_per_hvx; float * stages[2] = { - (float *) thr, - (float *) (thr + kp->stage_size), + VTCM_LAYOUT_PTR(float, spad, sl.off_stage[0]), + VTCM_LAYOUT_PTR(float, spad, sl.off_stage[1]), }; - __fp16 * act = hc->act[hc->pack_chunk & 1]; + __fp16 * act = hc->act[hc->pack_chunk & 1]; // CWHN: fp16 stage (+256 bytes of over-read slack), then 32 + 32 vectors for the transpose - const uint32_t n_stage = kp->tiled.n_stage > 1 ? 2 : 1; - __fp16 * stage16 = (__fp16 *) (thr + (size_t) n_stage * kp->stage_size + (size_t) 2 * 32 * kp->tiled.seg_tiles * 32 * sizeof(float)); - HVX_Vector * vin = (HVX_Vector *) ((uint8_t *) stage16 + kp->stage_size / 2 + 256); - HVX_Vector * scratch = vin + 32; + __fp16 * stage16 = VTCM_LAYOUT_PTR_OPTIONAL(__fp16, spad, sl.off_stage16, cwhn); + HVX_Vector * vin = VTCM_LAYOUT_PTR_OPTIONAL(HVX_Vector, spad, sl.off_vin, cwhn); + HVX_Vector * scratch = VTCM_LAYOUT_PTR_OPTIONAL(HVX_Vector, spad, sl.off_scratch, cwhn); const uint32_t gpr = kp->tiled.n_groups == KH ? 1 : KW; + // WHCN stages CC input channels per step. Chunk k range is [c0 * kc, (c0 + cc) * kc), even except for the last chunk. + const uint32_t CC = kp->tiled.cin_chunk; + const uint32_t kc = KH * KW; + + // threads left idle by a small col tile chunk split the channel chunks of each col tile + const struct htp_conv2d_chunk_plan * pp = hc->pack_plan; + const uint32_t n_tt = pp->n_tt; + const uint32_t n_cs = pp->n_cs; + const uint32_t ci = fastdiv(ith, &pp->div_n_tt); + const uint32_t ti = ith - ci * n_tt; + const uint32_t cc0 = ci * pp->cc_q + MIN(ci, pp->cc_r); + const uint32_t cc1 = cc0 + pp->cc_q + (ci < pp->cc_r ? 1 : 0); + const uint32_t cbeg = MIN(Cin, cc0 * CC); + const uint32_t cend = MIN(Cin, cc1 * CC); + uint32_t t0, t1; - const uint32_t cs = conv2d_hmx_chunk_range(hc, hc->pack_chunk, hc->pack_tpt, ith, &t0, &t1); + const uint32_t cs = conv2d_hmx_chunk_range(hc, hc->pack_chunk, pp->tpt, ti, &t0, &t1); struct htp_thread_trace * tr = th->trace; - if (t0 >= t1) { + if (ith >= n_tt * n_cs) { return; } // Reuse output staging after unpack has drained its DMA. - HVX_Vector * gather_tmp = (HVX_Vector *) (thr + (size_t) n_stage * kp->stage_size); - const HVX_Vector offsets = (kp->flags & HTP_CONV2D_FLAG_CWHN) || s0 <= 2 ? Q6_V_vzero() : hvx_vec_gather_offsets_w(s0 * sizeof(float)); + HVX_Vector * gather_tmp = VTCM_LAYOUT_PTR(HVX_Vector, spad, sl.off_ostage[0]); + const HVX_Vector offsets = cwhn || s0 <= 2 ? Q6_V_vzero() : hvx_vec_gather_offsets_w(s0 * sizeof(float)); + // A step stages channels [c, c + CC) of one segment: all channel chunks of a segment, then the next segment uint32_t ng[2] = { 0, 0 }; + uint32_t nc[2] = { 0, 0 }; uint32_t tq = t0; + uint32_t cq = cbeg; for (uint32_t i = 0; i < n_stage && tq < t1; i++) { - ng[i] = conv2d_hmx_issue_seg(octx, kp, hc->g, dmaq, stages[i], tq, t1); - tq += ng[i]; + ng[i] = conv2d_hmx_issue_seg(octx, kp, hc->g, dmaq, stages[i], tq, t1, cq, MIN(CC, cend - cq)); + nc[i] = cq; + cq += CC; + if (cq >= cend) { + cq = cbeg; + tq += ng[i]; + } } uint32_t bi = 0; for (uint32_t t = t0; t < t1;) { const uint32_t G = ng[bi]; + const uint32_t c0 = nc[bi]; + const uint32_t cc = MIN(CC, cend - c0); float * stage = stages[bi]; - for (uint32_t p = 0; p < KH; p++) { + const uint32_t n_dma = (kp->flags & HTP_CONV2D_FLAG_STAGE_PC) ? cc * kp->tiled.kd : KH; + for (uint32_t p = 0; p < n_dma; p++) { dma_queue_pop(dmaq); } htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) t); - if (kp->flags & HTP_CONV2D_FLAG_CWHN) { + if (cwhn) { const uint32_t Wb = 32 * G * s0 + (KW - 1) * d0; - conv2d_hmx_cwhn_f16(stage16, stage, KH, kp->tiled.stage_row, Wb * Cin); + conv2d_hmx_cwhn_f16(stage16, stage, KH, kp->tiled.stage_row, Wb * Cin, src_f16); for (uint32_t g = 0; g < G; g++) { __fp16 * tile = act + (size_t) (t - cs + g) * n_vec * 64; conv2d_hmx_pack_tile_cwhn(tile, stage16 + (size_t) g * 32 * Cin * s0, vin, scratch, kp, gpr, Cin, s0, d0); } } else { + if (src_f16) { + const uint32_t Wb = 32 * G * s0 + (KW - 1) * d0; + conv2d_hmx_expand_rows_f16_to_f32(stage, kp->tiled.stage_row, Wb, cc * KH); + } + const uint32_t k0 = c0 * kc; + const uint32_t nk = cc * kc; + const uint32_t nv = c0 + cc == Cin ? n_vec - k0 / 2 : nk / 2; for (uint32_t g = 0; g < G; g++) { - __fp16 * tile = act + (size_t) (t - cs + g) * n_vec * 64; + __fp16 * tile = act + (size_t) (t - cs + g) * n_vec * 64 + (size_t) (k0 / 2) * 64; const float * pixels = stage + (size_t) g * 32 * s0; if (s0 == 1) { - conv2d_hmx_pack_tile(tile, pixels, kp->tiled.k_size, KW, 1, d0, kp->tiled.stage_row, n_vec, offsets, gather_tmp); + conv2d_hmx_pack_tile(tile, pixels, nk, KW, 1, d0, kp->tiled.stage_row, nv, offsets, gather_tmp); } else if (s0 == 2) { - conv2d_hmx_pack_tile(tile, pixels, kp->tiled.k_size, KW, 2, d0, kp->tiled.stage_row, n_vec, offsets, gather_tmp); + conv2d_hmx_pack_tile(tile, pixels, nk, KW, 2, d0, kp->tiled.stage_row, nv, offsets, gather_tmp); } else { - conv2d_hmx_pack_tile(tile, pixels, kp->tiled.k_size, KW, s0, d0, kp->tiled.stage_row, n_vec, offsets, gather_tmp); + conv2d_hmx_pack_tile(tile, pixels, nk, KW, s0, d0, kp->tiled.stage_row, nv, offsets, gather_tmp); } } } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) t); if (tq < t1) { - ng[bi] = conv2d_hmx_issue_seg(octx, kp, hc->g, dmaq, stage, tq, t1); - tq += ng[bi]; + ng[bi] = conv2d_hmx_issue_seg(octx, kp, hc->g, dmaq, stage, tq, t1, cq, MIN(CC, cend - cq)); + nc[bi] = cq; + cq += CC; + if (cq >= cend) { + cq = cbeg; + tq += ng[bi]; + } + } + if (c0 + cc >= cend) { + t += G; } - t += G; bi = bi + 1 == n_stage ? 0 : bi + 1; } } @@ -873,11 +1074,20 @@ static void conv2d_hmx_unpack(const struct htp_conv2d_hmx_context * hc, const ht const uint32_t n_owt = kp->tiled.n_ow_tiles; const uint32_t OS = kp->tiled.seg_tiles * 32; + const bool cwhn = (kp->flags & HTP_CONV2D_FLAG_CWHN) != 0; + const bool kmajor = (kp->flags & HTP_CONV2D_FLAG_W_KMAJOR) != 0; + const bool dst_f16 = dst->type == HTP_TYPE_F16; + const size_t y_es = dst_f16 ? sizeof(__fp16) : sizeof(float); + const uint32_t n_stage = kp->tiled.n_stage; + + struct htp_conv2d_tiled_spad_layout sl; + htp_conv2d_tiled_spad_layout_build(&sl, kp->stage_size, n_stage, kp->tiled.seg_tiles, cwhn, kmajor, kp->tiled.wk_chunk); + dma_queue * dmaq = th->dma_q; - uint8_t * thr = hc->thr_base + (size_t) ith * kp->thr_size + (size_t) (kp->tiled.n_stage > 1 ? 2 : 1) * kp->stage_size; + uint8_t * spad = hc->spad_base + (size_t) ith * kp->spad_per_hvx; float * ostage[2] = { - (float *) thr, - (float *) (thr + (size_t) 32 * OS * sizeof(float)), + VTCM_LAYOUT_PTR(float, spad, sl.off_ostage[0]), + VTCM_LAYOUT_PTR(float, spad, sl.off_ostage[1]), }; const __fp16 * out = hc->out[hc->unpack_chunk & 1]; @@ -922,10 +1132,13 @@ static void conv2d_hmx_unpack(const struct htp_conv2d_hmx_context * hc, const ht *(HVX_Vector *) (ob + (size_t) (2 * r + 1) * OS + g * 32) = hvx_vec_mul_f32_f32(Q6_V_hi_W(pr), restore); } } + if (dst_f16) { + conv2d_hmx_pack_rows_f32_to_f16(ob, OS, nv, nco); + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) t); - const dma_addr_t ddr = dst->data + (size_t) n * hc->g->y_nb_n + (size_t) oh * dst->nb[1] + (size_t) co0 * hc->g->y_nb_c + (size_t) ow0 * sizeof(float); - dma_queue_push(dmaq, dma_make_data(ddr, ob), hc->g->y_nb_c, (size_t) OS * sizeof(float), (size_t) nv * sizeof(float), nco); + const dma_addr_t ddr = dst->data + (size_t) n * hc->g->y_nb_n + (size_t) oh * dst->nb[1] + (size_t) co0 * hc->g->y_nb_c + (size_t) ow0 * y_es; + dma_queue_push(dmaq, dma_make_data(ddr, ob), hc->g->y_nb_c, (size_t) OS * sizeof(float), (size_t) nv * y_es, nco); n_pushed++; b ^= 1; } @@ -960,20 +1173,20 @@ static void conv2d_hmx_phase_thread(const htp_thread_t * th, unsigned int nth, u } } -static inline uint32_t conv2d_hmx_tpt(const struct htp_conv2d_hmx_context * hc, int32_t c, uint32_t nth) { - if (c < 0) { - return 0; - } - const uint32_t cs = hc->t_base + (uint32_t) c * hc->kp->ct_chunk; - const uint32_t nct = MIN(hc->kp->ct_chunk, hc->t_end - cs); - return (nct + nth - 1) / nth; +static void conv2d_hmx_chunk_plan_init(struct htp_conv2d_chunk_plan * p, uint32_t nct, uint32_t n_cc, uint32_t nth) { + p->tpt = (nct + nth - 1) / nth; + p->n_tt = (nct + p->tpt - 1) / p->tpt; + p->n_cs = MIN(n_cc, nth / p->n_tt); + p->cc_q = n_cc / p->n_cs; + p->cc_r = n_cc - p->cc_q * p->n_cs; + p->div_n_tt = init_fastdiv_values(p->n_tt); } static void conv2d_hmx_run_phase(struct htp_conv2d_hmx_context * hc, int32_t pack, int32_t unpack, uint32_t nth) { hc->pack_chunk = pack; hc->unpack_chunk = unpack; - hc->pack_tpt = conv2d_hmx_tpt(hc, pack, nth); - hc->unpack_tpt = conv2d_hmx_tpt(hc, unpack, nth); + hc->pack_plan = pack >= 0 ? &hc->plan[pack == hc->last_chunk] : NULL; + hc->unpack_tpt = unpack >= 0 ? hc->plan[unpack == hc->last_chunk].tpt : 0; work_queue_run(hc->octx->ctx->hvx_queue, conv2d_hmx_phase_thread, hc, nth); } @@ -993,7 +1206,7 @@ static int conv2d_hmx_tiled(struct htp_ops_context * octx, const struct htp_conv const size_t out_size = (size_t) kp->rt_block * kp->ct_chunk * tile; struct htp_conv2d_vtcm_layout layout; - htp_conv2d_vtcm_layout_build(&layout, kp->rt_block, w_size, act_size, out_size, kp->thr_size, kp->n_hvx); + htp_conv2d_vtcm_layout_build(&layout, kp->rt_block, w_size, act_size, out_size, kp->spad_per_hvx, kp->n_hvx); uint8_t * base = (uint8_t *) octx->ctx->vtcm_base; @@ -1006,19 +1219,30 @@ static int conv2d_hmx_tiled(struct htp_ops_context * octx, const struct htp_conv .w_tiles = VTCM_LAYOUT_PTR(__fp16, base, layout.off_w), .act = { VTCM_LAYOUT_PTR(__fp16, base, layout.off_act[0]), VTCM_LAYOUT_PTR(__fp16, base, layout.off_act[1]) }, .out = { VTCM_LAYOUT_PTR(__fp16, base, layout.off_out[0]), VTCM_LAYOUT_PTR(__fp16, base, layout.off_out[1]) }, - .thr_base = VTCM_LAYOUT_PTR(uint8_t, base, layout.off_thr), + .spad_base = VTCM_LAYOUT_PTR(uint8_t, base, layout.off_spad), .t_base = row_base * kp->tiled.n_ow_tiles, .t_end = (row_base + n_rows) * kp->tiled.n_ow_tiles, }; - const uint32_t nth = kp->n_hvx; - const int32_t n_chunks = (int32_t) ((hc.t_end - hc.t_base + kp->ct_chunk - 1) / kp->ct_chunk); + const uint32_t nth = kp->n_hvx; + const uint32_t total_tiles = hc.t_end - hc.t_base; + const int32_t n_chunks = (int32_t) ((total_tiles + kp->ct_chunk - 1) / kp->ct_chunk); + const uint32_t tail_nct = total_tiles - (uint32_t) (n_chunks - 1) * kp->ct_chunk; + hc.last_chunk = n_chunks - 1; + conv2d_hmx_chunk_plan_init(&hc.plan[0], kp->ct_chunk, kp->tiled.n_cin_chunks, nth); + conv2d_hmx_chunk_plan_init(&hc.plan[1], tail_nct, kp->tiled.n_cin_chunks, nth); struct htp_conv2d_hmx_task task; + const uint32_t wpack_n_ks = (kp->tiled.n_k_tiles * HMX_FP16_TILE_N_COLS + kp->tiled.wk_chunk - 1) / kp->tiled.wk_chunk; + for (uint32_t rt0 = 0; rt0 < kp->n_row_tiles; rt0 += kp->rt_block) { - hc.rt0 = rt0; - hc.n_rt = MIN(kp->rt_block, kp->n_row_tiles - rt0); + hc.rt0 = rt0; + hc.n_rt = MIN(kp->rt_block, kp->n_row_tiles - rt0); + hc.wpack_n_kp = MIN(wpack_n_ks, MAX(1u, nth / hc.n_rt)); + hc.wpack_ks_q = wpack_n_ks / hc.wpack_n_kp; + hc.wpack_ks_r = wpack_n_ks - hc.wpack_ks_q * hc.wpack_n_kp; + hc.wpack_div_n_kp = init_fastdiv_values(hc.wpack_n_kp); work_queue_run(octx->ctx->hvx_queue, (kp->flags & HTP_CONV2D_FLAG_W_KMAJOR) ? conv2d_hmx_wpack_kmajor_thread : conv2d_hmx_wpack_thread, &hc, nth); conv2d_hmx_run_phase(&hc, 0, -1, nth); @@ -1071,7 +1295,7 @@ struct htp_conv2d_win_context { __fp16 * w_tiles; // [rt][tap][cc] weight tiles __fp16 * act[2]; // [cc][b] croutons of a chunk __fp16 * out[2]; // [rt][tile] output tiles of a chunk - uint8_t * thr_base; + uint8_t * spad_base; uint32_t t_base; // device col tile range uint32_t t_end; uint32_t vr0; // device virtual output row range @@ -1082,6 +1306,7 @@ struct htp_conv2d_win_context { int32_t unpack_chunk; uint32_t n_scat; // small Cin: scatters per crouton into zeroed croutons, else 0 uint8_t * live[2]; // per chunk: tiles with an output row to write + struct fastdiv_values div_nth; }; struct htp_conv2d_win_task { @@ -1340,13 +1565,13 @@ static void conv2d_hmx_win_wpack_kmajor(const struct htp_conv2d_win_context * wc dma_queue * dmaq = th->dma_q; const size_t w_raw_size = (size_t) TG * 32 * VLEN; - uint8_t * raws[2] = { wc->thr_base + (size_t) ith * kp->thr_size, - wc->thr_base + (size_t) ith * kp->thr_size + w_raw_size }; + uint8_t * raws[2] = { wc->spad_base + (size_t) ith * kp->spad_per_hvx, + wc->spad_base + (size_t) ith * kp->spad_per_hvx + w_raw_size }; const HVX_Vector zero = Q6_V_vzero(); struct htp_thread_trace * tr = th->trace; - const uint32_t n_tg = (T + TG - 1) / TG; + const uint32_t n_tg = kp->window.w_n_seg; const uint32_t n_units = wc->n_rt * n_cc * n_tg; struct conv2d_win_wpack_kmajor_task tasks[2]; @@ -1517,12 +1742,12 @@ static void conv2d_hmx_win_wpack_rows(const struct htp_conv2d_win_context * wc, const size_t wraw = (size_t) 32 * ((CS * T + kpw - 1) / kpw) * VLEN; dma_queue * dmaq = th->dma_q; - uint8_t * raws[2] = { wc->thr_base + (size_t) ith * kp->thr_size, wc->thr_base + (size_t) ith * kp->thr_size + wraw }; + uint8_t * raws[2] = { wc->spad_base + (size_t) ith * kp->spad_per_hvx, wc->spad_base + (size_t) ith * kp->spad_per_hvx + wraw }; uint8_t * xr = raws[1] + wraw; HVX_Vector * vin = (HVX_Vector *) (xr + wraw); HVX_Vector * scratch = vin + 32; - const uint32_t n_cs = (32 + CS - 1) / CS; + const uint32_t n_cs = kp->window.w_n_seg; const uint32_t n_units = wc->n_rt * kp->window.n_cc * n_cs; struct htp_thread_trace * tr = th->trace; @@ -1571,8 +1796,10 @@ static uint32_t conv2d_hmx_win_stage(const struct htp_conv2d_win_context * wc, d const uint32_t IHS = kp->window.ihs; const uint32_t p0 = octx->op_params[2]; const uint32_t p1 = octx->op_params[3]; - const uint32_t span = kp->window.seg_b * 32; - const bool cwhn = (kp->flags & HTP_CONV2D_FLAG_CWHN) != 0; + const uint32_t span = kp->window.seg_b * 32; + const bool cwhn = (kp->flags & HTP_CONV2D_FLAG_CWHN) != 0; + const uint32_t x_es = input->type == HTP_TYPE_F16 ? sizeof(__fp16) : sizeof(float); + const HVX_Vector zero = Q6_V_vzero(); // rows of one image are contiguous when there is no column padding const bool rows_contig = p0 == 0 && input->nb[1] == (size_t) IW * input->nb[0]; @@ -1590,10 +1817,10 @@ static uint32_t conv2d_hmx_win_stage(const struct htp_conv2d_win_context * wc, d if (n >= N || ih < 0 || ih >= (int32_t) IH) { const uint32_t len = end - u; if (cwhn) { - hvx_splat_f32_u(stage + (size_t) (u - ua) * Cin, 0.0f, len * Cin); + hvx_splat_u((uint8_t *) stage + (size_t) (u - ua) * Cin * x_es, zero, len * Cin, x_es); } else { for (uint32_t c = 0; c < Cin; c++) { - hvx_splat_f32_u(stage + (size_t) c * span + (u - ua), 0.0f, len); + hvx_splat_u((uint8_t *) (stage + (size_t) c * span) + (size_t) (u - ua) * x_es, zero, len, x_es); } } u = end; @@ -1615,10 +1842,10 @@ static uint32_t conv2d_hmx_win_stage(const struct htp_conv2d_win_context * wc, d if (a > col) { const uint32_t z = MIN(a, col + len) - col; if (cwhn) { - hvx_splat_f32_u(stage + (size_t) (u - ua) * Cin, 0.0f, z * Cin); + hvx_splat_u((uint8_t *) stage + (size_t) (u - ua) * Cin * x_es, zero, z * Cin, x_es); } else { for (uint32_t c = 0; c < Cin; c++) { - hvx_splat_f32_u(stage + (size_t) c * span + (u - ua), 0.0f, z); + hvx_splat_u((uint8_t *) (stage + (size_t) c * span) + (size_t) (u - ua) * x_es, zero, z, x_es); } } } @@ -1626,10 +1853,10 @@ static uint32_t conv2d_hmx_win_stage(const struct htp_conv2d_win_context * wc, d const uint32_t z0 = MAX(a, b); const uint32_t z = col + len - z0; if (cwhn) { - hvx_splat_f32_u(stage + (size_t) (u - ua + z0 - col) * Cin, 0.0f, z * Cin); + hvx_splat_u((uint8_t *) stage + (size_t) (u - ua + z0 - col) * Cin * x_es, zero, z * Cin, x_es); } else { for (uint32_t c = 0; c < Cin; c++) { - hvx_splat_f32_u(stage + (size_t) c * span + (u - ua + z0 - col), 0.0f, z); + hvx_splat_u((uint8_t *) (stage + (size_t) c * span) + (size_t) (u - ua + z0 - col) * x_es, zero, z, x_es); } } } @@ -1637,11 +1864,11 @@ static uint32_t conv2d_hmx_win_stage(const struct htp_conv2d_win_context * wc, d const dma_addr_t src = input->data + (size_t) n * input->nb[3] + (size_t) ih * input->nb[1] + (size_t) (a - p0) * input->nb[0]; const uint32_t off = u - ua + (a - col); if (cwhn) { - const size_t sz = (size_t) (b - a) * Cin * sizeof(float); - dma_queue_push(dmaq, dma_make_data(stage + (size_t) off * Cin, src), sz, sz, sz, 1); + const size_t sz = (size_t) (b - a) * Cin * x_es; + dma_queue_push(dmaq, dma_make_data((uint8_t *) stage + (size_t) off * Cin * x_es, src), sz, sz, sz, 1); } else { - dma_queue_push(dmaq, dma_make_data(stage + off, src), (size_t) span * sizeof(float), input->nb[2], - (size_t) (b - a) * sizeof(float), Cin); + dma_queue_push(dmaq, dma_make_data((uint8_t *) stage + (size_t) off * x_es, src), (size_t) span * sizeof(float), input->nb[2], + (size_t) (b - a) * x_es, Cin); } nd++; } @@ -1659,7 +1886,7 @@ static inline float * conv2d_hmx_win_fold_raw(float * stage) { static inline uint32_t conv2d_hmx_win_fold_rplane(const struct htp_conv2d_win_context * wc) { const uint32_t IW = wc->octx->src[1]->ne[0]; - return ((wc->kp->window.seg_b * 32 + wc->kp->window.sr - 1) / wc->kp->window.sr + 1) * IW; + return (fastdiv(wc->kp->window.seg_b * 32 + wc->kp->window.sr - 1, &wc->kp->window.div_sr) + 1) * IW; } // DMA the raw input rows of [ua, ub), returns the number of DMAs pushed @@ -1690,15 +1917,16 @@ static uint32_t conv2d_hmx_win_stage_fold(const struct htp_conv2d_win_context * continue; } // rows of one image are contiguous in DDR - const uint32_t nr = cont ? MIN(vr_b - vr, (uint32_t) (IH - ih)) : 1; - const dma_addr_t src = input->data + (size_t) n * input->nb[3] + (size_t) ih * input->nb[1]; + const uint32_t nr = cont ? MIN(vr_b - vr, (uint32_t) (IH - ih)) : 1; + const size_t x_es = input->type == HTP_TYPE_F16 ? sizeof(__fp16) : sizeof(float); + const dma_addr_t src = input->data + (size_t) n * input->nb[3] + (size_t) ih * input->nb[1]; if (kp->flags & HTP_CONV2D_FLAG_CWHN) { // raw[vr - vr_a][iw][c] - const size_t sz = (size_t) nr * IW * Cin * sizeof(float); - dma_queue_push(dmaq, dma_make_data(raw + (size_t) (vr - vr_a) * IW * Cin, src), sz, sz, sz, 1); + const size_t sz = (size_t) nr * IW * Cin * x_es; + dma_queue_push(dmaq, dma_make_data((uint8_t *) raw + (size_t) (vr - vr_a) * IW * Cin * x_es, src), sz, sz, sz, 1); } else { - dma_queue_push(dmaq, dma_make_data(raw + (size_t) (vr - vr_a) * IW, src), (size_t) RP * sizeof(float), input->nb[2], - (size_t) nr * IW * sizeof(float), Cin); + dma_queue_push(dmaq, dma_make_data((uint8_t *) raw + (size_t) (vr - vr_a) * IW * x_es, src), (size_t) RP * sizeof(float), input->nb[2], + (size_t) nr * IW * x_es, Cin); } nd++; vr += nr; @@ -2003,13 +2231,19 @@ static void conv2d_hmx_win_pack(const struct htp_conv2d_win_context * wc, const uint32_t ts; const uint32_t nt = conv2d_hmx_win_chunk_tiles(wc, wc->pack_chunk, &ts); const uint32_t ncb = MIN(kp->window.n_bc, nt + (kp->window.max_off >> 5) + 1); - const uint32_t bpt = (ncb + nth - 1) / nth; + const uint32_t bpt = fastdiv(ncb + nth - 1, &wc->div_nth); const uint32_t b0 = MIN(ith * bpt, ncb); const uint32_t b1 = MIN(b0 + bpt, ncb); + struct htp_conv2d_win_spad_layout sl; + htp_conv2d_win_spad_layout_build(&sl, kp->stage_size, kp->window.seg_t, 0); + dma_queue * dmaq = th->dma_q; - uint8_t * thr = wc->thr_base + (size_t) ith * kp->thr_size; - float * stages[2] = { (float *) thr, (float *) (thr + kp->stage_size) }; + uint8_t * spad = wc->spad_base + (size_t) ith * kp->spad_per_hvx; + float * stages[2] = { + VTCM_LAYOUT_PTR(float, spad, sl.off_stage[0]), + VTCM_LAYOUT_PTR(float, spad, sl.off_stage[1]), + }; __fp16 * act = wc->act[wc->pack_chunk & 1]; uint32_t (*stage_fn)(const struct htp_conv2d_win_context *, dma_queue *, float *, uint32_t, uint32_t) = @@ -2039,6 +2273,27 @@ static void conv2d_hmx_win_pack(const struct htp_conv2d_win_context * wc, const } htp_trace_event_start(tr, HTP_TRACE_EVT_HVX_A_PREP, (uint16_t) b); + if (wc->octx->src[1]->type == HTP_TYPE_F16) { + const uint32_t Cin = wc->octx->src[1]->ne[2]; + const bool cwhn = (kp->flags & HTP_CONV2D_FLAG_CWHN) != 0; + if (kp->window.fold) { + const uint32_t ua = (ts + b) * 32; + const uint32_t ub = (ts + b + nb) * 32; + const uint32_t vr_a = fastdiv(ua, &kp->window.div_sr); + const uint32_t vr_b = fastdiv(ub - 1, &kp->window.div_sr) + 1; + const uint32_t IW = wc->octx->src[1]->ne[0]; + float * raw = conv2d_hmx_win_fold_raw(stages[si]); + if (cwhn) { + conv2d_hmx_expand_f16_to_f32_inplace(raw, (vr_b - vr_a) * IW * Cin); + } else { + conv2d_hmx_expand_rows_f16_to_f32(raw, conv2d_hmx_win_fold_rplane(wc), (vr_b - vr_a) * IW, Cin); + } + } else if (cwhn) { + conv2d_hmx_expand_f16_to_f32_inplace(stages[si], nb * 32 * Cin); + } else { + conv2d_hmx_expand_rows_f16_to_f32(stages[si], kp->window.seg_b * 32, nb * 32, Cin); + } + } if (kp->window.fold && (kp->flags & HTP_CONV2D_FLAG_CWHN)) { conv2d_hmx_win_croutons_fold_cwhn(wc, stages[si], act, b, nb, (ts + b) * 32); } else if (kp->window.fold) { @@ -2069,13 +2324,16 @@ static void conv2d_hmx_win_unpack(const struct htp_conv2d_win_context * wc, cons uint32_t ts; const uint32_t nt = conv2d_hmx_win_chunk_tiles(wc, wc->unpack_chunk, &ts); - const uint32_t tpt = (nt + nth - 1) / nth; + const uint32_t tpt = fastdiv(nt + nth - 1, &wc->div_nth); const uint32_t i0 = MIN(ith * tpt, nt); const uint32_t i1 = MIN(i0 + tpt, nt); + struct htp_conv2d_win_spad_layout sl; + htp_conv2d_win_spad_layout_build(&sl, kp->stage_size, kp->window.seg_t, 0); + dma_queue * dmaq = th->dma_q; - uint8_t * thr = wc->thr_base + (size_t) ith * kp->thr_size + 2 * (size_t) kp->stage_size; - float * obuf = (float *) thr; + uint8_t * spad = wc->spad_base + (size_t) ith * kp->spad_per_hvx; + float * obuf = VTCM_LAYOUT_PTR(float, spad, sl.off_obuf); __fp16 * out = wc->out[wc->unpack_chunk & 1]; struct htp_thread_trace * tr = th->trace; @@ -2084,7 +2342,9 @@ static void conv2d_hmx_win_unpack(const struct htp_conv2d_win_context * wc, cons uint32_t nd[HTP_CONV2D_WIN_OBUF] = { 0 }; uint32_t bi = 0; - const bool rows_contig = SR == OW && dst->nb[1] == OW * sizeof(float); + const bool dst_f16 = dst->type == HTP_TYPE_F16; + const size_t y_es = dst_f16 ? sizeof(__fp16) : sizeof(float); + const bool rows_contig = SR == OW && dst->nb[1] == OW * y_es; for (uint32_t i = i0; i < i1; i += ST) { const uint32_t ni = MIN(ST, i1 - i); @@ -2123,6 +2383,9 @@ static void conv2d_hmx_win_unpack(const struct htp_conv2d_win_context * wc, cons o[(2 * k + 1) * (OS / 32)] = hvx_vec_mul_f32_f32(Q6_V_hi_W(pr), restore); } } + if (dst_f16) { + conv2d_hmx_pack_rows_f32_to_f16(ob, OS, ni * 32, nco); + } htp_trace_event_stop(tr, HTP_TRACE_EVT_HVX_O_PROC, (uint16_t) i); // write the valid part of each virtual row in [q_lo, q_hi) @@ -2140,7 +2403,7 @@ static void conv2d_hmx_win_unpack(const struct htp_conv2d_win_context * wc, cons if (b <= a) { continue; } - const dma_addr_t ddr = dst->data + (size_t) n * dst->nb[3] + (size_t) oh * dst->nb[1] + (size_t) co0 * dst->nb[2] + (size_t) a * sizeof(float); + const dma_addr_t ddr = dst->data + (size_t) n * dst->nb[3] + (size_t) oh * dst->nb[1] + (size_t) co0 * dst->nb[2] + (size_t) a * y_es; // no gap between rows: extend over the following rows of this image if (rows_contig) { @@ -2151,8 +2414,8 @@ static void conv2d_hmx_win_unpack(const struct htp_conv2d_win_context * wc, cons b = MIN(q_hi - base, (r - 1) * SR + OW); vr += r - 1; } - dma_queue_push(dmaq, dma_make_data(ddr, ob + (base + a - q_lo)), dst->nb[2], (size_t) OS * sizeof(float), - (size_t) (b - a) * sizeof(float), nco); + dma_queue_push(dmaq, dma_make_data(ddr, (uint8_t *) ob + (size_t) (base + a - q_lo) * y_es), dst->nb[2], (size_t) OS * sizeof(float), + (size_t) (b - a) * y_es, nco); nd[bi]++; } bi = bi + 1 == HTP_CONV2D_WIN_OBUF ? 0 : bi + 1; @@ -2192,7 +2455,7 @@ static void conv2d_hmx_win_zero_thread(const htp_thread_t * th, unsigned int nth const struct htp_conv2d_win_context * wc = (const struct htp_conv2d_win_context *) data; const size_t n = 2 * wc->layout.act_size / sizeof(float); - const size_t per = hex_round_up((n + nth - 1) / nth, VLEN_FP32); + const size_t per = hex_round_up(fastdiv((uint32_t) (n + nth - 1), &wc->div_nth), VLEN_FP32); const size_t i0 = MIN((size_t) ith * per, n); const size_t i1 = MIN(i0 + per, n); @@ -2265,7 +2528,7 @@ static int conv2d_hmx_win(struct htp_ops_context * octx, const struct htp_conv2d const size_t out_size = (size_t) kp->rt_block * kp->ct_chunk * tile; struct htp_conv2d_vtcm_layout layout; - htp_conv2d_vtcm_layout_build(&layout, kp->rt_block, w_size, act_size, out_size, kp->thr_size, kp->n_hvx); + htp_conv2d_vtcm_layout_build(&layout, kp->rt_block, w_size, act_size, out_size, kp->spad_per_hvx, kp->n_hvx); uint8_t * base = (uint8_t *) octx->ctx->vtcm_base; @@ -2277,11 +2540,12 @@ static int conv2d_hmx_win(struct htp_ops_context * octx, const struct htp_conv2d .w_tiles = VTCM_LAYOUT_PTR(__fp16, base, layout.off_w), .act = { VTCM_LAYOUT_PTR(__fp16, base, layout.off_act[0]), VTCM_LAYOUT_PTR(__fp16, base, layout.off_act[1]) }, .out = { VTCM_LAYOUT_PTR(__fp16, base, layout.off_out[0]), VTCM_LAYOUT_PTR(__fp16, base, layout.off_out[1]) }, - .thr_base = VTCM_LAYOUT_PTR(uint8_t, base, layout.off_thr), + .spad_base = VTCM_LAYOUT_PTR(uint8_t, base, layout.off_spad), .t_base = (vr0 * SR) / 32, .t_end = ((vr1 - 1) * SR + OW + 31) / 32, .vr0 = vr0, .vr1 = vr1, + .div_nth = init_fastdiv_values(kp->n_hvx), }; // small Cin: croutons are built by scattering the staged values into zeroed croutons diff --git a/ggml/src/ggml-hexagon/htp/conv2d-ops.h b/ggml/src/ggml-hexagon/htp/conv2d-ops.h index 9e66c5471ba2..7071578d012a 100644 --- a/ggml/src/ggml-hexagon/htp/conv2d-ops.h +++ b/ggml/src/ggml-hexagon/htp/conv2d-ops.h @@ -15,12 +15,15 @@ enum htp_conv2d_kernel_type { HTP_CONV2D_KERNEL_HMX_TILED, // tiled implicit-GEMM convolution on HMX }; -// HMX_WINDOW output staging buffers per thread +// HMX_WINDOW output staging buffers per HVX #define HTP_CONV2D_WIN_OBUF 2 // HMX scales of one row tile at the start of VTCM: 32 (scale, bias) fp16 pairs and 128 zero bytes #define HTP_CONV2D_HMX_SCALES_SIZE 256 +// Max bytes of one staged input buffer (the DMA descriptor row/stride limits are far below VTCM size) +#define HTP_CONV2D_STAGE_MAX ((size_t) 128 * 1024) + struct htp_conv2d_tiled_params { uint32_t w_kstride; uint32_t k_size; @@ -29,14 +32,18 @@ struct htp_conv2d_tiled_params { uint32_t n_groups; uint32_t n_k_tiles; uint32_t n_ow_tiles; - uint32_t seg_tiles; uint32_t stage_row; - uint32_t n_stage; + uint16_t seg_tiles; + uint16_t n_stage; + uint32_t cin_chunk; uint32_t wk_chunk; + uint32_t n_cin_chunks; + uint32_t kd; struct fastdiv_values div_ow_tiles; struct fastdiv_values div_oh; struct fastdiv_values div_khr; // kernel ne[1], unfolds conv_3d kh = kd * KHr + kh' struct fastdiv_values div_ohr; // dst ne[1], unfolds conv_3d oh = od * OHr + oh' + struct fastdiv_values div_d1; // dilation along H }; struct htp_conv2d_window_params { @@ -47,9 +54,10 @@ struct htp_conv2d_window_params { uint32_t ihs; uint32_t max_off; uint32_t n_bc; - uint32_t seg_b; - uint32_t seg_t; - uint32_t w_cs; + uint16_t seg_b; + uint16_t seg_t; + uint16_t w_cs; + uint16_t w_n_seg; // n_tg (kmajor) or n_cs (w_rows) struct fastdiv_values div_sr; struct fastdiv_values div_ihs; struct fastdiv_values div_kw; @@ -61,6 +69,7 @@ struct htp_conv2d_window_params { enum htp_conv2d_flags { HTP_CONV2D_FLAG_CWHN = (1u << 0), HTP_CONV2D_FLAG_W_KMAJOR = (1u << 1), + HTP_CONV2D_FLAG_STAGE_PC = (1u << 2), }; struct htp_conv2d_kernel_params { @@ -73,7 +82,7 @@ struct htp_conv2d_kernel_params { uint32_t ct_chunk; uint32_t rt_block; uint32_t stage_size; - uint32_t thr_size; + uint32_t spad_per_hvx; uint32_t vtcm_size; union { @@ -94,7 +103,7 @@ struct htp_conv2d_vtcm_layout { size_t off_w; size_t off_act[2]; size_t off_out[2]; - size_t off_thr; + size_t off_spad; size_t act_size; }; @@ -105,7 +114,7 @@ static inline void htp_conv2d_vtcm_layout_build( size_t w_size, size_t act_size, size_t out_size, - size_t thr_size, + size_t spad_per_hvx, uint32_t n_hvx ) { const size_t sc = hex_round_up((size_t) rt_block * HTP_CONV2D_HMX_SCALES_SIZE, 2048); @@ -116,9 +125,68 @@ static inline void htp_conv2d_vtcm_layout_build( VTCM_LAYOUT_ALLOC(off, off_act[1], act_size); VTCM_LAYOUT_ALLOC(off, off_out[0], out_size); VTCM_LAYOUT_ALLOC(off, off_out[1], out_size); - VTCM_LAYOUT_ALLOC(off, off_thr, (size_t) n_hvx * thr_size); + VTCM_LAYOUT_ALLOC(off, off_spad, (size_t) n_hvx * spad_per_hvx); L->act_size = act_size; L->total_bytes = off; } +struct htp_conv2d_tiled_spad_layout { + size_t total_bytes; + size_t off_stage[2]; + size_t off_ostage[2]; + size_t off_stage16; + size_t off_vin; + size_t off_scratch; + size_t stages_bytes; + size_t wpack_bytes; +}; + +static inline void htp_conv2d_tiled_spad_layout_build( + struct htp_conv2d_tiled_spad_layout * L, + size_t stage_size, + uint32_t n_stage, + uint32_t seg_tiles, + bool cwhn, + bool kmajor, + uint32_t wk_chunk +) { + const size_t ostage_half = (size_t) 32 * seg_tiles * 32 * sizeof(float); + size_t off = 0; + VTCM_LAYOUT_ALLOC(off, off_stage[0], stage_size); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_stage[1], stage_size, n_stage > 1); + VTCM_LAYOUT_ALLOC(off, off_ostage[0], ostage_half); + VTCM_LAYOUT_ALLOC(off, off_ostage[1], ostage_half); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_stage16, stage_size / 2 + 256, cwhn); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_vin, 32 * 128, cwhn); + VTCM_LAYOUT_ALLOC_OPTIONAL(off, off_scratch, 32 * 128, cwhn); + L->stages_bytes = off; + + L->wpack_bytes = kmajor + ? 2 * (size_t) wk_chunk * 64 * sizeof(float) + 96 * 128 + : 2 * (size_t) 32 * wk_chunk * (sizeof(float) + sizeof(uint16_t)); + L->total_bytes = hex_round_up(MAX(L->stages_bytes, L->wpack_bytes), 2048); +} + +struct htp_conv2d_win_spad_layout { + size_t total_bytes; + size_t off_stage[2]; + size_t off_obuf; + size_t stages_bytes; +}; + +static inline void htp_conv2d_win_spad_layout_build( + struct htp_conv2d_win_spad_layout * L, + size_t stage_size, + uint32_t seg_t, + size_t wscr_bytes +) { + const size_t obuf_bytes = (size_t) HTP_CONV2D_WIN_OBUF * 32 * seg_t * 32 * sizeof(float); + size_t off = 0; + VTCM_LAYOUT_ALLOC(off, off_stage[0], stage_size); + VTCM_LAYOUT_ALLOC(off, off_stage[1], stage_size); + VTCM_LAYOUT_ALLOC(off, off_obuf, obuf_bytes); + L->stages_bytes = off; + L->total_bytes = hex_round_up(MAX(L->stages_bytes, wscr_bytes), 2048); +} + #endif // HTP_CONV2D_OPS_H From d6e988c834e9aefecb6ded09496f855b1f6c684c Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Thu, 3 Dec 2026 21:52:44 +0200 Subject: [PATCH 380/401] ggml : bump version to 1.2.0 (ggml/1714) * ggml : bump version to 1.2.0 * authors : update --- ggml/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ggml/CMakeLists.txt b/ggml/CMakeLists.txt index 8d8be6517c06..ff567c020e41 100644 --- a/ggml/CMakeLists.txt +++ b/ggml/CMakeLists.txt @@ -4,8 +4,8 @@ project("ggml" C CXX ASM) ### GGML Version set(GGML_VERSION_MAJOR 1) -set(GGML_VERSION_MINOR 1) -set(GGML_VERSION_PATCH 1) +set(GGML_VERSION_MINOR 2) +set(GGML_VERSION_PATCH 0) set(GGML_VERSION_BASE "${GGML_VERSION_MAJOR}.${GGML_VERSION_MINOR}.${GGML_VERSION_PATCH}") list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/") From dd6b0fadf77357ac8ddd51b597ae72322e8237b1 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Fri, 4 Dec 2026 08:57:49 +0200 Subject: [PATCH 381/401] sync : ggml [no ci] --- scripts/sync-ggml.last | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/sync-ggml.last b/scripts/sync-ggml.last index 7ab1de63728e..2ddc6bef1654 100644 --- a/scripts/sync-ggml.last +++ b/scripts/sync-ggml.last @@ -1 +1 @@ -bb877c0c51f38c52ee2d5e41d58e3d0c20f3fed4 +4b326040f9303c302abf1ab9703261be2286b167 From 1579b02545274244eb159d204218d8dfab37baf0 Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Fri, 4 Dec 2026 09:17:21 +0200 Subject: [PATCH 382/401] llama.cpp : bump version to 1.1.1 (#33672) * llama.cpp : bump version to 1.1.1 * authors : update --- AUTHORS | 51 +++++++++++++++++++++++++++++++++++++++++++++++++- CMakeLists.txt | 2 +- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/AUTHORS b/AUTHORS index be9ff78cce4b..730ee268d7f4 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,4 +1,4 @@ -# date: Wed Nov 25 16:07:40 EET 2026 +# date: Fri Dec 4 09:04:43 EET 2026 # this file is auto-generated by scripts/gen-authors.sh Нияз Гарифзянов <112617865+garrnizon@users.noreply.github.com> @@ -83,6 +83,7 @@ AgoraPete agray3 Agustín Mista Ahmad Tameem <113388789+Tameem-10xE@users.noreply.github.com> +Ahmed Mohammed Ahmet Zeer ai-fonsi aic0d3r <168572732+aic0d3r@users.noreply.github.com> @@ -102,8 +103,10 @@ Al Mochkin <14274697+amochkin@users.noreply.github.com> Alan Gray Alan Tseng Alan Tseng +Alan Zhai Alawode Oluwandabira Albert Jin +Albert Lie 이영덕 Alberto <57916483+albbus-stack@users.noreply.github.com> Alberto Cabrera Pérez <1478977+Alcpz@users.noreply.github.com> Alberto Cabrera Pérez @@ -141,6 +144,7 @@ Alex-JP-93 alex-spacemit Alexander Batischev Alexander Heisler <126129661+heislera763@users.noreply.github.com> +Alexander Urmuzov Alexey Dubrov Alexey Kopytko Alexey Parfenov @@ -213,6 +217,7 @@ Ankur Verma <31362771+ankurvdev@users.noreply.github.com> anon998 <131767832+anon998@users.noreply.github.com> Anri Lombard Anthony Maltsev <77708730+anthonymaltsev@users.noreply.github.com> +Anthony N Anthony Umfer Anthony Van de Gejuchte Anthony Wang @@ -270,6 +275,7 @@ AustinMroz AUTOMATIC1111 <16777216c@gmail.com> automaticcat AWA <15575202581@163.com> +AWA awatuna <23447591+awatuna@users.noreply.github.com> Awss b4b4o @@ -440,6 +446,7 @@ cocktailpeanut <121128867+cocktailpeanut@users.noreply.github.com> codemonkey <441345965@qq.com> codezjx coezbek +Cokodayo <78474654+CaptainJack2491@users.noreply.github.com> comex compilade <113953597+compilade@users.noreply.github.com> compilade @@ -463,6 +470,7 @@ crsawyer <7572190+crsawyer@users.noreply.github.com> Csaba Kecskemeti Cuong Trinh Manh cwriter +cyxu0401 <162444998+cyxu0401@users.noreply.github.com> daboe01 daghanerdonmez <44506702+daghanerdonmez@users.noreply.github.com> Damian Stewart @@ -625,6 +633,7 @@ eric8607242 Erik Garrison Erik Scholz Erik Winter <93544977+ewintr@users.noreply.github.com> +ErsongWang <158176536+ErsongWang@users.noreply.github.com> Ervin Áron Tasnádi Esko Toivonen Ethan Guo @@ -673,6 +682,7 @@ fj-y-saito <85871716+fj-y-saito@users.noreply.github.com> FK fl0rianr <226492742+fl0rianr@users.noreply.github.com> fl0rianr +FlagZhao Florent BENOIT Florian Badie Foad Abo Dahood <32059146+masterFoad@users.noreply.github.com> @@ -681,6 +691,7 @@ forforever73 <63285796+forforever73@users.noreply.github.com> Foul-Tarnished <107711110+Foul-Tarnished@users.noreply.github.com> fox5611 <66219952+fox5611@users.noreply.github.com> Francisco Herrera +Francisco Javier Francisco Melo <43780565+francis2tm@users.noreply.github.com> Francois Dugast François-Xavier Gsell @@ -704,6 +715,7 @@ fzowl <160063452+fzowl@users.noreply.github.com> g2mt <166577174+g2mt@users.noreply.github.com> Gabe Goodhart Gabe Goodhart +Gabor Nagy Gabriel Larson <55459720+gabriellarson@users.noreply.github.com> Gadflyii <34758915+Gadflyii@users.noreply.github.com> Gaetan Bisson @@ -722,6 +734,7 @@ Geo Maciolek George <35490284+noctrex@users.noreply.github.com> George Burton <8233643+gecBurton@users.noreply.github.com> Georgi Gerganov +Geramy Loveless Geramy Loveless Gerard Guillemas Martos Gerard Martinez @@ -830,6 +843,7 @@ Holger Voormann homeofe <154892989+homeofe@users.noreply.github.com> HonestQiao Hong Bo PENG +Hongbo Wen <157263272+archidoge0@users.noreply.github.com> hongbo.mo <352280764@qq.com> HongHuang Hongqiang Wang <66336067+wanghqc@users.noreply.github.com> @@ -945,6 +959,7 @@ Jannis Schönleber Jared Tweed Jared Van Bortel Jared Van Bortel +jaredmeaux <132780082+jaredmeaux@users.noreply.github.com> Jaromír Hradílek Jasmine-tim <403568753@qq.com> Jason C.H @@ -1105,6 +1120,7 @@ Kangjia Gao <145212963+kkkzbh@users.noreply.github.com> Kante Yin karan <67942227+dheepakkaran@users.noreply.github.com> karavayev <192749314+karavayev@users.noreply.github.com> +Karlis <20698362+xojy@users.noreply.github.com> Karol Kontny <82021046+kkontny@users.noreply.github.com> Karsten Weiss Karthick @@ -1129,6 +1145,7 @@ Keiichi Tabata Keke Han Kenvix ⭐ Kerfuffle <44031344+KerfuffleV2@users.noreply.github.com> +Keroweir <79356629+luoji12103@users.noreply.github.com> Kevin Gibbons Kevin Hannon Kevin Hopper <93635715+kh0pper@users.noreply.github.com> @@ -1249,9 +1266,12 @@ LostRuins <39025047+LostRuins@users.noreply.github.com> LostRuins Concedo <39025047+LostRuins@users.noreply.github.com> lovedheart <6277001+lovedheart@users.noreply.github.com> ltoniazzi <61414566+ltoniazzi@users.noreply.github.com> +Luc Pommeret <135142064+l-pommeret@users.noreply.github.com> Luca Stefani +Lucas Matheson Lucas Moura Belo Luciano +Lucius <37386791+luciusacarr@users.noreply.github.com> lucy <154630366+lucyknada@users.noreply.github.com> Ludovic Henry Ludovic Henry @@ -1304,11 +1324,13 @@ Marcus Dunn <51931484+MarcusDunn@users.noreply.github.com> Marcus Tillmanns Marek Hradil jr. Marian Cepok +Marin Radic Mario <191101255+wariuccio@users.noreply.github.com> Mario Limonciello Mario Limonciello Marius Gerdes <141485318+mglambda@users.noreply.github.com> Mariusz Woloszyn +Mark Cockram Mark Fairbairn Mark Todorovich Mark Zhuang @@ -1336,6 +1358,7 @@ Mason Milburn MasterYi1024 <39848311+MasterYi1024@users.noreply.github.com> Maternion <98753158+maternion@users.noreply.github.com> Mateusz Charytoniuk +Matheus Britto <55333133+matheusbrittod3v@users.noreply.github.com> Matheus C. França Matheus Gabriel Alves Silva Mathieu Baudier @@ -1374,6 +1397,7 @@ Maxim Evtush <154841002+maximevtush@users.noreply.github.com> Maxime <672982+maximegmd@users.noreply.github.com> Maximilian Werk Maximilian Winter +maxipesfix mdrokz Me42019 meatposes @@ -1407,12 +1431,14 @@ Michael Paulauski Michael Podvitskiy Michael Potter Michael Taylor <162068037+mctylr-gh@users.noreply.github.com> +Michaël Tremblay <13114338+Tichael@users.noreply.github.com> Michael Wand michaeltrabalka-tech Michał Moskal Michał Piszczek Michał Tuszyński Michelle Tan <41475767+MichelleTanPY@users.noreply.github.com> +MichelRosselli <71264400+MichelRosselli@users.noreply.github.com> Mickael Desgranges midagedev <139564968+midagedev@users.noreply.github.com> midnight @@ -1459,9 +1485,11 @@ MuoDoo <36472129+MuoDoo@users.noreply.github.com> Murilo Santana Musab Gultekin musoles <135031143+musoles@users.noreply.github.com> +Mustafa Camurcu mzcu nachobh Naco Siren +Nakul Lagwal Nam D. Tran <42194884+namtranase@users.noreply.github.com> nanahi <130121847+na-na-hi@users.noreply.github.com> Nandan Vallamdasu @@ -1477,6 +1505,7 @@ neha-ha <137219201+neha-ha@users.noreply.github.com> Neo Zhang <14088817+arthw@users.noreply.github.com> Neo Zhang Neo Zhang Jianyu +neoli Neuman Vong NeverLucky <92274250+nvrxq@users.noreply.github.com> Nexes the Elder <124105151+Nexesenex@users.noreply.github.com> @@ -1511,6 +1540,7 @@ Nigel Jones Nik Bogatyrev <50734723+notforu777@users.noreply.github.com> Nikhil Jain Nikhil Sharma <150424968+nikhilfujitsu@users.noreply.github.com> +Nikita Belokopytov Nikita Gordeev Nikita Sarychev <42014488+sARY77@users.noreply.github.com> Niklas Korz @@ -1574,6 +1604,7 @@ Patrice Ferlet Patrick Buckley Patrick Hoffmann Patrick Peng +patricksamuelevans <66663476+patricksamuelevans@users.noreply.github.com> Patryk Kaminski Paul Dubs Paul Flynn @@ -1612,6 +1643,7 @@ Piero Evangelista Pierre Alexandre SCHEMBRI Pierrick Hymbert Pieter Ouwerkerk +Pig with dreams <114994886+PigHaveDreamS@users.noreply.github.com> PikaPikachu Piotr Piotr Jasiukajtis @@ -1640,6 +1672,7 @@ Pranav Dhinakar Pranav Dhinakar Pranav Uttarkar <122235768+PranavUttarkar@users.noreply.github.com> Pranesh Gonegandla +PRANESH S <150977208+Pranesh-2005@users.noreply.github.com> Prashant Vithule <119530321+Vithulep@users.noreply.github.com> pratiknarola-t Pratyush Kumar @@ -1740,6 +1773,7 @@ Riley Stewart rimoliga <53384203+rimoliga@users.noreply.github.com> Rinne Rinne +risingpresage <37319157+risingpresage@users.noreply.github.com> Rithik Sharma RJ Adriaansen rmatif <66360289+rmatif@users.noreply.github.com> @@ -1774,6 +1808,7 @@ Roni Ronny Brendel Ronny Brendel Ronsor +Rootodus <120185711+Rootodus@users.noreply.github.com> Roshan Kumar <52444089+roshankumarg529@users.noreply.github.com> Rotem Dan Rowan Hart @@ -1861,6 +1896,7 @@ SecondSeed <38520721+SecondSeed@users.noreply.github.com> semidark Senemu <10880819+Senemu@users.noreply.github.com> senhtry +Seohyun Choi Sergei Vorobyov Sergey Alirzaev Sergey Alirzaev @@ -1869,6 +1905,7 @@ Sergey Malinin Sergey Sklyarov Sergio López Sergio López +Sergio Sánchez Vallés Sergiu <8598216+mzsergiu@users.noreply.github.com> serhii-nakon <57632032+serhii-nakon@users.noreply.github.com> Sertaç Özercan <852750+sozercan@users.noreply.github.com> @@ -1927,6 +1964,7 @@ Siavash Norouzi <35790025+siavashnorouzi@users.noreply.github.com> Sid Mohan <61345237+sidmohan0@users.noreply.github.com> Sid Shaytay <2595088+SidShaytay@users.noreply.github.com> SIDDARTHA REDDY <75976672+SIDDARTHAREDDY8@users.noreply.github.com> +SIDDHARTH U Sidhartha Reddy Potu <73529763+sid-rp@users.noreply.github.com> Sigbjørn Skjæret <1629204+CISC@users.noreply.github.com> Sigbjørn Skjæret @@ -2000,6 +2038,7 @@ Steven Roussey stevenkuang Steward Garcia <57494570+FSSRepo@users.noreply.github.com> stormy <82701871+stormyhs@users.noreply.github.com> +stornic56 <71296607+stornic56@users.noreply.github.com> StrangeBytesDev <141275258+StrangeBytesDev@users.noreply.github.com> strawberrymelonpanda <152940198+strawberrymelonpanda@users.noreply.github.com> Strongtut @@ -2010,6 +2049,7 @@ Sumit Chatterjee <51856136+sumitchatterjee13@users.noreply.github.com> Sundaram krishnan <104441812+sundaram123krishnan@users.noreply.github.com> SuperUserNameMan Sutou Kouhei +Sv. Lockal Svetlozar Georgiev <55534064+sgeor255@users.noreply.github.com> Swigler <124839156+Swigler@users.noreply.github.com> swittk @@ -2091,11 +2131,13 @@ Timothy Cronin <40186632+4imothy@users.noreply.github.com> Ting Lou Ting Lou Ting Sun +Titania nastadeva Titaniumtown Tiwei Bie tjohnman tkran2 <157059462+tkran2@users.noreply.github.com> Tobias Lütke +Tobias Oetiker Toby <25832191+aetherbird@users.noreply.github.com> Todd Malsbary Todor Boinovski @@ -2106,6 +2148,7 @@ Tom Hillbrunner Tom Jobbins <784313+TheBloke@users.noreply.github.com> Tom Overlund Tom Tan <29201606+intel00000@users.noreply.github.com> +Tom Tan Tom Vaucourt <34662901+T0mSIlver@users.noreply.github.com> Tomas Tomáš Pazdiora @@ -2115,6 +2158,7 @@ toyer <2042519524@qq.com> TrevorS TriDefender triplenom <79777178+triplenom@users.noreply.github.com> +Triss Lazaj <114891155+trisslazaj@users.noreply.github.com> Tristan Druyen Tristan Ross Trivalik <3148279+trivalik@users.noreply.github.com> @@ -2124,6 +2168,7 @@ Trunk Trick <2451421621@qq.com> Ts-sound <44093942+Ts-sound@users.noreply.github.com> tslmy tt <291400568@qq.com> +Túlio Ribeiro dos Anjos Tunahan <115956684+tnhnyzc@users.noreply.github.com> Tungsten842 <886724vf@anonaddy.me> Tungsten842 @@ -2238,6 +2283,7 @@ wonjun Jang woodx <124784234+woodx9@users.noreply.github.com> Woof Dog <197125663+woof-dog@users.noreply.github.com> wooksong +Wooseok Shin <46666862+wooseok-shin@users.noreply.github.com> Wouter <9594229+DifferentialityDevelopment@users.noreply.github.com> Wroclaw wsbagnsv1 @@ -2260,6 +2306,7 @@ xiaobing318 <71554036+xiaobing318@users.noreply.github.com> xiaofei XiaotaoChen Xiaoyi Chen +Xiaoyuan Wang Xie Wenxiang <123370282+DreamingWater@users.noreply.github.com> Xie Yanbo Xingchen Song(宋星辰) @@ -2316,6 +2363,7 @@ yomi <3527628634@qq.com> Yonghye Kwon Yongmin Yoo 유용민 Yongyue Sun +yoshi <61565054+Yoshi4470@users.noreply.github.com> Yoshi Suhara Yoshi Suhara Yoshi_likes_e4 <104140648+pt13762104@users.noreply.github.com> @@ -2377,5 +2425,6 @@ Zijun Yu zql <37731799+zqlcode@users.noreply.github.com> zrm Zsapi +Zuhal Karadavut <94466074+zuhalsicim@users.noreply.github.com> zyang-dev <267119621+zyang-dev@users.noreply.github.com> zzzzwc diff --git a/CMakeLists.txt b/CMakeLists.txt index 93543defd9fd..c461e14230d1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,7 +5,7 @@ include(CheckIncludeFileCXX) ### llama.cpp version set(LLAMA_VERSION_MAJOR 1) set(LLAMA_VERSION_MINOR 1) -set(LLAMA_VERSION_PATCH 0) +set(LLAMA_VERSION_PATCH 1) set(LLAMA_VERSION_BASE "${LLAMA_VERSION_MAJOR}.${LLAMA_VERSION_MINOR}.${LLAMA_VERSION_PATCH}") # whether this is a development/nightly build From d8c5a344f5c090eb2bbccdf43659911ca369a850 Mon Sep 17 00:00:00 2001 From: lhez Date: Fri, 4 Dec 2026 00:38:57 -0800 Subject: [PATCH 383/401] opencl: split backend implementation by operation (#29354) Assisted-by: OpenAI Codex Assisted-by: Claude Opus 5.5 --- ggml/src/ggml-opencl/CMakeLists.txt | 88 +- ggml/src/ggml-opencl/cl-common.cpp | 903 + ggml/src/ggml-opencl/cl-common.h | 2703 + ggml/src/ggml-opencl/fa_tune.h | 6 +- ggml/src/ggml-opencl/ggml-opencl.cpp | 43327 +--------------- .../kernels/mul_mm_f16_f32_attn_adreno.cl | 434 + .../ggml-opencl/kernels/mul_mv_f16_f32_l4.cl | 396 - ggml/src/ggml-opencl/kernels/unary_ext.cl | 26 - ggml/src/ggml-opencl/kernels/xielu.cl | 26 + ggml/src/ggml-opencl/ops.h | 1104 + ggml/src/ggml-opencl/ops/abs.cpp | 123 + ggml/src/ggml-opencl/ops/add.cpp | 204 + ggml/src/ggml-opencl/ops/add_id.cpp | 92 + ggml/src/ggml-opencl/ops/arange.cpp | 58 + ggml/src/ggml-opencl/ops/argmax.cpp | 58 + ggml/src/ggml-opencl/ops/argsort.cpp | 83 + ggml/src/ggml-opencl/ops/clamp.cpp | 107 + ggml/src/ggml-opencl/ops/concat.cpp | 142 + ggml/src/ggml-opencl/ops/cont.cpp | 12 + ggml/src/ggml-opencl/ops/conv_2d.cpp | 162 + ggml/src/ggml-opencl/ops/conv_2d_dw.cpp | 102 + ggml/src/ggml-opencl/ops/cpy.cpp | 191 + ggml/src/ggml-opencl/ops/cumsum.cpp | 136 + ggml/src/ggml-opencl/ops/diag.cpp | 66 + ggml/src/ggml-opencl/ops/div.cpp | 152 + ggml/src/ggml-opencl/ops/dsv4_hc.cpp | 66 + ggml/src/ggml-opencl/ops/dup.cpp | 12 + ggml/src/ggml-opencl/ops/exp.cpp | 109 + ggml/src/ggml-opencl/ops/expm1.cpp | 123 + ggml/src/ggml-opencl/ops/fill.cpp | 54 + ggml/src/ggml-opencl/ops/flash_attn.cpp | 4474 ++ ggml/src/ggml-opencl/ops/gated_delta_net.cpp | 328 + ggml/src/ggml-opencl/ops/gelu.cpp | 142 + ggml/src/ggml-opencl/ops/get_rows.cpp | 107 + ggml/src/ggml-opencl/ops/glu.cpp | 159 + ggml/src/ggml-opencl/ops/group_norm.cpp | 122 + ggml/src/ggml-opencl/ops/im2col.cpp | 123 + ggml/src/ggml-opencl/ops/im2col_3d.cpp | 134 + ggml/src/ggml-opencl/ops/l2_norm.cpp | 81 + .../src/ggml-opencl/ops/lightning_indexer.cpp | 87 + ggml/src/ggml-opencl/ops/mean.cpp | 85 + ggml/src/ggml-opencl/ops/mul.cpp | 163 + ggml/src/ggml-opencl/ops/mul_mat.cpp | 6723 +++ ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp | 10859 ++++ ggml/src/ggml-opencl/ops/mul_mat_id.cpp | 3600 ++ ggml/src/ggml-opencl/ops/neg.cpp | 109 + ggml/src/ggml-opencl/ops/nop.cpp | 17 + ggml/src/ggml-opencl/ops/norm.cpp | 160 + ggml/src/ggml-opencl/ops/pad.cpp | 122 + ggml/src/ggml-opencl/ops/permute.cpp | 12 + ggml/src/ggml-opencl/ops/relu.cpp | 59 + ggml/src/ggml-opencl/ops/repeat.cpp | 104 + ggml/src/ggml-opencl/ops/reshape.cpp | 12 + ggml/src/ggml-opencl/ops/rms_norm.cpp | 304 + ggml/src/ggml-opencl/ops/rope.cpp | 220 + ggml/src/ggml-opencl/ops/scale.cpp | 100 + ggml/src/ggml-opencl/ops/set.cpp | 93 + ggml/src/ggml-opencl/ops/set_rows.cpp | 201 + ggml/src/ggml-opencl/ops/sigmoid.cpp | 108 + ggml/src/ggml-opencl/ops/silu.cpp | 98 + ggml/src/ggml-opencl/ops/soft_max.cpp | 202 + ggml/src/ggml-opencl/ops/softplus.cpp | 123 + ggml/src/ggml-opencl/ops/solve_tri.cpp | 89 + ggml/src/ggml-opencl/ops/sqr.cpp | 77 + ggml/src/ggml-opencl/ops/sqrt.cpp | 77 + ggml/src/ggml-opencl/ops/ssm_conv.cpp | 88 + ggml/src/ggml-opencl/ops/ssm_scan.cpp | 187 + ggml/src/ggml-opencl/ops/sub.cpp | 147 + ggml/src/ggml-opencl/ops/sum_rows.cpp | 84 + ggml/src/ggml-opencl/ops/tanh.cpp | 123 + .../ggml-opencl/ops/timestep_embedding.cpp | 72 + ggml/src/ggml-opencl/ops/top_k.cpp | 99 + ggml/src/ggml-opencl/ops/top_k_mask.cpp | 137 + ggml/src/ggml-opencl/ops/transpose.cpp | 12 + ggml/src/ggml-opencl/ops/tri.cpp | 62 + ggml/src/ggml-opencl/ops/unary-ext.cpp | 133 + ggml/src/ggml-opencl/ops/upscale.cpp | 148 + ggml/src/ggml-opencl/ops/view.cpp | 12 + ggml/src/ggml-opencl/ops/xielu.cpp | 64 + ggml/src/ggml-opencl/repack.cpp | 2702 + ggml/src/ggml-opencl/unpack.cpp | 1795 + 81 files changed, 44594 insertions(+), 41810 deletions(-) create mode 100644 ggml/src/ggml-opencl/cl-common.cpp create mode 100644 ggml/src/ggml-opencl/cl-common.h create mode 100644 ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_attn_adreno.cl create mode 100644 ggml/src/ggml-opencl/kernels/xielu.cl create mode 100644 ggml/src/ggml-opencl/ops.h create mode 100644 ggml/src/ggml-opencl/ops/abs.cpp create mode 100644 ggml/src/ggml-opencl/ops/add.cpp create mode 100644 ggml/src/ggml-opencl/ops/add_id.cpp create mode 100644 ggml/src/ggml-opencl/ops/arange.cpp create mode 100644 ggml/src/ggml-opencl/ops/argmax.cpp create mode 100644 ggml/src/ggml-opencl/ops/argsort.cpp create mode 100644 ggml/src/ggml-opencl/ops/clamp.cpp create mode 100644 ggml/src/ggml-opencl/ops/concat.cpp create mode 100644 ggml/src/ggml-opencl/ops/cont.cpp create mode 100644 ggml/src/ggml-opencl/ops/conv_2d.cpp create mode 100644 ggml/src/ggml-opencl/ops/conv_2d_dw.cpp create mode 100644 ggml/src/ggml-opencl/ops/cpy.cpp create mode 100644 ggml/src/ggml-opencl/ops/cumsum.cpp create mode 100644 ggml/src/ggml-opencl/ops/diag.cpp create mode 100644 ggml/src/ggml-opencl/ops/div.cpp create mode 100644 ggml/src/ggml-opencl/ops/dsv4_hc.cpp create mode 100644 ggml/src/ggml-opencl/ops/dup.cpp create mode 100644 ggml/src/ggml-opencl/ops/exp.cpp create mode 100644 ggml/src/ggml-opencl/ops/expm1.cpp create mode 100644 ggml/src/ggml-opencl/ops/fill.cpp create mode 100644 ggml/src/ggml-opencl/ops/flash_attn.cpp create mode 100644 ggml/src/ggml-opencl/ops/gated_delta_net.cpp create mode 100644 ggml/src/ggml-opencl/ops/gelu.cpp create mode 100644 ggml/src/ggml-opencl/ops/get_rows.cpp create mode 100644 ggml/src/ggml-opencl/ops/glu.cpp create mode 100644 ggml/src/ggml-opencl/ops/group_norm.cpp create mode 100644 ggml/src/ggml-opencl/ops/im2col.cpp create mode 100644 ggml/src/ggml-opencl/ops/im2col_3d.cpp create mode 100644 ggml/src/ggml-opencl/ops/l2_norm.cpp create mode 100644 ggml/src/ggml-opencl/ops/lightning_indexer.cpp create mode 100644 ggml/src/ggml-opencl/ops/mean.cpp create mode 100644 ggml/src/ggml-opencl/ops/mul.cpp create mode 100644 ggml/src/ggml-opencl/ops/mul_mat.cpp create mode 100644 ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp create mode 100644 ggml/src/ggml-opencl/ops/mul_mat_id.cpp create mode 100644 ggml/src/ggml-opencl/ops/neg.cpp create mode 100644 ggml/src/ggml-opencl/ops/nop.cpp create mode 100644 ggml/src/ggml-opencl/ops/norm.cpp create mode 100644 ggml/src/ggml-opencl/ops/pad.cpp create mode 100644 ggml/src/ggml-opencl/ops/permute.cpp create mode 100644 ggml/src/ggml-opencl/ops/relu.cpp create mode 100644 ggml/src/ggml-opencl/ops/repeat.cpp create mode 100644 ggml/src/ggml-opencl/ops/reshape.cpp create mode 100644 ggml/src/ggml-opencl/ops/rms_norm.cpp create mode 100644 ggml/src/ggml-opencl/ops/rope.cpp create mode 100644 ggml/src/ggml-opencl/ops/scale.cpp create mode 100644 ggml/src/ggml-opencl/ops/set.cpp create mode 100644 ggml/src/ggml-opencl/ops/set_rows.cpp create mode 100644 ggml/src/ggml-opencl/ops/sigmoid.cpp create mode 100644 ggml/src/ggml-opencl/ops/silu.cpp create mode 100644 ggml/src/ggml-opencl/ops/soft_max.cpp create mode 100644 ggml/src/ggml-opencl/ops/softplus.cpp create mode 100644 ggml/src/ggml-opencl/ops/solve_tri.cpp create mode 100644 ggml/src/ggml-opencl/ops/sqr.cpp create mode 100644 ggml/src/ggml-opencl/ops/sqrt.cpp create mode 100644 ggml/src/ggml-opencl/ops/ssm_conv.cpp create mode 100644 ggml/src/ggml-opencl/ops/ssm_scan.cpp create mode 100644 ggml/src/ggml-opencl/ops/sub.cpp create mode 100644 ggml/src/ggml-opencl/ops/sum_rows.cpp create mode 100644 ggml/src/ggml-opencl/ops/tanh.cpp create mode 100644 ggml/src/ggml-opencl/ops/timestep_embedding.cpp create mode 100644 ggml/src/ggml-opencl/ops/top_k.cpp create mode 100644 ggml/src/ggml-opencl/ops/top_k_mask.cpp create mode 100644 ggml/src/ggml-opencl/ops/transpose.cpp create mode 100644 ggml/src/ggml-opencl/ops/tri.cpp create mode 100644 ggml/src/ggml-opencl/ops/unary-ext.cpp create mode 100644 ggml/src/ggml-opencl/ops/upscale.cpp create mode 100644 ggml/src/ggml-opencl/ops/view.cpp create mode 100644 ggml/src/ggml-opencl/ops/xielu.cpp create mode 100644 ggml/src/ggml-opencl/repack.cpp create mode 100644 ggml/src/ggml-opencl/unpack.cpp diff --git a/ggml/src/ggml-opencl/CMakeLists.txt b/ggml/src/ggml-opencl/CMakeLists.txt index 66d32a88a79c..1e0160686ace 100644 --- a/ggml/src/ggml-opencl/CMakeLists.txt +++ b/ggml/src/ggml-opencl/CMakeLists.txt @@ -5,6 +5,80 @@ set(TARGET_NAME ggml-opencl) ggml_add_backend_library(${TARGET_NAME} ggml-opencl.cpp + cl-common.h + cl-common.cpp + ops.h + repack.cpp + unpack.cpp + ops/nop.cpp + ops/unary-ext.cpp + ops/get_rows.cpp + ops/set_rows.cpp + ops/add.cpp + ops/add_id.cpp + ops/mul.cpp + ops/div.cpp + ops/sub.cpp + ops/sqr.cpp + ops/sqrt.cpp + ops/mean.cpp + ops/ssm_conv.cpp + ops/ssm_scan.cpp + ops/gelu.cpp + ops/silu.cpp + ops/relu.cpp + ops/sigmoid.cpp + ops/tri.cpp + ops/fill.cpp + ops/arange.cpp + ops/clamp.cpp + ops/norm.cpp + ops/rms_norm.cpp + ops/group_norm.cpp + ops/l2_norm.cpp + ops/tanh.cpp + ops/neg.cpp + ops/exp.cpp + ops/expm1.cpp + ops/abs.cpp + ops/xielu.cpp + ops/softplus.cpp + ops/repeat.cpp + ops/pad.cpp + ops/upscale.cpp + ops/concat.cpp + ops/timestep_embedding.cpp + ops/flash_attn.cpp + ops/mul_mat.cpp + ops/mul_mat_adreno.cpp + ops/conv_2d.cpp + ops/conv_2d_dw.cpp + ops/mul_mat_id.cpp + ops/scale.cpp + ops/cpy.cpp + ops/dup.cpp + ops/cont.cpp + ops/reshape.cpp + ops/view.cpp + ops/permute.cpp + ops/transpose.cpp + ops/set.cpp + ops/diag.cpp + ops/soft_max.cpp + ops/rope.cpp + ops/solve_tri.cpp + ops/im2col.cpp + ops/im2col_3d.cpp + ops/argmax.cpp + ops/lightning_indexer.cpp + ops/top_k.cpp + ops/top_k_mask.cpp + ops/argsort.cpp + ops/dsv4_hc.cpp + ops/sum_rows.cpp + ops/cumsum.cpp + ops/glu.cpp + ops/gated_delta_net.cpp cl-program-cache.cpp cl-program-cache.h ../../include/ggml-opencl.h) @@ -397,6 +471,7 @@ set(GGML_OPENCL_KERNELS expm1 abs unary_ext + xielu softplus pad repeat @@ -421,7 +496,18 @@ set(GGML_OPENCL_KERNELS ) if (GGML_OPENCL_USE_ADRENO_KERNELS) - list(APPEND GGML_OPENCL_KERNELS gemm_xmem_f16_f32_os8 sdpa_xmem_f32_f16_os8 gemm_moe_mxfp4_f32_ns_coopmat gemm_moe_q4_0_f32_ns_coopmat gemm_moe_q4_1_f32_ns_coopmat gemm_moe_q5_0_f32_ns_coopmat gemm_moe_q5_1_f32_ns_coopmat gemm_moe_q4_k_f32_ns_coopmat gemm_moe_q5_k_f32_ns_coopmat gemm_moe_q6_k_f32_ns_coopmat) + list(APPEND GGML_OPENCL_KERNELS + gemm_xmem_f16_f32_os8 + gemm_moe_mxfp4_f32_ns_coopmat + gemm_moe_q4_0_f32_ns_coopmat + gemm_moe_q4_1_f32_ns_coopmat + gemm_moe_q4_k_f32_ns_coopmat + gemm_moe_q5_0_f32_ns_coopmat + gemm_moe_q5_1_f32_ns_coopmat + gemm_moe_q5_k_f32_ns_coopmat + gemm_moe_q6_k_f32_ns_coopmat + mul_mm_f16_f32_attn_adreno + sdpa_xmem_f32_f16_os8) endif () foreach (K ${GGML_OPENCL_KERNELS}) diff --git a/ggml/src/ggml-opencl/cl-common.cpp b/ggml/src/ggml-opencl/cl-common.cpp new file mode 100644 index 000000000000..70f89075a0e5 --- /dev/null +++ b/ggml/src/ggml-opencl/cl-common.cpp @@ -0,0 +1,903 @@ +#include "cl-common.h" +#include "ops.h" + +std::string read_file(const std::string &path) { + std::ifstream ifs(path); + if (!ifs) { + return ""; + } + std::string text; + ifs.seekg(0, std::ios::end); + text.resize(ifs.tellg()); + ifs.seekg(0, std::ios::beg); + ifs.read(&text[0], text.size()); + return text; +} + +// fatal=false returns NULL on compile failure instead of aborting; used for +// optional FA variants that may exhaust the Adreno compiler at large DK. +// when the compiler returns CL_OUT_OF_HOST_MEMORY/CL_OUT_OF_RESOURCES (seen with DK>=256/512) +// for FA programs, do clFinish the queue to free up resources, then rebuild (up to 3x) +// if retry_queue is provided +cl_program build_program_from_source_ex(cl_context ctx, cl_device_id dev, const char* program_buffer, const std::string &compile_opts, bool fatal, const char *tag, cl_command_queue retry_queue) { + if (tag) { GGML_LOG_INFO("ggml_opencl: compiling %s\n", tag); } + cl_program p; + char *program_log; + size_t program_size; + size_t log_size; + int err; + + program_size = strlen(program_buffer); + + const int max_attempts = retry_queue ? 3 : 1; + for (int attempt = 0; attempt < max_attempts; ++attempt) { + p = clCreateProgramWithSource(ctx, 1, (const char**)&program_buffer, &program_size, &err); + if(err < 0) { + GGML_LOG_ERROR("OpenCL error creating program"); + if (fatal) exit(1); + return NULL; + } + + err = clBuildProgram(p, 0, NULL, compile_opts.c_str(), NULL, NULL); + if (err == CL_SUCCESS) { + return p; + } + + const bool transient = (err == CL_OUT_OF_HOST_MEMORY || err == CL_OUT_OF_RESOURCES); + if (retry_queue && transient && attempt + 1 < max_attempts) { + clReleaseProgram(p); + GGML_LOG_WARN("ggml_opencl: transient compile failure (err=%d)%s%s — clFinish + retry (%d/%d)\n", + err, tag ? " building " : "", tag ? tag : "", attempt + 2, max_attempts); + clFinish(retry_queue); // drain in-flight ops holding driver host-heap + continue; + } + + clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); + program_log = (char*) malloc(log_size + 1); + program_log[log_size] = '\0'; + clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL); + GGML_LOG_ERROR("ggml_opencl: kernel compile error (err=%d)%s%s:\n\n%s\n", err, tag ? " building " : "", tag ? tag : "", program_log); + free(program_log); + clReleaseProgram(p); + if (fatal) { + exit(1); + } + return nullptr; + } + return NULL; +} + +cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts, bool fatal) { + cl_context ctx = backend_ctx->context; + cl_device_id dev = backend_ctx->device; + + // Try the on-disk binary cache first. Falls through silently on miss or + // any failure; never blocks the build path. Disabled cache => nullptr. + cl_program p_cached = cl_program_cache_try_load( + backend_ctx->program_cache, ctx, dev, program_buffer, compile_opts); + if (p_cached != nullptr) { + return p_cached; + } + + cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, fatal); + + // Best-effort save of the freshly-built binary (no-op if cache disabled). + if (p != nullptr) { + cl_program_cache_try_save(backend_ctx->program_cache, p, dev, program_buffer, compile_opts); + } + return p; +} + +cl_program build_program_from_binary(cl_context ctx, cl_device_id dev, const char* program_buffer, const std::string &compile_opts, size_t bin_size) { + cl_program p; + char *program_log; + size_t log_size; + int err; + + p = clCreateProgramWithBinary(ctx, 1, &dev, &bin_size, (const unsigned char**)&program_buffer, NULL, &err); + if(err < 0) { + GGML_LOG_ERROR("OpenCL error creating program from binary"); + exit(1); + } + + err = clBuildProgram(p, 0, NULL, compile_opts.c_str(), NULL, NULL); + if(err < 0) { + clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); + program_log = (char*) malloc(log_size + 1); + program_log[log_size] = '\0'; + clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL); + GGML_LOG_ERROR("ggml_opencl: kernel compile error:\n\n%s\n", program_log); + free(program_log); + exit(1); + } + + return p; +} + +bool use_adreno_bin_kernels(ggml_backend_opencl_context * backend_ctx) { +#ifndef GGML_OPENCL_USE_ADRENO_BIN_KERNELS + GGML_UNUSED(backend_ctx); + return false; +#else + if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO) { + return false; + } + return backend_ctx->adreno_use_bin_kernels; +#endif // GGML_OPENCL_USE_ADRENO_BIN_KERNELS +} + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void transpose_2d( + ggml_backend_opencl_context * backend_ctx, + cl_kernel kernel, + cl_mem src, cl_mem dst, size_t size, + cl_int stride, cl_int rows, + bool blocking, + bool auto_local // let driver pick local size for non-uniform workgroups +) { + static ggml_cl_buffer buf; + + cl_event evt; + cl_int err; + + buf.allocate(backend_ctx->context, size); + + cl_mem trans; + cl_buffer_region region; + + region.origin = 0; + region.size = size; + CL_CHECK((trans = clCreateSubBuffer( + buf.buffer, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &src)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_int), &stride)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &rows)); + + size_t local_size[3] = {64, 1, 1}; + size_t global_size[3] = {(size_t)stride, (size_t)rows, 1};; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, + global_size, auto_local ? NULL : local_size, 0, NULL, NULL)); + + if (blocking) { + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, trans, dst, 0, 0, size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + } else { + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, trans, dst, 0, 0, size, 0, NULL, NULL)); + } + + CL_CHECK(clReleaseMemObject(trans)); +} + +void transpose_2d_as_8b( + ggml_backend_opencl_context * backend_ctx, + cl_mem src, cl_mem dst, size_t size, + cl_int stride, cl_int rows, + bool blocking, + bool auto_local +) { + transpose_2d(backend_ctx, backend_ctx->mul_mat.kernel_transpose_8_buf, + src, dst, size, stride, rows, blocking, auto_local); +} + +void transpose_2d_as_16b( + ggml_backend_opencl_context * backend_ctx, + cl_mem src, cl_mem dst, size_t size, + cl_int stride, cl_int rows, + bool blocking, + bool auto_local +) { + transpose_2d(backend_ctx, backend_ctx->mul_mat.kernel_transpose_16_buf, + src, dst, size, stride, rows, blocking, auto_local); +} + +void transpose_2d_as_32b( + ggml_backend_opencl_context * backend_ctx, + cl_mem src, cl_mem dst, size_t size, + cl_int stride, cl_int rows, + bool blocking, + bool auto_local +) { + transpose_2d(backend_ctx, backend_ctx->mul_mat.kernel_transpose_32_buf, + src, dst, size, stride, rows, blocking, auto_local); +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +std::vector g_ggml_backend_opencl_devices; +std::vector> g_ggml_backend_opencl_dev_ctxs; + +void sync_with_other_backends(ggml_backend_opencl_context * backend_ctx) { + if (g_ggml_backend_opencl_devices.size() < 2) { + return; // No other devices to synchronize with. + } + + std::vector events; + events.reserve(g_ggml_backend_opencl_devices.size()); + + for (ggml_backend_device & backend_dev : g_ggml_backend_opencl_devices) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) backend_dev.context; + auto * other_backend_ctx = dev_ctx->backend_ctx; + + if (backend_ctx != other_backend_ctx) { + cl_event ev; + CL_CHECK(clEnqueueMarkerWithWaitList(other_backend_ctx->queue, 0, nullptr, &ev)); + CL_CHECK(clFlush(other_backend_ctx->queue)); + events.push_back(ev); + } + } + + CL_CHECK(clEnqueueBarrierWithWaitList(backend_ctx->queue, events.size(), events.data(), nullptr)); + for (auto ev : events) { + CL_CHECK(clReleaseEvent(ev)); + } +} + +void sync_with_other_backends(ggml_backend_t backend) { + auto * backend_ctx = static_cast(backend->context); + sync_with_other_backends(backend_ctx); +} + +// look up or create a pooled image1d_buffer over a KV-cache view. +cl_mem ggml_cl_img_pool_get_or_create( + ggml_backend_opencl_context * backend_ctx, + std::map & pool, + cl_mem data_device, + cl_ulong offset0, + size_t required_bytes, + cl_channel_type channel_data_type +) { + ggml_backend_opencl_context::ImagePoolKey key{(uintptr_t)data_device, (uint64_t)offset0}; + auto it = pool.find(key); + if (it != pool.end() + && it->second.k_bytes >= required_bytes + && it->second.channel_data_type == channel_data_type + && it->second.image != nullptr) { + return it->second.image; + } + + // need to create or recreate and release any stale entry first. + if (it != pool.end()) { + if (it->second.image) { CL_CHECK(clReleaseMemObject(it->second.image)); } + if (it->second.sub_buffer) {CL_CHECK(clReleaseMemObject(it->second.sub_buffer)); } + pool.erase(it); + } + + cl_int status = CL_SUCCESS; + cl_buffer_region region = {}; + region.origin = (size_t)offset0; + region.size = required_bytes; + cl_mem sub = clCreateSubBuffer(data_device, 0, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + if (status != CL_SUCCESS) { + return nullptr; + } + + const size_t pixel_size = (channel_data_type == CL_HALF_FLOAT) ? 8 : 16; + cl_image_format fmt = {CL_RGBA, channel_data_type}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = required_bytes / pixel_size; + desc.buffer = sub; + cl_mem img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, + &fmt, &desc, NULL, &status); + if (status != CL_SUCCESS) { + CL_CHECK(clReleaseMemObject(sub)); + return nullptr; + } + + ggml_backend_opencl_context::ImagePoolEntry entry; + entry.sub_buffer = sub; + entry.image = img; + entry.k_bytes = required_bytes; + entry.channel_data_type = channel_data_type; + pool[key] = entry; + return img; +} + +// True if two tensors share a device buffer with overlapping byte ranges. The pool +// allocator may place a fused op's output over a sequentially-dead input (safe for the +// original separate kernels, but a read/write race inside one fused kernel). +bool use_adreno_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + int64_t threshold_ne0 = 512; + int64_t threshold_ne1 = 512; + if (!backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 38, 11, 0) && + backend_ctx->adreno_cl_compiler_version.type != DX) { + threshold_ne0 = 128; + threshold_ne1 = 128; + } + // K floor 256 on X2E: the gemma-4 E2B/E4B MTP drafters' weights are all K = 256. + // Default on for X2E, GGML_OPENCL_K_FLOOR_256=0/1 forces it. + static const char * k_floor_256_env = getenv("GGML_OPENCL_K_FLOOR_256"); + const bool k_floor_256 = k_floor_256_env ? atoi(k_floor_256_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; + if (k_floor_256 && threshold_ne0 > 256) { + threshold_ne0 = 256; + } + bool threashold_ok = tensor->ne[0] >= threshold_ne0 && tensor->ne[1] >= threshold_ne1 && + tensor->ne[2] == 1 && tensor->ne[3] == 1; + + // the transposed layout needs K % 32 == 0 and M % 4 == 0 + if (tensor->ne[0] % 32 != 0 || tensor->ne[1] % 4 != 0) { + return false; + } + + // The noshuffle layout packs 2 rows per 32-bit texel and the GEMV reads it at an + // ne1/2 texel stride with an exact-cover dispatch, so it is only addressable when + // ne1 is a multiple of 64; an unaligned ne1 truncates the stride and the weight is + // read misaligned. That is a property of the layout, not of one quant -- q4_K, q5_K + // and q8_0 read the same packing as q6_K. The bound is 64, not 128: a q8_0 attention + // weight of ne1 = 2880 is a multiple of 64 but not 128 and is correct. + switch (tensor->type) { + case GGML_TYPE_Q4_K: + case GGML_TYPE_Q5_K: + case GGML_TYPE_Q6_K: + case GGML_TYPE_Q8_0: + return threashold_ok && tensor->ne[1] % 64 == 0; + default: + break; + } + return threashold_ok; +} + +bool adreno_e17_compiler_quirks(const ggml_backend_opencl_context *backend_ctx) { + if (!backend_ctx || backend_ctx->gpu_family != GPU_FAMILY::ADRENO || + backend_ctx->adreno_cl_compiler_version.type != ADRENO_CL_COMPILER_TYPE::E17) { + return false; + } + + static const bool enabled = []() { + const char * e = getenv("GGML_OPENCL_ADRENO_E17_QUIRKS"); + return e && e[0] && e[0] != '0'; + }(); + return enabled; +} + +bool ggml_cl_q2_k_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_Q2_K_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_Q2_K && + backend_ctx->gpu_family == ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_q3_k_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_Q3_K_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_Q3_K && + backend_ctx->gpu_family == GPU_FAMILY::ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq3_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ3_S_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ3_S && + backend_ctx->gpu_family == ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq3_xxs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ3_XXS_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ3_XXS && + backend_ctx->gpu_family == ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq4_xs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ4_XS_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ4_XS && + backend_ctx->gpu_family == ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq1_m_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ1_M_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ1_M && + backend_ctx->gpu_family == ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq1_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ1_S_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ1_S && + backend_ctx->gpu_family == ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_q2_0_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_Q2_0_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_Q2_0 && + backend_ctx->gpu_family == GPU_FAMILY::ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq2_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ2_S_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ2_S && + backend_ctx->gpu_family == GPU_FAMILY::ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq2_xs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ2_XS_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ2_XS && + backend_ctx->gpu_family == GPU_FAMILY::ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_iq2_xxs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) + if (const char * env = getenv("GGML_OPENCL_IQ2_XXS_NOSHUFFLE")) { + if (env[0] == '0') { + return false; + } + } + return tensor->type == GGML_TYPE_IQ2_XXS && + backend_ctx->gpu_family == GPU_FAMILY::ADRENO && + ggml_is_contiguous(tensor) && !tensor->view_src && + use_adreno_kernels(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool use_adreno_moe_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + // The moe weight repack kernels *_trans4_ns alias a private ushort8 through a uchar*. + // Certain compilers (found with some A7x and A6x) miscompiles this, corrupting the weights. + // So, exclude A6x and A7x from using Adreno MoE kernels for now. + // The quants that have a general mul_mat_id kernel fallback to the general version; the + // rest fallback to CPU. + if (backend_ctx && (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::ADRENO_UNKNOWN)) { + return false; + } + + if (adreno_e17_compiler_quirks(backend_ctx)) { + return false; + } + + int ne01 = tensor->ne[1]; + return (((strstr(tensor->name, "ffn") != NULL) && (strstr(tensor->name, "exps") != NULL)) || (strstr(tensor->name, "as") != NULL)) && (ne01 % 32 == 0); +} + +bool enable_adreno_trans_weight(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + + bool adreno_kernel = use_adreno_kernels(backend_ctx, tensor); + + size_t elem_num = tensor->ne[0] * tensor->ne[1] * tensor->ne[2] * tensor->ne[3]; + + // The 2D weight transpose (transpose_2d_as_*) tiles rows by 4 over a 2D matrix, + // so it requires K(ne0)%32==0, M(ne1)%4==0 and ne2==ne3==1. + const bool shape_ok = (tensor->ne[0] % 32 == 0) && (tensor->ne[1] % 4 == 0) && + (tensor->ne[2] == 1) && (tensor->ne[3] == 1); + + return ((elem_num < 128 * 1024 * 1024) && adreno_kernel && shape_ok); // max element num: 2**27 +} + +inline bool tiled_gemv_default_on(const ggml_backend_opencl_context *backend_ctx) { + return backend_ctx && (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X); +} +inline bool q6k_gemv_tiled_enabled(const ggml_backend_opencl_context *backend_ctx) { + static const char * e = std::getenv("GGML_OPENCL_Q6K_GEMV_TILED"); + if (e && e[0] != '\0') { + return e[0] != '0'; + } + return tiled_gemv_default_on(backend_ctx); +} +bool use_q6k_tiled(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + return q6k_gemv_tiled_enabled(backend_ctx) && tensor->type == GGML_TYPE_Q6_K && + tensor->ne[1] >= 32768 && tensor->ne[1] % 64 == 0 && + use_adreno_kernels(backend_ctx, tensor); +} +inline bool q4k_gemv_tiled_enabled(const ggml_backend_opencl_context *backend_ctx) { + if (!backend_ctx->has_integer_dot) { + return false; + } + static const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_TILED"); + if (e && e[0] != '\0') { + return e[0] != '0'; + } + return tiled_gemv_default_on(backend_ctx); +} +bool use_q4k_tiled(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + return q4k_gemv_tiled_enabled(backend_ctx) && tensor->type == GGML_TYPE_Q4_K && + tensor->ne[1] >= 32768 && tensor->ne[1] % 64 == 0 && + use_adreno_kernels(backend_ctx, tensor); +} + +static inline bool flat_large_m_enabled() { + static const char * e = getenv("GGML_OPENCL_FLAT_LARGE_M"); + static const bool en = e != nullptr && atoi(e) != 0; + return en; +} +bool enable_adreno_trans_weight_q5_K(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + if (!use_adreno_kernels(backend_ctx, tensor)) { + return false; + } + + const size_t elem_num = ggml_nelements(tensor); + const size_t q_img_width = elem_num / 8; + const size_t qh_img_width = elem_num / 16; + const bool shape_ok = tensor->ne[0] % 32 == 0 && tensor->ne[1] % 4 == 0 && + tensor->ne[2] == 1 && tensor->ne[3] == 1; + + return shape_ok && q_img_width <= backend_ctx->image_max_buffer_size && + qh_img_width <= backend_ctx->image_max_buffer_size; +} + +// The noshuffle Q4_K weight image stores eight weights per uint texel. +static inline bool q4_K_weight_image_fits(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + const size_t texels = (size_t) ggml_nelements(tensor) / 8; + return texels != 0 && texels <= backend_ctx->image_max_buffer_size; +} + +bool use_flat_gemv_for_large_m_q4_K(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + if (tensor->ne[1] % 4 != 0 && tensor->ne[2] == 1 && tensor->ne[3] == 1) { + return true; + } + + if (tensor->ne[2] != 1 || tensor->ne[3] != 1 || use_q4k_tiled(backend_ctx, tensor)) { + return false; + } + + // The image limit is a correctness guard, independent of the large-M opt-in. + if (!q4_K_weight_image_fits(backend_ctx, tensor)) { + return true; + } + + // gemv_noshuffle variant perf drops for large M, use flat variant for large M. + // threshold is well above typical hidden/FFN dims, but below typical vocab sizes. + // note that this forces large M weights to use LM GEMM. + return flat_large_m_enabled() && tensor->ne[1] >= 32768; +} + +bool use_flat_gemv_for_large_m_q6_K(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { + // NOTE on ordering: the ne01 % 128 escape below is a CORRECTNESS guard, not a + // performance one, so it must be reachable regardless of flat_large_m_enabled(). + // The opt-in gate therefore sits after it, and after the tiled deferral. + // gemv_noshuffle variant perf drops for large M, use flat variant for large M. + // threshold is well above typical hidden/FFN dims, but below typical vocab sizes. + // q6_K flat gemv is worse for smaller K; 2048 seems to be a reasonable threshold. + // note that this forces large M weights to use LM GEMM. + // When this branch's tiled-canonical lm_head/embed layout is active, the weight is + // converted to the 64-row tiled layout, which the flat gemv would misread as + // garbage. use_q6k_tiled owns these large-M weights (it requires ne01 % 64 == 0, + // so it never claims an odd-vocab weight), so defer to it first. + if (use_q6k_tiled(backend_ctx, tensor)) { + return false; + } + // The noshuffle (transposed-weight) layout packs 2 rows per 32-bit texel and the + // gemv reads it with a ne01/2 texel stride and an exact-cover dispatch of + // ceil(ne01/2 / 64)*64 work-items with no store guard; the gemm uses 4-row tiles. + // It is therefore only correct for ne01 % 128 == 0: an odd ne01 (e.g. granitemoe + // lm_head [1536, 49155] -- odd vocab) truncates the texel stride, misaligning every + // odd column of the transposed layout (gross garbage) and dropping the last row; + // other non-multiples over-dispatch and write past the end of dst. Route such + // tensors to the flat GEMV + regular convert; the matching GEMM (ne1>1) falls back + // to CPU (see supports_op). All standard even-vocab/hidden dims are multiples of + // 128 and keep the noshuffle path. + if ((tensor->ne[1] % 128 != 0) && tensor->ne[2] == 1 && tensor->ne[3] == 1) { + return true; + } + + if (!flat_large_m_enabled()) { + return false; + } + + // The gemv_noshuffle slowdown tracks TOTAL weight size, not ne0 alone; ne0 >= 2048 is a + // proxy for "large weight" that misses a narrow-hidden vocab-scale lm_head. + // Add a direct size escape so such weights also take the flat path, without changing + // which weights ne0 >= 2048 already routes there. + // The size escape is not taken on the A7X since its compiler miscompiles the flat K-quant GEMV + return tensor->ne[1] >= 32768 + && (tensor->ne[0] >= 2048 || (backend_ctx->adreno_gen != ADRENO_GPU_GEN::A7X && ggml_nbytes(tensor) >= (256ull << 20))) + && tensor->ne[2] == 1 && tensor->ne[3] == 1; +} + +// check if a Q8_0 tensor has been SOA'ed in set_tensor +// we store SOA'ed tensors in a map in set_tensor, check against that map +bool use_q4_0_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (!backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_32b_trans || + !(backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_coopmat)) { + return false; + } + // bin kernels require ne2 == 1 and ne3 == 1 for weights + return tensor->ne[2] == 1 && tensor->ne[3] == 1 && + (tensor->ne[0] % 32 == 0) && (tensor->ne[1] % 64 == 0); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool use_q4_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (!backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_32b_trans || + !(backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_coopmat)) { + return false; + } + // bin kernels require ne2 == 1 and ne3 == 1 for weights + return tensor->ne[2] == 1 && tensor->ne[3] == 1 && + (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0) && + !use_q4k_tiled(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool use_q5_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (!backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32_32b_trans || + !(backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_coopmat)) { + return false; + } + return (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool use_q6_k_bin_kernels(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (!backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_k_f32_32b_trans || + !(backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin || + backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_coopmat)) { + return false; + } + // bin kernels require ne2 == 1 and ne3 == 1 for weights + return tensor->ne[2] == 1 && tensor->ne[3] == 1 && + (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0) && + !use_q6k_tiled(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(tensor); + return false; +#endif +} + +bool ggml_cl_is_q8_0_soa(const ggml_tensor * tensor) { + if (tensor == nullptr || tensor->type != GGML_TYPE_Q8_0 || tensor->buffer == nullptr) { + return false; + } + auto * ctx = (ggml_backend_opencl_buffer_context *) tensor->buffer->context; + if (ctx == nullptr) { + return false; + } + const ggml_tensor * key = tensor->view_src != nullptr ? tensor->view_src : tensor; + return ctx->q8_0_soa_tensors.count(key) > 0; +} + +// check if a Q4_0 tensor has been SOA'ed in set_tensor +// we store SOA'ed tensors in a map in set_tensor, check against that map +bool ggml_cl_is_q4_0_soa(const ggml_tensor * tensor) { + if (tensor == nullptr || tensor->type != GGML_TYPE_Q4_0 || tensor->buffer == nullptr) { + return false; + } + auto * ctx = (ggml_backend_opencl_buffer_context *) tensor->buffer->context; + if (ctx == nullptr) { + return false; + } + const ggml_tensor * key = tensor->view_src != nullptr ? tensor->view_src : tensor; + return ctx->q4_0_soa_tensors.count(key) > 0; +} + + +std::string ggml_opencl_make_compile_opts(const ggml_backend_opencl_context * backend_ctx) { + const auto opencl_c_std = + std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + + std::to_string(backend_ctx->opencl_c_version.minor); + std::string compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable -cl-unsafe-math-optimizations" + " -cl-finite-math-only -cl-fast-relaxed-math"; + if (backend_ctx->adreno_use_large_buffer) { + compile_opts += " -qcom-enable-large-buffer "; + } + + return compile_opts; +} + +void load_cl_kernels(ggml_backend_opencl_context * backend_ctx) { + if (backend_ctx->kernels_loaded) { + return; + } + + GGML_LOG_INFO("ggml_opencl: loading OpenCL kernels"); + ggml_cl_load_kernels_add(backend_ctx); + ggml_cl_load_kernels_add_id(backend_ctx); + ggml_cl_load_kernels_tri(backend_ctx); + ggml_cl_load_kernels_fill(backend_ctx); + ggml_cl_load_kernels_arange(backend_ctx); + ggml_cl_load_kernels_clamp(backend_ctx); + ggml_cl_load_kernels_cpy(backend_ctx); + ggml_cl_load_kernels_repack(backend_ctx); + ggml_cl_load_kernels_diag(backend_ctx); + ggml_cl_load_kernels_gelu(backend_ctx); + ggml_cl_load_kernels_glu(backend_ctx); + ggml_cl_load_kernels_get_rows(backend_ctx); + ggml_cl_load_kernels_solve_tri(backend_ctx); + ggml_cl_load_kernels_im2col(backend_ctx); + ggml_cl_load_kernels_im2col_3d(backend_ctx); + ggml_cl_load_kernels_mul_mat(backend_ctx); + ggml_cl_load_kernels_mul(backend_ctx); + ggml_cl_load_kernels_norm(backend_ctx); + ggml_cl_load_kernels_relu(backend_ctx); + ggml_cl_load_kernels_rms_norm(backend_ctx); + ggml_cl_load_kernels_l2_norm(backend_ctx); + ggml_cl_load_kernels_rope(backend_ctx); + ggml_cl_load_kernels_scale(backend_ctx); + ggml_cl_load_kernels_silu(backend_ctx); + ggml_cl_load_kernels_soft_max(backend_ctx); + ggml_cl_load_kernels_div(backend_ctx); + ggml_cl_load_kernels_sqr(backend_ctx); + ggml_cl_load_kernels_sqrt(backend_ctx); + ggml_cl_load_kernels_mean(backend_ctx); + ggml_cl_load_kernels_sub(backend_ctx); + ggml_cl_load_kernels_dsv4_hc(backend_ctx); + ggml_cl_load_kernels_sum_rows(backend_ctx); + ggml_cl_load_kernels_cumsum(backend_ctx); + ggml_cl_load_kernels_sigmoid(backend_ctx); + ggml_cl_load_kernels_group_norm(backend_ctx); + ggml_cl_load_kernels_repeat(backend_ctx); + ggml_cl_load_kernels_pad(backend_ctx); + ggml_cl_load_kernels_tanh(backend_ctx); + ggml_cl_load_kernels_neg(backend_ctx); + ggml_cl_load_kernels_exp(backend_ctx); + ggml_cl_load_kernels_expm1(backend_ctx); + ggml_cl_load_kernels_abs(backend_ctx); + ggml_cl_load_kernels_xielu(backend_ctx); + ggml_cl_load_kernels_softplus(backend_ctx); + ggml_cl_load_kernels_upscale(backend_ctx); + ggml_cl_load_kernels_concat(backend_ctx); + ggml_cl_load_kernels_timestep_embedding(backend_ctx); + ggml_cl_load_kernels_set_rows(backend_ctx); + ggml_cl_load_kernels_conv_2d(backend_ctx); + ggml_cl_load_kernels_conv_2d_dw(backend_ctx); + ggml_cl_load_kernels_ssm_conv(backend_ctx); + ggml_cl_load_kernels_ssm_scan(backend_ctx); + ggml_cl_load_kernels_gated_delta_net(backend_ctx); + ggml_cl_load_kernels_lightning_indexer(backend_ctx); + ggml_cl_load_kernels_top_k(backend_ctx); + ggml_cl_load_kernels_top_k_mask(backend_ctx); + ggml_cl_load_kernels_mul_mat_id(backend_ctx); + ggml_cl_load_kernels_mul_mat_adreno(backend_ctx); + ggml_cl_load_kernels_unary_ext(backend_ctx); + ggml_cl_load_kernels_nop(backend_ctx); + ggml_cl_load_kernels_dup(backend_ctx); + ggml_cl_load_kernels_cont(backend_ctx); + ggml_cl_load_kernels_reshape(backend_ctx); + ggml_cl_load_kernels_view(backend_ctx); + ggml_cl_load_kernels_permute(backend_ctx); + ggml_cl_load_kernels_transpose(backend_ctx); + ggml_cl_load_kernels_set(backend_ctx); + ggml_cl_load_kernels_flash_attn(backend_ctx); + ggml_cl_load_kernels_unpack(backend_ctx); + GGML_LOG_CONT("\n"); + backend_ctx->kernels_loaded = true; +} diff --git a/ggml/src/ggml-opencl/cl-common.h b/ggml/src/ggml-opencl/cl-common.h new file mode 100644 index 000000000000..9b572a898203 --- /dev/null +++ b/ggml/src/ggml-opencl/cl-common.h @@ -0,0 +1,2703 @@ +#pragma once + +#define CL_TARGET_OPENCL_VERSION GGML_OPENCL_TARGET_VERSION +#define CL_USE_DEPRECATED_OPENCL_1_2_APIS + +// suppress warnings in CL headers for GCC and Clang +#pragma GCC diagnostic ignored "-Woverlength-strings" +#ifdef __clang__ +#pragma GCC diagnostic ignored "-Wgnu-anonymous-struct" +#endif + +#include "ggml-opencl.h" +#include "ggml-backend.h" +#include "ggml-impl.h" +#include "ggml-backend-impl.h" +#include "ggml.h" + +#include "cl-program-cache.h" +#include "ops.h" + +#ifdef GGML_OPENCL_USE_ADRENO_BIN_KERNELS +#include "libdl.h" +#ifdef _WIN32 +#define KERNEL_LIB_NAME "adreno-opencl-kernels.dll" +#else +#define KERNEL_LIB_NAME "libadreno-opencl-kernels.so" +#endif // _WIN32 +#endif // GGML_OPENCL_USE_ADRENO_BIN_KERNELS + +typedef const void * (*get_adreno_bin_kernel_func_t)( + const char * name, + const char * gpu_name, + const char * compiler_ver, + size_t * out_size +); + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#undef MIN +#undef MAX +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#define CEIL_DIV(M, N) (((M) + (N)-1) / (N)) + +#define UNUSED(x) (void)(x) + +#define CL_CHECK(err) \ + do { \ + cl_int err_ = (err); \ + if (err_ != CL_SUCCESS) { \ + GGML_LOG_ERROR("ggml_opencl: %s error %d at %s:%d\n", \ + #err, err_, __FILE__, __LINE__); \ + GGML_ASSERT(0); \ + } \ + } while (0) + +//------------------------------------------------------------------------------ +// OpenCL +//------------------------------------------------------------------------------ + + +// See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1. +// Precompute mp (m' in the paper) and L such that division +// can be computed using a multiply (high 32b of 64b result) +// and a shift: +// +// n/d = (mulhi(n, mp) + n) >> L; +struct fastdiv_vals { + uint32_t mp; + uint32_t L; + uint32_t d; + uint32_t pad; +}; +static_assert(sizeof(fastdiv_vals) == 16, "fastdiv_vals size incorrect"); + +static fastdiv_vals init_fastdiv_values(uint64_t d_64) { + GGML_ASSERT(d_64 != 0); + GGML_ASSERT(d_64 <= std::numeric_limits::max()); + + uint32_t d = (uint32_t)d_64; + + // compute L = ceil(log2(d)); + uint32_t L = 0; + while (L < 32 && (uint32_t{ 1 } << L) < d) { + L++; + } + + uint32_t mp = (uint32_t) ((uint64_t{ 1 } << 32) * ((uint64_t{ 1 } << L) - d) / d + 1); + // pack divisor as well to reduce error surface + return { mp, L, d, 0 }; +} + +enum GPU_FAMILY { + ADRENO, + INTEL, + UNKNOWN, +}; + +enum ADRENO_GPU_GEN { + ADRENO_UNKNOWN, + A6X, + A7X, + A8X, + X1E, + X2E, +}; + +enum ADRENO_CL_COMPILER_TYPE { + E031, + E17, + DX, +}; + +struct ggml_cl_version { + cl_uint major = 0; + cl_uint minor = 0; +}; + + +struct ggml_cl_compiler_version { + ADRENO_CL_COMPILER_TYPE type; + int major = -1; + int minor = -1; + int patch = -1; + + bool same(ADRENO_CL_COMPILER_TYPE t, int x, int y, int z) const { + return major == x && minor == y && patch == z && type == t; + } + bool newer_than(ADRENO_CL_COMPILER_TYPE t, int x, int y, int z) const { + return major*10000 + minor*100 + patch > x*10000 + y*100 + z && type == t; + } + bool newer_than_or_same(ADRENO_CL_COMPILER_TYPE t, int x, int y, int z) const { + return same(t, x, y, z) || newer_than(t, x, y, z); + } +}; + +static size_t align_to(size_t value, size_t to_alignment) { + GGML_ASSERT(to_alignment && "Invalid alignment (must be non-zero)"); + GGML_ASSERT((to_alignment & (to_alignment - 1)) == 0 && "to_alignment must be power-of-two"); + + return ((value + to_alignment - 1) / to_alignment) * to_alignment; +} + + +// Parses a version string of form "XX.YY ". On an error returns ggml_cl_version with all zeroes. +static ggml_cl_version parse_cl_version(std::string_view str) { + size_t major_str_begin = 0; + size_t major_str_end = str.find(".", major_str_begin); + if (major_str_end == std::string::npos) { + return {}; + } + + size_t minor_str_begin = major_str_end + 1; + size_t minor_str_end = str.find(" ", minor_str_begin); + if (minor_str_end == std::string::npos) { + return {}; + } + + cl_uint version_major; + if (std::from_chars(str.data() + major_str_begin, str.data() + major_str_end, version_major).ec != std::errc{}) { + return {}; + } + + cl_uint version_minor; + if (std::from_chars(str.data() + minor_str_begin, str.data() + minor_str_end, version_minor).ec != std::errc{}) { + return {}; + } + return { version_major, version_minor }; +} + +// Returns OpenCL platform's version. On an error returns ggml_cl_version with all zeroes. +static ggml_cl_version get_opencl_platform_version(cl_platform_id platform) { + size_t param_size; + CL_CHECK(clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 0, nullptr, ¶m_size)); + std::unique_ptr param_storage(new char[param_size]); + CL_CHECK(clGetPlatformInfo(platform, CL_PLATFORM_VERSION, param_size, param_storage.get(), nullptr)); + + auto param_value = std::string_view(param_storage.get(), param_size); + const std::string version_prefix = "OpenCL "; // Suffix: "XX.YY " + if (param_value.find(version_prefix) != 0) { + return {}; + } + param_value.remove_prefix(version_prefix.length()); + return parse_cl_version(param_value); +} + +// Return a version to use in OpenCL C compilation. On an error returns ggml_cl_version with all zeroes. +static ggml_cl_version get_opencl_device_version(cl_device_id device) { + size_t param_size; + if (clGetDeviceInfo(device, CL_DEVICE_VERSION, 0, nullptr, ¶m_size) != CL_SUCCESS || !param_size) { + return {}; + } + std::unique_ptr param_storage(new char[param_size]); + if (clGetDeviceInfo(device, CL_DEVICE_VERSION, param_size, param_storage.get(), nullptr) != CL_SUCCESS) { + return {}; + } + + auto param_value = std::string_view(param_storage.get(), param_size); + const std::string version_prefix = "OpenCL "; // "OpenCL . " + if (param_value.find(version_prefix) != 0) { + return {}; + } + param_value.remove_prefix(version_prefix.length()); + return parse_cl_version(param_value); +} + +static ggml_cl_version get_opencl_c_version(ggml_cl_version platform_version, cl_device_id device) { + size_t param_size; + +#if CL_TARGET_OPENCL_VERSION >= 300 + // CL_DEVICE_OPENCL_C_ALL_VERSIONS is an OpenCL 3.0 *device* query, so gating it on the + // *platform* version is not enough: a 3.0 platform can expose 2.0 devices, where the + // query returns CL_INVALID_VALUE and the old CL_CHECK aborted during backend init. + // Gate on the device version, and treat a failure as "fall back to the legacy query" + // rather than fatal -- a device may advertise 3.0 and still refuse the property. + const ggml_cl_version device_version = get_opencl_device_version(device); + if (platform_version.major >= 3 && device_version.major >= 3) { + cl_int err = clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_ALL_VERSIONS, 0, nullptr, ¶m_size); + if (err == CL_SUCCESS && param_size) { + std::unique_ptr versions(new cl_name_version[param_size]); + err = clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_ALL_VERSIONS, param_size, versions.get(), nullptr); + if (err == CL_SUCCESS) { + unsigned versions_count = param_size / sizeof(cl_name_version); + + cl_version version_max = 0; + for (unsigned i = 0; i < versions_count; i++) { + version_max = std::max(versions[i].version, version_max); + } + + return { CL_VERSION_MAJOR(version_max), CL_VERSION_MINOR(version_max) }; + } + } + // fall through to CL_DEVICE_OPENCL_C_VERSION below + } +#else + GGML_UNUSED(platform_version); +#endif // CL_TARGET_OPENCL_VERSION >= 300 + + if (clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_VERSION, 0, nullptr, ¶m_size) != CL_SUCCESS || !param_size) { + return {}; + } + + std::unique_ptr param_storage(new char[param_size]); + if (clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_VERSION, param_size, param_storage.get(), nullptr) != CL_SUCCESS) { + return {}; + } + auto param_value = std::string_view(param_storage.get(), param_size); + + const std::string version_prefix = "OpenCL C "; // Suffix: "XX.YY " + if (param_value.find(version_prefix) != 0) { + return {}; + } + param_value.remove_prefix(version_prefix.length()); + + return parse_cl_version(param_value); +} + +static ADRENO_GPU_GEN get_adreno_gpu_gen(const char *device_name) { + if (strstr(device_name, "610") || strstr(device_name, "612") || + strstr(device_name, "613") || strstr(device_name, "615") || + strstr(device_name, "616") || strstr(device_name, "618") || + strstr(device_name, "619") || strstr(device_name, "620") || + strstr(device_name, "623") || strstr(device_name, "630") || + strstr(device_name, "640") || + strstr(device_name, "642") || strstr(device_name, "643") || + strstr(device_name, "644") || strstr(device_name, "650") || + strstr(device_name, "660") || strstr(device_name, "663") || + strstr(device_name, "680") || strstr(device_name, "685") || + strstr(device_name, "690")) { + return ADRENO_GPU_GEN::A6X; + } + + if (strstr(device_name, "730") || + strstr(device_name, "740") || + strstr(device_name, "750")) { + return ADRENO_GPU_GEN::A7X; + } + + if (strstr(device_name, "810") || + strstr(device_name, "830") || + strstr(device_name, "840") || + strstr(device_name, "850")) { + return ADRENO_GPU_GEN::A8X; + } + + if (strstr(device_name, "X1")) { + return ADRENO_GPU_GEN::X1E; + } + + if (strstr(device_name, "X2")) { + return ADRENO_GPU_GEN::X2E; + } + + return ADRENO_GPU_GEN::ADRENO_UNKNOWN; +} + +static ggml_cl_compiler_version get_adreno_cl_compiler_version(const char *driver_version) { + std::string driver_ver_str(driver_version); + ADRENO_CL_COMPILER_TYPE type = ADRENO_CL_COMPILER_TYPE::E031; + size_t compiler_ver_pos = driver_ver_str.find("E031"); + size_t compiler_ver_len = 13; + size_t compiler_major_offset = 5; + size_t compiler_minor_offset = 8; + size_t compiler_patch_offset = 11; + + if (compiler_ver_pos == std::string::npos) { + compiler_ver_pos = driver_ver_str.find("E17"); + if (compiler_ver_pos != std::string::npos) { + type = ADRENO_CL_COMPILER_TYPE::E17; + compiler_ver_len = 12; + compiler_major_offset = 4; + compiler_minor_offset = 7; + compiler_patch_offset = 10; + } + } + + if (compiler_ver_pos == std::string::npos) { + compiler_ver_pos = driver_ver_str.find("DX"); + if (compiler_ver_pos == std::string::npos) { + return {}; + } + type = ADRENO_CL_COMPILER_TYPE::DX; + compiler_ver_len = 11; + compiler_major_offset = 3; + compiler_minor_offset = 6; + compiler_patch_offset = 9; + } + + std::string compiler_ver_str = driver_ver_str.substr(compiler_ver_pos, compiler_ver_len); + int major = std::atoi(compiler_ver_str.substr(compiler_major_offset, 2).c_str()); + int minor = std::atoi(compiler_ver_str.substr(compiler_minor_offset, 2).c_str()); + int patch = std::atoi(compiler_ver_str.substr(compiler_patch_offset, 2).c_str()); + return { type, major, minor, patch }; +} + +// cl buffer wrapper +struct ggml_cl_buffer { + cl_mem buffer; + size_t size; + + ggml_cl_buffer() + : buffer(nullptr), size(0) {} + + ~ggml_cl_buffer() { + if (buffer) { + CL_CHECK(clReleaseMemObject(buffer)); + } + } + + void allocate(cl_context context, size_t new_size) { + if (new_size > size) { + size = new_size; + if (buffer) { + CL_CHECK(clReleaseMemObject(buffer)); + } + cl_int err; + CL_CHECK((buffer = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err), err)); + } + } +}; + +// Profiling +struct ProfilingInfo { + std::string op_name; + std::string kernel_name; + + cl_kernel kernel; + cl_event evt; + + cl_ulong cmd_queued; + cl_ulong cmd_submit; + cl_ulong cmd_start; + cl_ulong cmd_end; + cl_ulong overhead_start; + cl_ulong overhead_end; + // For the times below, see spec for clGetEventProfilingInfo + // The time kernel spent in cmd queue - SUBMIT - QUEUED + cl_ulong cmd_queued_duration_ns; + // The time kernel spent for submission - START - SUBMIT + cl_ulong cmd_submit_duration_ns; + // Kernel execution time in nanoseconds - END - START + cl_ulong cmd_duration_ns; + // The time for the kernel to complete - COMPLETE - END + cl_ulong cmd_complete_duration_ns; + // Total time to finish the kernel - COMPLETE - QUEUED + cl_ulong cmd_total_duration_ns; + // Global and local work sizes. + size_t global_size[3]; + size_t local_size[3]; + // Op output size. + size_t output_size[4]; +}; + +static void populateProfilingInfo( + ProfilingInfo& info, cl_event evt, cl_kernel kernel, cl_uint work_dim, + size_t global_size[3], size_t local_size[3], + const ggml_tensor * tensor) { + info.op_name = tensor->name; + info.kernel = kernel; + info.evt = evt; + + // 0 means not specified, e.g., 2D workgroup, or NULL for driver to choose + info.local_size[0] = 0; + info.local_size[1] = 0; + info.local_size[2] = 0; + + info.global_size[0] = 0; + info.global_size[1] = 0; + info.global_size[2] = 0; + + if (local_size) { + for (cl_uint i = 0; i < work_dim; ++i) { + info.local_size[i] = local_size[i]; + } + } + + for (cl_uint i = 0; i < work_dim; ++i) { + info.global_size[i] = global_size[i]; + } + + info.output_size[0] = tensor->ne[0]; + info.output_size[1] = tensor->ne[1]; + info.output_size[2] = tensor->ne[2]; + info.output_size[3] = tensor->ne[3]; +} + +struct ggml_backend_opencl_context; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_adreno_xmem_attn_release_scratch(ggml_backend_opencl_context * backend_ctx); +#endif + + +// backend device context +struct ggml_backend_opencl_device_context { + cl_platform_id platform; + std::string platform_name; + + cl_device_id device; + std::string device_name; + cl_device_type device_type; + std::string device_version; + + // Initialized by ggml_cl_init(). + ggml_backend_opencl_context * backend_ctx = nullptr; + + // Initialized by ggml_backend_opencl_device_get_buffer_type() + ggml_backend_buffer_type buffer_type; + + cl_context context = nullptr; + + GPU_FAMILY gpu_family = GPU_FAMILY::UNKNOWN; + ADRENO_GPU_GEN adreno_gen = ADRENO_GPU_GEN::ADRENO_UNKNOWN; + + std::regex *opfilter = nullptr; // regex of ops to not claim + std::string opfilter_str = ""; // regex string for opfilter + size_t global_mem_size = 0; +}; + +// Lazily-compiled flash-attention kernels and their per-(dk,dv) tile metadata. +// One map per (Q/KV dtype, decode/prefill, split) combination; the int maps +// hold tile dims (bm/bn), workgroup sizes and the n_kv split thresholds. +struct ggml_opencl_fa_kernels { + // FA bin kernels +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel_flash_attn_f32_f16_bin; + + cl_kernel kernel_repack_q_for_wmm; + cl_kernel kernel_repack_k_for_wmm; + cl_kernel kernel_repack_v_for_wmm; + cl_kernel kernel_repack_mask_for_wmm; +#endif + + // f16 Q / f16 KV + std::map, cl_kernel> f16; + std::map, cl_kernel> f16_q1; + // f32 Q / f32 KV + std::map, cl_kernel> f32; + std::map, cl_kernel> f32_q1; + // f32 Q / f16 KV (mixed) + std::map, cl_kernel> f32_f16; + std::map, cl_kernel> f32_f16_split; // N_SPLIT>1 variant + std::map, cl_kernel> f32_f16_split_k_img; // DK=512 prefill split, K via image1d_buffer_t + std::map, cl_kernel> f32_f16_q1; + std::map, cl_kernel> f32_f16_q1_split; // flash-decoding K-split + // vec decode + std::map, cl_kernel> f32_f16_q1_vec; + bool f32_f16_vec_512_attempted = false; + std::map, cl_kernel> f32_f16_mq_decode; + std::map, size_t> f32_f16_mq_decode_wg; + std::map, int> f32_f16_mq_decode_hs; + std::set> f32_f16_mq_decode_attempted; + ggml_cl_buffer fd_partial; + cl_uint compute_units = 0; + // kv-head-coalesced vec decode + std::map, cl_kernel> f32_f16_q1_vec_mq; + // kv-head-coalesced + flash-decoding split + std::map, cl_kernel> f32_f16_q1_vec_mq_split; + // MQ_GQA=8 specializations + std::map, cl_kernel> f32_f16_q1_vec_mq_g8; + std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8; + // k-image variant of MQ_G8 vec_mq_split + std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_k_img; + // k-image variant of MQ_GQA=4 vec_mq_split + std::map, cl_kernel> f32_f16_q1_vec_mq_split_k_img; + // Cluster-parallel decode + std::map, cl_kernel> f32_f16_q1_vec_mq_split_c8; + std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_c8; + // NSG_SPLIT=2 specializations (WG=128): the c8 kernel's register footprint + // caps its per-kernel WG at 128 on X2, below the stock 256/192 requirement. + // 2 subgroups × FA_CL_NCL streams still gives 16 in-flight rows per WG. + std::map, cl_kernel> f32_f16_q1_vec_mq_split_c8_ns2; + std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_c8_ns2; + // FA_CL_C=32 / MQ_GQA=8 / NSG_SPLIT=2 specialization for the DK=DV=256 + // GQA=8 class (Qwen3.5/3.6-35B-A3B: 16 Q heads, 2 KV heads). o_acc = + // DV_VEC/32 × 8 = 128B/lane (in budget); the baseline fa1 path for this + // shape has NO MQ/FD at all and pays an 8× KV re-read per Q head. + std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_c32; + // alternative decode + std::map, cl_kernel> f32_f16_q1_local_tile; + // hybrid local-tile + MQ + FD-split kernel for DK=DV=128 only + std::map, cl_kernel> f32_f16_q1_local_mq_split; + std::map, cl_kernel> f32_f16_q1_local_mq_split_g8; + std::map, int> f32_f16_bm; + std::map, int> f32_f16_bn; + std::map, int> f32_f16_wg_size; + std::map, int> f32_f16_split_wg_size; + std::map, int> f32_f16_split_nkv_threshold; + // f32 Q / native q8_0 KV + std::map, cl_kernel> f32_q8_0_q1; // decode + std::map, cl_kernel> f32_q8_0_q1_vec; // DV-split + multi-subgroup decode + std::map, cl_kernel> f32_q8_0_q1_split; // flash-decoding pass 1 + // KV-head-coalesced + flash-decoding split for q8_0 KV + std::map, cl_kernel> f32_q8_0_q1_vec_mq_split; + std::map, cl_kernel> f32_q8_0_q1_vec_mq_split_g8; + // Cluster-parallel q8_0 decode + std::map, cl_kernel> f32_q8_0_q1_vec_mq_split_c8; + std::map, cl_kernel> f32_q8_0; // prefill (baseline) + std::map, cl_kernel> f32_q8_0_split; // N_SPLIT>1 variant + std::map, int> f32_q8_0_split_wg_size; // wg_size = bm*n_split + std::map, int> f32_q8_0_split_nkv_threshold; // use split when n_kv >= this + std::map, int> f32_q8_0_split_bm; // per-split BLOCK_M + // f32 Q / native q4_0 KV + std::map, cl_kernel> f32_q4_0_q1; + std::map, cl_kernel> f32_q4_0_q1_vec; // DV-split + multi-subgroup decode + std::map, cl_kernel> f32_q4_0_q1_split; + // kv-head-coalesced + flash-decoding split for q4_0 kv (dp4a K dot) + std::map, cl_kernel> f32_q4_0_q1_vec_mq_split; + std::map, cl_kernel> f32_q4_0_q1_vec_mq_split_g8; + // Cluster-parallel q4_0 decode + std::map, cl_kernel> f32_q4_0_q1_vec_mq_split_g8_c8; + std::map, cl_kernel> f32_q4_0_q1_vec_mq_split_c8; + std::map, cl_kernel> f32_q4_0; + std::map, cl_kernel> f32_q4_0_split; + std::map, int> f32_q4_0_split_wg_size; + std::map, int> f32_q4_0_split_nkv_threshold; + std::map, int> f32_q4_0_split_bm; + // shared: flash-decoding merge + prefill prepass (kv-pad, mask-pad, blk class) + std::map, cl_kernel> f32_merge; + std::map, cl_kernel> kv_pad_f16; + std::map, cl_kernel> mask_pad_f16; + std::map, cl_kernel> blk_f16; + // decomposed prefill: V^T, built with the prepass + std::map, cl_kernel> v_transpose_f16; + cl_kernel kernel_fa_decompose_soft_max_4_f16 = nullptr; + cl_kernel kernel_fa_decompose_scale_rows_f32 = nullptr; + cl_kernel kernel_mul_mm_f16_f32_kq_p8 = nullptr; + cl_kernel kernel_mul_mm_q8_f32_kqv = nullptr; + cl_kernel kernel_fa_p8_fixup = nullptr; + cl_kernel kernel_fa_kqv_direct_f16 = nullptr; + cl_kernel kernel_fa_kqv_direct_reduce = nullptr; + cl_kernel kernel_fa_v_transpose_q8 = nullptr; + cl_kernel kernel_fa_q8_rows_f16 = nullptr; + cl_kernel kernel_fa_q8_rows_f32 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8 = nullptr; + cl_kernel kernel_mul_mm_q8_kq_p8_dk512 = nullptr; + // generic prefill tile dims (f16 / f32 paths) + std::map, int> bm; + std::map, int> bn; + // attempted (variant, (dk, dv)) + // all attempted FA kernels appear here, but those not registered failed compilation + std::set>> variant_attempted; +}; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +struct ggml_cl_adreno_xmem_attn_scratch { + cl_mem q_img = nullptr; + cl_mem k_img = nullptr; + cl_mem v_img = nullptr; + cl_mem out_img = nullptr; + cl_mem k_transpose_buf = nullptr; + cl_mem k_transpose_img1d = nullptr; + cl_mem k_packed_buf = nullptr; + cl_mem v_packed_buf = nullptr; + cl_mem score_buf = nullptr; + cl_mem prob_buf = nullptr; + cl_mem score_img1d = nullptr; + cl_mem prob_img1d = nullptr; + cl_mem softmax_stats_img2d = nullptr; + cl_mem xmem_qk = nullptr; + cl_mem xmem_pv = nullptr; + + int n_q = 0; + int n_kv = 0; + int n_kv_padded = 0; + int d_head_q = 0; + int d_head_v = 0; + int q_width = 0; + int kv_heads_total = 0; +}; + +struct ggml_cl_adreno_xmem_attn_state { + bool compiled = false; + bool logged = false; + + cl_kernel kernel_q_f32_to_img_scaled = nullptr; + cl_kernel kernel_kv_f32_to_img_gqa = nullptr; + cl_kernel kernel_kv_f16_to_img_gqa = nullptr; + cl_kernel kernel_img_to_f32 = nullptr; + cl_kernel kernel_k_gather = nullptr; + cl_kernel kernel_pack_k = nullptr; + cl_kernel kernel_qk_gemm = nullptr; + cl_kernel kernel_softmax_reduce_basic = nullptr; + cl_kernel kernel_softmax_apply_basic = nullptr; + cl_kernel kernel_mask_scores = nullptr; + cl_kernel kernel_pack_v = nullptr; + cl_kernel kernel_pv_gemm = nullptr; + + ggml_cl_adreno_xmem_attn_scratch scratch; +}; +#endif + +// backend context +struct ggml_backend_opencl_context { + int ref_count; + + cl_device_id device; + std::string device_name; + + ggml_cl_version platform_version; + ggml_cl_version opencl_c_version; + + // argmax and argsort are loaded in supports_op; argsort availability depends on the compiled kernel's workgroup limit. + bool kernels_loaded_argmax = false; + bool kernels_loaded_argsort = false; + // rest of the kernels are currently always loaded in alloc_buffer. + bool kernels_loaded = false; + + std::string driver_version; + + GPU_FAMILY gpu_family; + ADRENO_GPU_GEN adreno_gen; + + cl_int alignment; + size_t global_mem_size; + size_t max_alloc_size; + cl_ulong local_mem_size; + size_t max_workgroup_size; + bool fp16_support; + bool has_vector_subgroup_broadcast; + bool has_khr_subgroup_shuffle = false; + bool has_subgroup_shuffle = false; // cl_khr_subgroup_shuffle or cl_qcom_subgroup_shuffle + bool has_integer_dot = false; // cl_khr_integer_dot_product or cl_qcom_dot_product8 + bool has_qcom_subgroup_shuffle = false; // specifically cl_qcom_subgroup_shuffle + bool disable_fusion; + bool fuse_mm_glu = true; // opt-out GGML_OPENCL_FUSE_MM_GLU=0 (byte-identical gate+up GEMV + GLU, q4_K FFN) + bool fuse_rms_add = true; // opt-out GGML_OPENCL_FUSE_RMS_ADD=0 (fused rms_norm*w + residual) + bool f16_mrow = true; // opt-out GGML_OPENCL_F16_MROW=0 (multi-row-per-WG f16 decode GEMV for attn proj + lm_head) + int f16_mrow_rpt = 1; // GGML_OPENCL_F16_MROW_RPT={1,2,4,8,16} rows-per-subgroup register blocking + + // ragged moe, use int to directly pass to kernel + cl_uint adreno_use_moe_ragged; + cl_uint adreno_moe_ragged_skip_gran; + cl_uint adreno_use_moe_ragged_dp4; + + // whether fuse moe combine + cl_uint fuse_moe_combine; + + // whether to fold the MoE bias adds into swiglu_oai + cl_uint fuse_moe_bias_glu; + + // whether to fold the MoE down-projection bias add into the combine + cl_uint fuse_moe_bias_combine; + + bool adreno_has_large_buffer; + bool adreno_use_large_buffer; + bool adreno_use_bin_kernels; + get_adreno_bin_kernel_func_t get_adreno_bin_kernel_func = nullptr; + ggml_cl_compiler_version adreno_cl_compiler_version; + // The q6_K flat mul_mat codegen workarounds are needed by old E031 compilers only. + bool q6_k_flat_old_compiler; + + std::string kernel_compile_opts; // cached for lazy-compiled kernels. + + int adreno_wave_size; + + cl_bool non_uniform_workgroups; + size_t image_max_buffer_size; + size_t image2d_max_width; + size_t image2d_max_height; + size_t image3d_max_width; + size_t image3d_max_height; + size_t image3d_max_depth; + + cl_device_svm_capabilities svm_caps; + + cl_context context; + cl_command_queue queue; + + // On-disk compiled-program cache (see GGML_OPENCL_KERNEL_CACHE_DIR). + cl_program_cache_state program_cache; + bool program_cache_initialized = false; + + // prealloc buffers for transposing weights and activations + ggml_cl_buffer prealloc_quant_trans; + ggml_cl_buffer prealloc_scales_trans; + ggml_cl_buffer prealloc_act_trans; + // q8_1-quantized reordered MoE activations for the dp4a prefill GEMM. + ggml_cl_buffer prealloc_moe_qa; // int8 quants [tok_slots * ne00] + ggml_cl_buffer prealloc_moe_da; // per-block d [tok_slots * ne00/32] (half) + ggml_cl_buffer prealloc_moe_sa; // per-block s [tok_slots * ne00/32] (half) + // per-tile transposed qa/da and on-chip scratch for the ldck dp4a MoE GEMM + ggml_cl_buffer prealloc_moe_qa_trans; // int8 quants [tok_slots * ne00] + ggml_cl_buffer prealloc_moe_da_trans; // per-block d [tok_slots * ne00/32] (float) + ggml_cl_buffer prealloc_moe_qda_on_chip; + // scratch copy of the router weights to avoid dst aliasing + ggml_cl_buffer prealloc_moe_combine_w; + ggml_cl_buffer prealloc_splitk_partial; // [ksplit * M] partials for split-K GEMV + cl_mem coopk_c8_qa_image = nullptr; + cl_mem coopk_c8_qa_buffer = nullptr; + size_t coopk_c8_qa_image_bytes = 0; + cl_mem coopk_c8_ds_image = nullptr; + cl_mem coopk_c8_ds_buffer = nullptr; + size_t coopk_c8_ds_image_bytes = 0; + ggml_cl_buffer iq2_s_grid_buffer; + ggml_cl_buffer iq2_xs_grid_buffer; + ggml_cl_buffer iq2_xxs_grid_buffer; + ggml_cl_buffer iq1_s_grid_buffer; + ggml_cl_buffer iq3_s_grid_buffer; + ggml_cl_buffer iq3_xxs_grid_buffer; + cl_mem iq2_s_grid_image = nullptr; + cl_mem iq2_xs_grid_image = nullptr; + cl_mem iq2_xxs_grid_image = nullptr; + cl_mem iq1_s_grid_image = nullptr; + cl_mem iq3_s_grid_image = nullptr; + cl_mem iq3_xxs_grid_image = nullptr; + + // pool of persistent image1d_buffer views over kv-cache layers, keyed by + // (parent buffer, offset within parent) + // used by the img-variant KQ/KQV dispatch paths to avoid per-call + // clCreateSubBuffer + clCreateImage + pending-release-queue on long-context decode + struct ImagePoolKey { + uintptr_t buf; + uint64_t offset; + bool operator<(const ImagePoolKey & o) const { + if (buf != o.buf) return buf < o.buf; + return offset < o.offset; + } + }; + struct ImagePoolEntry { + cl_mem sub_buffer = nullptr; + cl_mem image = nullptr; + size_t k_bytes = 0; + cl_channel_type channel_data_type = CL_FLOAT; + }; + std::map kq_img_pool; + std::map kqv_img_pool; + + // pool for the on-device f16 buffer for kv-cache with non-FA quantized-K (q8_0/q4_0) + std::map dequant_f16_pool; + + // prealloc buffers for src0 and src1 + ggml_cl_buffer prealloc_src0; + ggml_cl_buffer prealloc_src1; + ggml_cl_buffer prealloc_top_k; + + // scratch for the decomposed flash attention prefill, sized per query chunk + ggml_cl_buffer prealloc_fa_vt; + ggml_cl_buffer prealloc_fa_kq; + ggml_cl_buffer prealloc_fa_kqv; + ggml_cl_buffer prealloc_fa_sums; + ggml_cl_buffer prealloc_fa_vtq; + ggml_cl_buffer prealloc_fa_vtd; + ggml_cl_buffer prealloc_fa_pq; + ggml_cl_buffer prealloc_fa_pd; + ggml_cl_buffer prealloc_fa_bmax; + ggml_cl_buffer prealloc_fa_bsum; + ggml_cl_buffer prealloc_fa_k8; + ggml_cl_buffer prealloc_fa_k8_scale; + ggml_cl_buffer prealloc_fa_q8; + ggml_cl_buffer prealloc_fa_q8_scale; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer prealloc_adreno_xmem_const; + bool adreno_xmem_gemm_enabled = false; +#endif + + // prealloc buffers for MoE router table preprocess + bool toggle_reorder = false; + ggml_cl_buffer prealloc_post_router; + ggml_cl_buffer prealloc_emap; + ggml_cl_buffer prealloc_hist; + ggml_cl_buffer prealloc_tile_offset; + ggml_cl_buffer prealloc_total_tiles; + ggml_cl_buffer prealloc_slot_counter; + + ggml_opencl_add_kernels add = {}; + ggml_opencl_add_id_kernels add_id = {}; + ggml_opencl_mul_kernels mul = {}; + ggml_opencl_div_kernels div = {}; + ggml_opencl_sub_kernels sub = {}; + ggml_opencl_scale_kernels scale = {}; + ggml_opencl_sqr_kernels sqr = {}; + ggml_opencl_sqrt_kernels sqrt = {}; + ggml_opencl_mean_kernels mean = {}; + ggml_opencl_silu_kernels silu = {}; + ggml_opencl_gelu_kernels gelu = {}; + ggml_opencl_relu_kernels relu = {}; + ggml_opencl_sigmoid_kernels sigmoid = {}; + ggml_opencl_tri_kernels tri = {}; + ggml_opencl_fill_kernels fill = {}; + ggml_opencl_arange_kernels arange = {}; + ggml_opencl_clamp_kernels clamp = {}; + ggml_opencl_glu_kernels glu = {}; + ggml_opencl_norm_kernels norm = {}; + ggml_opencl_rms_norm_kernels rms_norm = {}; + ggml_opencl_l2_norm_kernels l2_norm = {}; + ggml_opencl_group_norm_kernels group_norm = {}; + ggml_opencl_diag_kernels diag = {}; + ggml_opencl_soft_max_kernels soft_max = {}; + ggml_opencl_fa_kernels fa; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_adreno_xmem_attn_state adreno_xmem_attn; +#endif + ggml_opencl_get_rows_kernels get_rows = {}; + ggml_opencl_set_rows_kernels set_rows = {}; + ggml_opencl_rope_kernels rope = {}; + ggml_opencl_cpy_kernels cpy = {}; + ggml_opencl_repack_kernels repack = {}; + ggml_opencl_mul_mat_kernels mul_mat = {}; + int min_m_gemv_nsg1_q1_0 = 0; + int tile_n_dp4a_q4_k = 32; + int tile_n_dp4a_narrow_q4_k = 32; + int max_n_dp4a_narrow_q4_k = 16; + ggml_opencl_mul_mat_id_kernels mul_mat_id = {}; + ggml_opencl_solve_tri_kernels solve_tri = {}; + ggml_opencl_im2col_kernels im2col = {}; + ggml_opencl_im2col_3d_kernels im2col_3d = {}; + ggml_opencl_argmax_kernels argmax = {}; + ggml_opencl_top_k_kernels top_k = {}; + ggml_opencl_top_k_mask_kernels top_k_mask = {}; + ggml_opencl_lightning_indexer_kernels lightning_indexer = {}; + ggml_opencl_argsort_kernels argsort = {}; + ggml_opencl_dsv4_hc_kernels dsv4_hc = {}; + ggml_opencl_sum_rows_kernels sum_rows = {}; + ggml_opencl_cumsum_kernels cumsum = {}; + ggml_opencl_repeat_kernels repeat = {}; + ggml_opencl_pad_kernels pad = {}; + ggml_opencl_tanh_kernels tanh = {}; + ggml_opencl_neg_kernels neg = {}; + ggml_opencl_exp_kernels exp = {}; + ggml_opencl_expm1_kernels expm1 = {}; + ggml_opencl_abs_kernels abs = {}; + ggml_opencl_xielu_kernels xielu = {}; + ggml_opencl_unary_ext_kernels unary_ext = {}; + ggml_opencl_softplus_kernels softplus = {}; + ggml_opencl_upscale_kernels upscale = {}; + ggml_opencl_concat_kernels concat = {}; + ggml_opencl_conv_2d_kernels conv_2d = {}; + ggml_opencl_conv_2d_dw_kernels conv_2d_dw = {}; + ggml_opencl_ssm_conv_kernels ssm_conv = {}; + ggml_opencl_gated_delta_net_kernels gated_delta_net = {}; + ggml_opencl_ssm_scan_kernels ssm_scan = {}; + ggml_opencl_timestep_embedding_kernels timestep_embedding = {}; + std::vector profiling_info; + std::vector profiling_results; + + void flush_profiling_batch() { + if (profiling_info.empty()) { + return; + } + + // Populate profiling info + for (ProfilingInfo & info : profiling_info) { + cl_ulong cmd_queued; + cl_ulong cmd_submit; + cl_ulong cmd_start; + cl_ulong cmd_end; + cl_ulong cmd_complete; + + CL_CHECK(clWaitForEvents(1, &info.evt)); + CL_CHECK(clGetEventProfilingInfo( + info.evt, CL_PROFILING_COMMAND_QUEUED, sizeof(cl_ulong), &cmd_queued, NULL)); + CL_CHECK(clGetEventProfilingInfo( + info.evt, CL_PROFILING_COMMAND_SUBMIT, sizeof(cl_ulong), &cmd_submit, NULL)); + CL_CHECK(clGetEventProfilingInfo( + info.evt, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &cmd_start, NULL)); + CL_CHECK(clGetEventProfilingInfo( + info.evt, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &cmd_end, NULL)); + CL_CHECK(clGetEventProfilingInfo( + info.evt, CL_PROFILING_COMMAND_COMPLETE, sizeof(cl_ulong), &cmd_complete, NULL)); + CL_CHECK(clReleaseEvent(info.evt)); + info.evt = nullptr; + + char kernel_name[512]; + CL_CHECK(clGetKernelInfo(info.kernel, CL_KERNEL_FUNCTION_NAME, + sizeof(kernel_name), kernel_name, NULL)); + info.kernel_name = kernel_name; + + info.cmd_queued = cmd_queued; + info.cmd_submit = cmd_submit; + info.cmd_start = cmd_start; + info.cmd_end = cmd_end; + + info.cmd_queued_duration_ns = cmd_submit - cmd_queued; + info.cmd_submit_duration_ns = cmd_start - cmd_submit; + info.cmd_duration_ns = cmd_end - cmd_start; + info.cmd_complete_duration_ns = cmd_complete - cmd_end; + info.cmd_total_duration_ns = cmd_complete - cmd_queued; + } + profiling_results.insert(profiling_results.end(), + std::make_move_iterator(profiling_info.begin()), + std::make_move_iterator(profiling_info.end())); + profiling_info.clear(); + } + + void write_profiling_info() { + if (profiling_results.empty()) { + return; + } + + // Dump a csv + FILE * fperf = fopen("cl_profiling.csv", "w"); + if (!fperf) { + GGML_LOG_ERROR("Failed to open cl_profiling.csv\n"); + return; + } + + fprintf(fperf, "op name, kernel name, exec duration (ms), global size, local size, output size\n"); + for (const ProfilingInfo & info : profiling_results) { + fprintf(fperf, "%s,%s,%f,%zux%zux%zu,%zux%zux%zu,%zux%zux%zux%zu\n", + info.op_name.c_str(), info.kernel_name.c_str(), + info.cmd_duration_ns/1.e6f, + info.global_size[0], info.global_size[1], info.global_size[2], + info.local_size[0], info.local_size[1], info.local_size[2], + info.output_size[0], info.output_size[1], info.output_size[2], info.output_size[3]); + } + fclose(fperf); + + // Dump a simple chrome trace + FILE * ftrace = fopen("cl_trace.json", "w"); + if (!ftrace) { + GGML_LOG_ERROR("Failed to open cl_trace.json\n"); + return; + } + + fprintf(ftrace, "[\n"); + for (const ProfilingInfo & info : profiling_results) { + fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"B\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Host\"},\n", + info.kernel_name.c_str(), info.cmd_queued/1000); + fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"E\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Host\"},\n", + info.kernel_name.c_str(), info.cmd_submit/1000); + + fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"B\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Device\"},\n", + info.kernel_name.c_str(), info.cmd_start/1000); + fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"E\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Device\"},\n", + info.kernel_name.c_str(), info.cmd_end/1000); + } + fprintf(ftrace, "]\n"); + fclose(ftrace); + } + + size_t get_kernel_workgroup_size(cl_kernel kernel) const { + size_t workgroup_size = 0; + size_t ret_size = 0; + CL_CHECK( + clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, + sizeof(size_t), &workgroup_size, &ret_size)); + GGML_ASSERT(sizeof(size_t) == ret_size); + return workgroup_size; + } + + void enqueue_ndrange_kernel(cl_kernel kernel, cl_uint work_dim, size_t *global_work_size, size_t *local_work_size, const ggml_tensor * tensor) { + // From the spec on clEnqueueNDRangeKernel: + // If the device associated with command_queue is an OpenCL 2.1 or newer device, + // and global_work_size is NULL or the value in any passed dimension is zero, + // then the kernel command will trivially succeed after its event dependencies + // are satisfied and subsequently update its completion event. + // So this ensures such cases always return trivially without causing errors in + // case of an older device. + for (cl_uint i = 0; i < work_dim; i++) { + if (global_work_size[i] == 0) { + return; + } + } +#ifdef GGML_OPENCL_PROFILING + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + + profiling_info.emplace_back(); + populateProfilingInfo(profiling_info.back(), evt, kernel, work_dim, global_work_size, local_work_size, tensor); + if (profiling_info.size() >= 2048) { + flush_profiling_batch(); + } +#else + GGML_UNUSED(tensor); + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, NULL)); +#endif + } + + const void * get_adreno_bin_kernel(const std::string &kernel_name, size_t *bin_size) const { + if (!get_adreno_bin_kernel_func) { + return nullptr; + } + + size_t sz = 0; + const void * kernel_bin = get_adreno_bin_kernel_func( + kernel_name.c_str(), device_name.c_str(), driver_version.c_str(), &sz); + if (bin_size) { + *bin_size = sz; + } + return kernel_bin; + } + + ~ggml_backend_opencl_context() { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + for (cl_kernel kernel : { + mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8, + mul_mat.kernel_quant_a_q8_1_k4, + mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8, + mul_mat.kernel_quant_a_q8_1_k4h + } + ) { + if (kernel != nullptr) { + CL_CHECK(clReleaseKernel(kernel)); + } + } + for (cl_mem image : {coopk_c8_qa_image, coopk_c8_ds_image}) { + if (image != nullptr) { + CL_CHECK(clReleaseMemObject(image)); + } + } +#endif + for (cl_kernel kernel : { + mul_mat.kernel_gemv_f32_f32_mcr, + mul.kernel_mul_mat_scale, + xielu.kernel_xielu_f32, + xielu.kernel_xielu_f16, + fa.kernel_mul_mm_f16_f32_kq_p8, + fa.kernel_mul_mm_q8_f32_kqv, + fa.kernel_fa_p8_fixup, + fa.kernel_fa_v_transpose_q8, + fa.kernel_fa_kqv_direct_f16, + fa.kernel_fa_kqv_direct_reduce, + fa.kernel_fa_q8_rows_f16, + fa.kernel_fa_q8_rows_f32, + fa.kernel_mul_mm_q8_kq_p8, + fa.kernel_mul_mm_q8_kq_p8_dk512 + }) { + if (kernel != nullptr) { + CL_CHECK(clReleaseKernel(kernel)); + } + } + if (dsv4_hc.kernel_dsv4_hc_pre) { + CL_CHECK(clReleaseKernel(dsv4_hc.kernel_dsv4_hc_pre)); + } + for (int i = 0; i < 2; ++i) { + if (dsv4_hc.kernel_dsv4_hc_post[i]) { + CL_CHECK(clReleaseKernel(dsv4_hc.kernel_dsv4_hc_post[i])); + } + } + if (iq1_s_grid_image) { + CL_CHECK(clReleaseMemObject(iq1_s_grid_image)); + } + if (iq3_xxs_grid_image) { + CL_CHECK(clReleaseMemObject(iq3_xxs_grid_image)); + } + if (iq3_s_grid_image) { + CL_CHECK(clReleaseMemObject(iq3_s_grid_image)); + } + if (iq2_xxs_grid_image) { + CL_CHECK(clReleaseMemObject(iq2_xxs_grid_image)); + } + if (iq2_xs_grid_image) { + CL_CHECK(clReleaseMemObject(iq2_xs_grid_image)); + } + if (iq2_s_grid_image) { + CL_CHECK(clReleaseMemObject(iq2_s_grid_image)); + } + } + + void free() { + clFinish(queue); + + ref_count--; + if (ref_count == 0) { + if (fa.fd_partial.buffer) { + CL_CHECK(clReleaseMemObject(fa.fd_partial.buffer)); + fa.fd_partial.buffer = nullptr; + fa.fd_partial.size = 0; + } +#ifdef GGML_OPENCL_PROFILING + flush_profiling_batch(); + write_profiling_info(); + profiling_results.clear(); +#endif + // release pooled image1d_buffer views over KV cache layers. + for (auto & kv : kq_img_pool) { + if (kv.second.image) { CL_CHECK(clReleaseMemObject(kv.second.image)); } + if (kv.second.sub_buffer) { CL_CHECK(clReleaseMemObject(kv.second.sub_buffer)); } + } + kq_img_pool.clear(); + for (auto & kv : kqv_img_pool) { + if (kv.second.image) { CL_CHECK(clReleaseMemObject(kv.second.image)); } + if (kv.second.sub_buffer) { CL_CHECK(clReleaseMemObject(kv.second.sub_buffer)); } + } + kqv_img_pool.clear(); + for (auto & kv : dequant_f16_pool) { + if (kv.second.image) { CL_CHECK(clReleaseMemObject(kv.second.image)); } + } + dequant_f16_pool.clear(); +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_adreno_xmem_attn_release_scratch(this); +#endif + } + } +}; + +struct ggml_tensor_extra_cl { + // The buffer object that holds the data. + cl_mem data_device; + // The offset into the buffer object. This is primarily for scratch buffer + // and view operation. + // NB: this offset no longer includes view offset (view_offs). Whenever this + // offset is used, view_offs should be considered. + cl_ulong offset; + // The actual size of the cl_mem object. This is needed when returning the + // block to the pool. + size_t actual_size; + + void reset() { + data_device = nullptr; + offset = 0; + actual_size = 0; + } +}; + +struct ggml_tensor_extra_cl_q1_0 { + cl_mem q = nullptr; + cl_mem q_img = nullptr; + + cl_mem d = nullptr; + cl_mem d_img = nullptr; + + size_t size_q = 0; + size_t size_d = 0; + + ~ggml_tensor_extra_cl_q1_0() { + reset(); + } + + void reset() { + // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. + // They must be properly released so that the original buffer can be + // properly released to avoid memory leak. + if (q != nullptr) { + CL_CHECK(clReleaseMemObject(q)); + q = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + q_img = nullptr; + d_img = nullptr; + size_q = 0; + size_d = 0; + } +}; + +// Additional tensor extra structs for quantized tensors. +// These tensors are loaded from files and should not be allocated in scratch -- +// they should always be allocated from the pool. Hence, they do not have an +// `offset`, which indicate their locations in the scratch buffer. +struct ggml_tensor_extra_cl_q4_0 { + // Quantized values. + cl_mem q = nullptr; + // Quantized values in image1d_buffer_t. + cl_mem q_img = nullptr; + // Scales. + cl_mem d = nullptr; + // Scales in image1d_buffer_t. + cl_mem d_img = nullptr; + // Size of quantized values. + size_t size_q = 0; + // Size of scales. + size_t size_d = 0; + + ~ggml_tensor_extra_cl_q4_0() { + reset(); + } + + void reset() { + // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. + // They must be properly released so that the original buffer can be + // properly released to avoid memory leak. + if (q != nullptr) { + CL_CHECK(clReleaseMemObject(q)); + q = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (q_img != nullptr) { + CL_CHECK(clReleaseMemObject(q_img)); + q_img = nullptr; + } + if (d_img != nullptr) { + CL_CHECK(clReleaseMemObject(d_img)); + d_img = nullptr; + } + size_q = 0; + size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_q4_1 { + // Quantized values. + cl_mem q = nullptr; + // Quantized values in image1d_buffer_t. + cl_mem q_img = nullptr; + // Scales. + cl_mem d = nullptr; + // Scales in image1d_buffer_t. + cl_mem d_img = nullptr; + // Min + cl_mem m = nullptr; + // Min in image1d_buffer_t. + cl_mem m_img = nullptr; + // Size of quantized values. + size_t size_q = 0; + // Size of scales. + size_t size_d = 0; + // Size of min values. + size_t size_m = 0; + + ~ggml_tensor_extra_cl_q4_1() { + reset(); + } + + void reset() { + // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. + // They must be properly released so that the original buffer can be + // properly released to avoid memory leak. + if (q != nullptr) { + CL_CHECK(clReleaseMemObject(q)); + q = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (m != nullptr) { + CL_CHECK(clReleaseMemObject(m)); + m = nullptr; + } + if (q_img != nullptr) { + CL_CHECK(clReleaseMemObject(q_img)); + q_img = nullptr; + } + // Currently, q_img and d_img are only initialized when SMALL_ALLOC is + // enabled. They point to the images in ggml_backend_opencl_buffer_context. + // So, there is no need to release them here. + // TODO: initialize them for non SMALL_PATH path, or remove them. + d_img = nullptr; + m_img = nullptr; + size_q = 0; + size_d = 0; + size_m = 0; + } +}; + +struct ggml_tensor_extra_cl_q5_0 { + // Quantized values. + cl_mem qs = nullptr; + // Quantized values in image1d_buffer_t. + cl_mem qs_img = nullptr; + // 5-th bit values. + cl_mem qh = nullptr; + // 5-th bit values in image1d_buffer_t. + cl_mem qh_img = nullptr; + // Scales. + cl_mem d = nullptr; + // Scales in image1d_buffer_t. + cl_mem d_img = nullptr; + // Uniform per-32-block scale (2/block) + min (1/block, = d*16 for the -16 centering) + // for the generic dp4a MoE GEMM. Built from d. + cl_mem scale = nullptr; + cl_mem min = nullptr; + // Size of quantized values. + size_t size_qs = 0; + // Size of 5-th bit values. + size_t size_qh = 0; + // Size of scales. + size_t size_d = 0; + + ~ggml_tensor_extra_cl_q5_0() { + reset(); + } + + void reset() { + if (qs != nullptr) { + CL_CHECK(clReleaseMemObject(qs)); + qs = nullptr; + } + if (qh != nullptr) { + CL_CHECK(clReleaseMemObject(qh)); + qh = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (qs_img != nullptr) { + CL_CHECK(clReleaseMemObject(qs_img)); + qs_img = nullptr; + } + if (scale != nullptr) { + CL_CHECK(clReleaseMemObject(scale)); + scale = nullptr; + } + if (min != nullptr) { + CL_CHECK(clReleaseMemObject(min)); + min = nullptr; + } + + qh_img = nullptr; + d_img = nullptr; + size_qs = 0; + size_qh = 0; + size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_q5_1 { + // Quantized values. + cl_mem qs = nullptr; + // Quantized values in image1d_buffer_t. + cl_mem qs_img = nullptr; + // 5-th bit values. + cl_mem qh = nullptr; + // 5-th bit values in image1d_buffer_t. + cl_mem qh_img = nullptr; + // Scales. + cl_mem d = nullptr; + // Scales in image1d_buffer_t. + cl_mem d_img = nullptr; + // Min + cl_mem m = nullptr; + // Min in image1d_buffer_t. + cl_mem m_img = nullptr; + // Size of quantized values. + size_t size_qs = 0; + // Size of 5-th bit values. + size_t size_qh = 0; + // Size of scales. + size_t size_d = 0; + // Size of min values. + size_t size_m = 0; + + ~ggml_tensor_extra_cl_q5_1() { + reset(); + } + + void reset() { + // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. + // They must be properly released so that the original buffer can be + // properly released to avoid memory leak. + if (qs != nullptr) { + CL_CHECK(clReleaseMemObject(qs)); + qs = nullptr; + } + if (qh != nullptr) { + CL_CHECK(clReleaseMemObject(qh)); + qh = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (m != nullptr) { + CL_CHECK(clReleaseMemObject(m)); + m = nullptr; + } + if (qs_img != nullptr) { + CL_CHECK(clReleaseMemObject(qs_img)); + qs_img = nullptr; + } + // qh_img, d_img, and m_img are not currently allocated separately. + // TODO: initialize them for non SMALL_PATH path, or remove them. + qh_img = nullptr; + d_img = nullptr; + m_img = nullptr; + size_qs = 0; + size_qh = 0; + size_d = 0; + size_m = 0; + } +}; + +struct ggml_tensor_extra_cl_mxfp4 { + // Quantized values. + cl_mem q = nullptr; + // Quantized values in image1d_buffer_t. + cl_mem q_img = nullptr; + // Scales in E8M0. + cl_mem e = nullptr; + // Scales in image1d_buffer_t. + cl_mem e_img = nullptr; + // Size of quantized values. + size_t size_q = 0; + // Size of scales. + size_t size_e = 0; + + ~ggml_tensor_extra_cl_mxfp4() { + reset(); + } + + void reset() { + // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. + // They must be properly released so that the original buffer can be + // properly released to avoid memory leak. + if (q != nullptr) { + CL_CHECK(clReleaseMemObject(q)); + q = nullptr; + } + if (e != nullptr) { + CL_CHECK(clReleaseMemObject(e)); + e = nullptr; + } + if (q_img != nullptr) { + CL_CHECK(clReleaseMemObject(q_img)); + q_img = nullptr; + } + // Currently, e_img is not used. They can be image1d_buffer_t + // that wraps around q and d to utilize image access path. + e_img = nullptr; + size_q = 0; + size_e = 0; + } +}; + +struct ggml_tensor_extra_cl_q8_0 { + cl_mem q = nullptr; + cl_mem q_img = nullptr; + + cl_mem d = nullptr; + cl_mem d_img = nullptr; + + // Uniform per-16-segment scale (16/superblock) for the generic dp4a MoE GEMM. + // Expanded from d at set_tensor; the int8 codes are reused from q. + // q8_0 is symmetric so no min buffer (has_min=0). + cl_mem scale = nullptr; + + size_t size_q = 0; + size_t size_d = 0; + + ~ggml_tensor_extra_cl_q8_0() { + reset(); + } + + void reset() { + // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. + // They must be properly released so that the original buffer can be + // properly released to avoid memory leak. + if (q != nullptr) { + CL_CHECK(clReleaseMemObject(q)); + q = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (scale != nullptr) { + CL_CHECK(clReleaseMemObject(scale)); + scale = nullptr; + } + // Currently, q_img and d_img are not used. They can be image1d_buffer_t + // that wraps around q and d to utilize image access path. + q_img = nullptr; + d_img = nullptr; + size_q = 0; + size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq4_nl { + cl_mem q = nullptr; + cl_mem q_img = nullptr; + + cl_mem d = nullptr; + cl_mem d_img = nullptr; + + size_t size_q = 0; + size_t size_d = 0; + + ~ggml_tensor_extra_cl_iq4_nl() { + reset(); + } + + void reset() { + if (q != nullptr) { CL_CHECK(clReleaseMemObject(q)); q = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + q_img = nullptr; + d_img = nullptr; + size_q = 0; + size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_q4_K { + // Quantized values + cl_mem q = nullptr; + // Quantized values in image1d_buffer_t. + cl_mem q_img = nullptr; + // Scales for each super block. + cl_mem s = nullptr; + // Scales + cl_mem d = nullptr; + // Min + cl_mem dm = nullptr; + + ~ggml_tensor_extra_cl_q4_K() { + reset(); + } + + void reset() { + if (q != nullptr) { + CL_CHECK(clReleaseMemObject(q)); + q = nullptr; + } + if (s != nullptr) { + CL_CHECK(clReleaseMemObject(s)); + s = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (dm != nullptr) { + CL_CHECK(clReleaseMemObject(dm)); + dm = nullptr; + } + if (q_img != nullptr) { + CL_CHECK(clReleaseMemObject(q_img)); + q_img = nullptr; + } + } +}; + +struct ggml_tensor_extra_cl_q5_K { + // Lower 4 bits of quantized weights. + cl_mem q = nullptr; + // Quantized values in image1d_buffer_t. + cl_mem q_img = nullptr; + // Upper 1 bit of quantized weights. + cl_mem qh = nullptr; + // Scales for each block. + cl_mem s = nullptr; + // Scales for each super block. + cl_mem d = nullptr; + // Min for each super block. + cl_mem dm = nullptr; + // Uniform per-32-block scale (2/block) + min (1/block, = dm*mn) decoded from the + // 6-bit packed s[] for the generic dp4a MoE GEMM kernel_gemm_moe_q8_1_dp4a. + // Built from s/d/dm at set_tensor; q/qh are reused as-is. + cl_mem scale = nullptr; + cl_mem min = nullptr; + + size_t size_q = 0; + size_t size_qh = 0; + size_t size_s = 0; + size_t size_d = 0; + size_t size_dm = 0; + + ~ggml_tensor_extra_cl_q5_K() { + reset(); + } + + void reset() { + if (q != nullptr) { + CL_CHECK(clReleaseMemObject(q)); + q = nullptr; + } + if (qh != nullptr) { + CL_CHECK(clReleaseMemObject(qh)); + qh = nullptr; + } + if (s != nullptr) { + CL_CHECK(clReleaseMemObject(s)); + s = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (dm != nullptr) { + CL_CHECK(clReleaseMemObject(dm)); + dm = nullptr; + } + if (q_img != nullptr) { + CL_CHECK(clReleaseMemObject(q_img)); + q_img = nullptr; + } + if (scale != nullptr) { + CL_CHECK(clReleaseMemObject(scale)); + scale = nullptr; + } + if (min != nullptr) { + CL_CHECK(clReleaseMemObject(min)); + min = nullptr; + } + + size_q = 0; + size_qh = 0; + size_s = 0; + size_d = 0; + size_dm = 0; + } +}; + +struct ggml_tensor_extra_cl_q2_K { + bool noshuffle = false; + cl_mem qs = nullptr; // quantized values + cl_mem sc = nullptr; // one uchar per 16 weights: scale nibble + min nibble + cl_mem dm = nullptr; // half2 per super-block: d, dmin + + size_t size_qs = 0, size_sc = 0, size_dm = 0; + + ~ggml_tensor_extra_cl_q2_K() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } + if (dm != nullptr) { CL_CHECK(clReleaseMemObject(dm)); dm = nullptr; } + size_qs = size_sc = size_dm = 0; + } +}; + +struct ggml_tensor_extra_cl_q3_K { + bool noshuffle = false; + cl_mem qs = nullptr; // quantized values + cl_mem hm = nullptr; // high bits + cl_mem sc = nullptr; // packed 6-bit scales + cl_mem d = nullptr; // super-block scales + + size_t size_qs = 0, size_hm = 0, size_sc = 0, size_d = 0; + + ~ggml_tensor_extra_cl_q3_K() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (hm != nullptr) { CL_CHECK(clReleaseMemObject(hm)); hm = nullptr; } + if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_hm = size_sc = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq3_xxs { + bool noshuffle = false; + cl_mem qs = nullptr; // grid indices + cl_mem sas = nullptr; // packed sign codes and scales + cl_mem d = nullptr; // super-block scales + + size_t size_qs = 0, size_sas = 0, size_d = 0; + + ~ggml_tensor_extra_cl_iq3_xxs() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (sas != nullptr) { CL_CHECK(clReleaseMemObject(sas)); sas = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_sas = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq3_s { + bool noshuffle = false; + cl_mem qs = nullptr; // grid index low bits + cl_mem sg = nullptr; // sign bits + cl_mem qh = nullptr; // grid index high bits + cl_mem sc = nullptr; // packed scales + cl_mem d = nullptr; // super-block scales + + size_t size_qs = 0, size_sg = 0, size_qh = 0, size_sc = 0, size_d = 0; + + ~ggml_tensor_extra_cl_iq3_s() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (sg != nullptr) { CL_CHECK(clReleaseMemObject(sg)); sg = nullptr; } + if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } + if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_sg = size_qh = size_sc = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq2_xxs { + bool noshuffle = false; + cl_mem qs = nullptr; // grid indices + cl_mem sas = nullptr; // packed sign codes and scales + cl_mem d = nullptr; // super-block scales + + size_t size_qs = 0, size_sas = 0, size_d = 0; + + ~ggml_tensor_extra_cl_iq2_xxs() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (sas != nullptr) { CL_CHECK(clReleaseMemObject(sas)); sas = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_sas = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq2_xs { + bool noshuffle = false; + cl_mem qs = nullptr; // packed grid indices and sign codes + cl_mem sc = nullptr; // packed scales + cl_mem d = nullptr; // super-block scales + + size_t size_qs = 0, size_sc = 0, size_d = 0; + + ~ggml_tensor_extra_cl_iq2_xs() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_sc = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq2_s { + bool noshuffle = false; + cl_mem qs = nullptr; // grid index low bits + cl_mem sg = nullptr; // sign bits + cl_mem qh = nullptr; // grid index high bits + cl_mem sc = nullptr; // packed scales + cl_mem d = nullptr; // super-block scales + + size_t size_qs = 0, size_sg = 0, size_qh = 0, size_sc = 0, size_d = 0; + + ~ggml_tensor_extra_cl_iq2_s() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (sg != nullptr) { CL_CHECK(clReleaseMemObject(sg)); sg = nullptr; } + if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } + if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_sg = size_qh = size_sc = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_q2_0 { + bool noshuffle = false; + cl_mem qs = nullptr; + cl_mem d = nullptr; + + size_t size_qs = 0, size_d = 0; + + ~ggml_tensor_extra_cl_q2_0() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq1_s { + bool noshuffle = false; + cl_mem qs = nullptr; // grid indices + cl_mem qh = nullptr; // high grid bits, scales, and shifts + cl_mem d = nullptr; // super-block scales + + size_t size_qs = 0, size_qh = 0, size_d = 0; + + ~ggml_tensor_extra_cl_iq1_s() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_qh = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_iq1_m { + bool noshuffle = false; + cl_mem qs = nullptr; // grid indices + cl_mem qh = nullptr; // high grid bits and shifts + cl_mem sc = nullptr; // packed block and super-block scales + + size_t size_qs = 0, size_qh = 0, size_sc = 0; + + ~ggml_tensor_extra_cl_iq1_m() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } + if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } + size_qs = size_qh = size_sc = 0; + } +}; + +struct ggml_tensor_extra_cl_iq4_xs { + bool noshuffle = false; + cl_mem qs = nullptr; + cl_mem sl = nullptr; + cl_mem sh = nullptr; + cl_mem d = nullptr; + + size_t size_qs = 0, size_sl = 0, size_sh = 0, size_d = 0; + + ~ggml_tensor_extra_cl_iq4_xs() { reset(); } + + void reset() { + noshuffle = false; + if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } + if (sl != nullptr) { CL_CHECK(clReleaseMemObject(sl)); sl = nullptr; } + if (sh != nullptr) { CL_CHECK(clReleaseMemObject(sh)); sh = nullptr; } + if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } + size_qs = size_sl = size_sh = size_d = 0; + } +}; + +struct ggml_tensor_extra_cl_q6_K { + // Lower 4 bits of quantized weights. + cl_mem ql = nullptr; + // Lower 4 bits as image1d_buffer_t + cl_mem ql_img = nullptr; + // Upper 2 bits of quantized weights. + cl_mem qh = nullptr; + // Upper 2 bits as image1d_buffer_t + cl_mem qh_img = nullptr; + // Scales for each block. + cl_mem s = nullptr; + // Scales for each super block. + cl_mem d = nullptr; + + size_t size_ql = 0; + size_t size_qh = 0; + size_t size_s = 0; + size_t size_d = 0; + + ~ggml_tensor_extra_cl_q6_K() { + reset(); + } + + void reset() { + if (ql != nullptr) { + CL_CHECK(clReleaseMemObject(ql)); + ql = nullptr; + } + if (qh != nullptr) { + CL_CHECK(clReleaseMemObject(qh)); + qh = nullptr; + } + if (s != nullptr) { + CL_CHECK(clReleaseMemObject(s)); + s = nullptr; + } + if (d != nullptr) { + CL_CHECK(clReleaseMemObject(d)); + d = nullptr; + } + if (ql_img != nullptr) { + CL_CHECK(clReleaseMemObject(ql_img)); + ql_img = nullptr; + } + if (qh_img != nullptr) { + CL_CHECK(clReleaseMemObject(qh_img)); + qh_img = nullptr; + } + + size_ql = 0; + size_qh = 0; + size_s = 0; + size_d = 0; + } +}; +struct ggml_backend_opencl_buffer_context { + // A buffer context can hold multiple cl_mem objects. This is for flattening + // quantized weights and should be used with GGML_OPENCL_SMALL_ALLOC where + // each tensor is allocated a separate buffer. When flattening is enabled + // with small allocation, each tensor is backed by two cl_mem objects (for + // quants and scales) packed into a backend_opencl_buffer. + ggml_backend_opencl_buffer_context(cl_mem buf) + : name("OpenCL") { + buffer.push_back(buf); + } + + ~ggml_backend_opencl_buffer_context() { + for (cl_mem buf : buffer) { + CL_CHECK(clReleaseMemObject(buf)); + } + for (cl_mem im : img) { + CL_CHECK(clReleaseMemObject(im)); + } + + // Delete all extras to trigger their destructors + for (ggml_tensor_extra_cl * e : temp_tensor_extras) { + delete e; + } + for (ggml_tensor_extra_cl * e : temp_tensor_extras_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q4_0 * e : temp_tensor_extras_q4_0) { + delete e; + } + for (ggml_tensor_extra_cl_q4_0 * e : temp_tensor_extras_q4_0_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q4_1 * e : temp_tensor_extras_q4_1) { + delete e; + } + for (ggml_tensor_extra_cl_q4_1 * e : temp_tensor_extras_q4_1_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q5_0 * e : temp_tensor_extras_q5_0) { + delete e; + } + for (ggml_tensor_extra_cl_q5_0 * e : temp_tensor_extras_q5_0_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q5_1 * e : temp_tensor_extras_q5_1) { + delete e; + } + for (ggml_tensor_extra_cl_q5_1 * e : temp_tensor_extras_q5_1_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_mxfp4 * e : temp_tensor_extras_mxfp4) { + delete e; + } + for (ggml_tensor_extra_cl_mxfp4 * e : temp_tensor_extras_mxfp4_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q8_0 * e : temp_tensor_extras_q8_0) { + delete e; + } + for (ggml_tensor_extra_cl_q8_0 * e : temp_tensor_extras_q8_0_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q1_0 * e : temp_tensor_extras_q1_0) { + delete e; + } + for (ggml_tensor_extra_cl_q1_0 * e : temp_tensor_extras_q1_0_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq4_nl * e : temp_tensor_extras_iq4_nl) { + delete e; + } + for (ggml_tensor_extra_cl_iq4_nl * e : temp_tensor_extras_iq4_nl_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q4_K * e : temp_tensor_extras_q4_K) { + delete e; + } + for (ggml_tensor_extra_cl_q4_K * e : temp_tensor_extras_q4_K_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q6_K * e : temp_tensor_extras_q6_K) { + delete e; + } + for (ggml_tensor_extra_cl_q2_K * e : temp_tensor_extras_q2_K) { + delete e; + } + for (ggml_tensor_extra_cl_q3_K * e : temp_tensor_extras_q3_K) { + delete e; + } + for (ggml_tensor_extra_cl_iq2_s * e : temp_tensor_extras_iq2_s) { + delete e; + } + for (ggml_tensor_extra_cl_iq2_xs * e : temp_tensor_extras_iq2_xs) { + delete e; + } + for (ggml_tensor_extra_cl_iq2_xxs * e : temp_tensor_extras_iq2_xxs) { + delete e; + } + for (ggml_tensor_extra_cl_q2_0 * e : temp_tensor_extras_q2_0) { + delete e; + } + for (ggml_tensor_extra_cl_iq1_m * e : temp_tensor_extras_iq1_m) { + delete e; + } + for (ggml_tensor_extra_cl_iq1_s * e : temp_tensor_extras_iq1_s) { + delete e; + } + for (ggml_tensor_extra_cl_iq3_s * e : temp_tensor_extras_iq3_s) { + delete e; + } + for (ggml_tensor_extra_cl_iq3_xxs * e : temp_tensor_extras_iq3_xxs) { + delete e; + } + for (ggml_tensor_extra_cl_iq4_xs * e : temp_tensor_extras_iq4_xs) { + delete e; + } + for (ggml_tensor_extra_cl_q6_K * e : temp_tensor_extras_q6_K_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q2_K * e : temp_tensor_extras_q2_K_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q3_K * e : temp_tensor_extras_q3_K_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq2_s * e : temp_tensor_extras_iq2_s_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq2_xs * e : temp_tensor_extras_iq2_xs_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq2_xxs * e : temp_tensor_extras_iq2_xxs_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q2_0 * e : temp_tensor_extras_q2_0_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq1_m * e : temp_tensor_extras_iq1_m_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq1_s * e : temp_tensor_extras_iq1_s_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq3_s * e : temp_tensor_extras_iq3_s_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq3_xxs * e : temp_tensor_extras_iq3_xxs_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_iq4_xs * e : temp_tensor_extras_iq4_xs_in_use) { + delete e; + } + for (ggml_tensor_extra_cl_q5_K * e : temp_tensor_extras_q5_K) { + delete e; + } + for (ggml_tensor_extra_cl_q5_K * e : temp_tensor_extras_q5_K_in_use) { + delete e; + } + } + + ggml_tensor_extra_cl * ggml_opencl_alloc_temp_tensor_extra() { + ggml_tensor_extra_cl * extra; + if (temp_tensor_extras.empty()) { + extra = new ggml_tensor_extra_cl(); + } else { + extra = temp_tensor_extras.back(); + temp_tensor_extras.pop_back(); + } + + temp_tensor_extras_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q1_0 * ggml_opencl_alloc_temp_tensor_extra_q1_0() { + ggml_tensor_extra_cl_q1_0 * extra; + if (temp_tensor_extras_q1_0.empty()) { + extra = new ggml_tensor_extra_cl_q1_0(); + } else { + extra = temp_tensor_extras_q1_0.back(); + temp_tensor_extras_q1_0.pop_back(); + } + + temp_tensor_extras_q1_0_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q4_0 * ggml_opencl_alloc_temp_tensor_extra_q4_0() { + ggml_tensor_extra_cl_q4_0 * extra; + if (temp_tensor_extras_q4_0.empty()) { + extra = new ggml_tensor_extra_cl_q4_0(); + } else { + extra = temp_tensor_extras_q4_0.back(); + temp_tensor_extras_q4_0.pop_back(); + } + + temp_tensor_extras_q4_0_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q4_1 * ggml_opencl_alloc_temp_tensor_extra_q4_1() { + ggml_tensor_extra_cl_q4_1 * extra; + if (temp_tensor_extras_q4_1.empty()) { + extra = new ggml_tensor_extra_cl_q4_1(); + } else { + extra = temp_tensor_extras_q4_1.back(); + temp_tensor_extras_q4_1.pop_back(); + } + + temp_tensor_extras_q4_1_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q5_0 * ggml_opencl_alloc_temp_tensor_extra_q5_0() { + ggml_tensor_extra_cl_q5_0 * extra; + if (temp_tensor_extras_q5_0.empty()) { + extra = new ggml_tensor_extra_cl_q5_0(); + } else { + extra = temp_tensor_extras_q5_0.back(); + temp_tensor_extras_q5_0.pop_back(); + } + + temp_tensor_extras_q5_0_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q5_1 * ggml_opencl_alloc_temp_tensor_extra_q5_1() { + ggml_tensor_extra_cl_q5_1 * extra; + if (temp_tensor_extras_q5_1.empty()) { + extra = new ggml_tensor_extra_cl_q5_1(); + } else { + extra = temp_tensor_extras_q5_1.back(); + temp_tensor_extras_q5_1.pop_back(); + } + + temp_tensor_extras_q5_1_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_mxfp4 * ggml_opencl_alloc_temp_tensor_extra_mxfp4() { + ggml_tensor_extra_cl_mxfp4 * extra; + if (temp_tensor_extras_mxfp4.empty()) { + extra = new ggml_tensor_extra_cl_mxfp4(); + } else { + extra = temp_tensor_extras_mxfp4.back(); + temp_tensor_extras_mxfp4.pop_back(); + } + + temp_tensor_extras_mxfp4_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q8_0 * ggml_opencl_alloc_temp_tensor_extra_q8_0() { + ggml_tensor_extra_cl_q8_0 * extra; + if (temp_tensor_extras_q8_0.empty()) { + extra = new ggml_tensor_extra_cl_q8_0(); + } else { + extra = temp_tensor_extras_q8_0.back(); + temp_tensor_extras_q8_0.pop_back(); + } + + temp_tensor_extras_q8_0_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq4_nl * ggml_opencl_alloc_temp_tensor_extra_iq4_nl() { + ggml_tensor_extra_cl_iq4_nl * extra; + if (temp_tensor_extras_iq4_nl.empty()) { + extra = new ggml_tensor_extra_cl_iq4_nl(); + } else { + extra = temp_tensor_extras_iq4_nl.back(); + temp_tensor_extras_iq4_nl.pop_back(); + } + + temp_tensor_extras_iq4_nl_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q4_K * ggml_opencl_alloc_temp_tensor_extra_q4_K() { + ggml_tensor_extra_cl_q4_K * extra; + if (temp_tensor_extras_q4_K.empty()) { + extra = new ggml_tensor_extra_cl_q4_K(); + } else { + extra = temp_tensor_extras_q4_K.back(); + temp_tensor_extras_q4_K.pop_back(); + } + + temp_tensor_extras_q4_K_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q5_K * ggml_opencl_alloc_temp_tensor_extra_q5_K() { + ggml_tensor_extra_cl_q5_K * extra; + if (temp_tensor_extras_q5_K.empty()) { + extra = new ggml_tensor_extra_cl_q5_K(); + } else { + extra = temp_tensor_extras_q5_K.back(); + temp_tensor_extras_q5_K.pop_back(); + } + + temp_tensor_extras_q5_K_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q2_K * ggml_opencl_alloc_temp_tensor_extra_q2_K() { + ggml_tensor_extra_cl_q2_K * extra; + if (temp_tensor_extras_q2_K.empty()) { + extra = new ggml_tensor_extra_cl_q2_K(); + } else { + extra = temp_tensor_extras_q2_K.back(); + temp_tensor_extras_q2_K.pop_back(); + } + + temp_tensor_extras_q2_K_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q3_K * ggml_opencl_alloc_temp_tensor_extra_q3_K() { + ggml_tensor_extra_cl_q3_K * extra; + if (temp_tensor_extras_q3_K.empty()) { + extra = new ggml_tensor_extra_cl_q3_K(); + } else { + extra = temp_tensor_extras_q3_K.back(); + temp_tensor_extras_q3_K.pop_back(); + } + + temp_tensor_extras_q3_K_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq2_s * ggml_opencl_alloc_temp_tensor_extra_iq2_s() { + ggml_tensor_extra_cl_iq2_s * extra; + if (temp_tensor_extras_iq2_s.empty()) { + extra = new ggml_tensor_extra_cl_iq2_s(); + } else { + extra = temp_tensor_extras_iq2_s.back(); + temp_tensor_extras_iq2_s.pop_back(); + } + + temp_tensor_extras_iq2_s_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq2_xs * ggml_opencl_alloc_temp_tensor_extra_iq2_xs() { + ggml_tensor_extra_cl_iq2_xs * extra; + if (temp_tensor_extras_iq2_xs.empty()) { + extra = new ggml_tensor_extra_cl_iq2_xs(); + } else { + extra = temp_tensor_extras_iq2_xs.back(); + temp_tensor_extras_iq2_xs.pop_back(); + } + + temp_tensor_extras_iq2_xs_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq2_xxs * ggml_opencl_alloc_temp_tensor_extra_iq2_xxs() { + ggml_tensor_extra_cl_iq2_xxs * extra; + if (temp_tensor_extras_iq2_xxs.empty()) { + extra = new ggml_tensor_extra_cl_iq2_xxs(); + } else { + extra = temp_tensor_extras_iq2_xxs.back(); + temp_tensor_extras_iq2_xxs.pop_back(); + } + + temp_tensor_extras_iq2_xxs_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q2_0 * ggml_opencl_alloc_temp_tensor_extra_q2_0() { + ggml_tensor_extra_cl_q2_0 * extra; + if (temp_tensor_extras_q2_0.empty()) { + extra = new ggml_tensor_extra_cl_q2_0(); + } else { + extra = temp_tensor_extras_q2_0.back(); + temp_tensor_extras_q2_0.pop_back(); + } + + temp_tensor_extras_q2_0_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq1_m * ggml_opencl_alloc_temp_tensor_extra_iq1_m() { + ggml_tensor_extra_cl_iq1_m * extra; + if (temp_tensor_extras_iq1_m.empty()) { + extra = new ggml_tensor_extra_cl_iq1_m(); + } else { + extra = temp_tensor_extras_iq1_m.back(); + temp_tensor_extras_iq1_m.pop_back(); + } + + temp_tensor_extras_iq1_m_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq1_s * ggml_opencl_alloc_temp_tensor_extra_iq1_s() { + ggml_tensor_extra_cl_iq1_s * extra; + if (temp_tensor_extras_iq1_s.empty()) { + extra = new ggml_tensor_extra_cl_iq1_s(); + } else { + extra = temp_tensor_extras_iq1_s.back(); + temp_tensor_extras_iq1_s.pop_back(); + } + + temp_tensor_extras_iq1_s_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq3_s * ggml_opencl_alloc_temp_tensor_extra_iq3_s() { + ggml_tensor_extra_cl_iq3_s * extra; + if (temp_tensor_extras_iq3_s.empty()) { + extra = new ggml_tensor_extra_cl_iq3_s(); + } else { + extra = temp_tensor_extras_iq3_s.back(); + temp_tensor_extras_iq3_s.pop_back(); + } + + temp_tensor_extras_iq3_s_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq3_xxs * ggml_opencl_alloc_temp_tensor_extra_iq3_xxs() { + ggml_tensor_extra_cl_iq3_xxs * extra; + if (temp_tensor_extras_iq3_xxs.empty()) { + extra = new ggml_tensor_extra_cl_iq3_xxs(); + } else { + extra = temp_tensor_extras_iq3_xxs.back(); + temp_tensor_extras_iq3_xxs.pop_back(); + } + + temp_tensor_extras_iq3_xxs_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_iq4_xs * ggml_opencl_alloc_temp_tensor_extra_iq4_xs() { + ggml_tensor_extra_cl_iq4_xs * extra; + if (temp_tensor_extras_iq4_xs.empty()) { + extra = new ggml_tensor_extra_cl_iq4_xs(); + } else { + extra = temp_tensor_extras_iq4_xs.back(); + temp_tensor_extras_iq4_xs.pop_back(); + } + + temp_tensor_extras_iq4_xs_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + ggml_tensor_extra_cl_q6_K * ggml_opencl_alloc_temp_tensor_extra_q6_K() { + ggml_tensor_extra_cl_q6_K * extra; + if (temp_tensor_extras_q6_K.empty()) { + extra = new ggml_tensor_extra_cl_q6_K(); + } else { + extra = temp_tensor_extras_q6_K.back(); + temp_tensor_extras_q6_K.pop_back(); + } + + temp_tensor_extras_q6_K_in_use.push_back(extra); + + extra->reset(); + return extra; + } + + void reset() { + for (ggml_tensor_extra_cl * e : temp_tensor_extras_in_use) { + temp_tensor_extras.push_back(e); + } + temp_tensor_extras_in_use.clear(); + + for (ggml_tensor_extra_cl_q1_0 * e : temp_tensor_extras_q1_0_in_use) { + temp_tensor_extras_q1_0.push_back(e); + } + temp_tensor_extras_q1_0_in_use.clear(); + + for (ggml_tensor_extra_cl_q4_0 * e : temp_tensor_extras_q4_0_in_use) { + temp_tensor_extras_q4_0.push_back(e); + } + temp_tensor_extras_q4_0_in_use.clear(); + + for (ggml_tensor_extra_cl_q4_1 * e : temp_tensor_extras_q4_1_in_use) { + temp_tensor_extras_q4_1.push_back(e); + } + temp_tensor_extras_q4_1_in_use.clear(); + + for (ggml_tensor_extra_cl_q5_0 * e : temp_tensor_extras_q5_0_in_use) { + temp_tensor_extras_q5_0.push_back(e); + } + temp_tensor_extras_q5_0_in_use.clear(); + + for (ggml_tensor_extra_cl_q5_1 * e : temp_tensor_extras_q5_1_in_use) { + temp_tensor_extras_q5_1.push_back(e); + } + temp_tensor_extras_q5_1_in_use.clear(); + + for (ggml_tensor_extra_cl_mxfp4 * e : temp_tensor_extras_mxfp4_in_use) { + temp_tensor_extras_mxfp4.push_back(e); + } + temp_tensor_extras_mxfp4_in_use.clear(); + + for (ggml_tensor_extra_cl_q8_0 * e : temp_tensor_extras_q8_0_in_use) { + temp_tensor_extras_q8_0.push_back(e); + } + temp_tensor_extras_q8_0_in_use.clear(); + + for (ggml_tensor_extra_cl_iq4_nl * e : temp_tensor_extras_iq4_nl_in_use) { + temp_tensor_extras_iq4_nl.push_back(e); + } + temp_tensor_extras_iq4_nl_in_use.clear(); + + for (ggml_tensor_extra_cl_q4_K * e : temp_tensor_extras_q4_K_in_use) { + temp_tensor_extras_q4_K.push_back(e); + } + temp_tensor_extras_q4_K_in_use.clear(); + + for (ggml_tensor_extra_cl_q5_K * e : temp_tensor_extras_q5_K_in_use) { + temp_tensor_extras_q5_K.push_back(e); + } + temp_tensor_extras_q5_K_in_use.clear(); + + for (ggml_tensor_extra_cl_q6_K * e : temp_tensor_extras_q6_K_in_use) { + temp_tensor_extras_q6_K.push_back(e); + } + temp_tensor_extras_q6_K_in_use.clear(); + + for (ggml_tensor_extra_cl_q2_K * e : temp_tensor_extras_q2_K_in_use) { + temp_tensor_extras_q2_K.push_back(e); + } + temp_tensor_extras_q2_K_in_use.clear(); + + for (ggml_tensor_extra_cl_q3_K * e : temp_tensor_extras_q3_K_in_use) { + temp_tensor_extras_q3_K.push_back(e); + } + temp_tensor_extras_q3_K_in_use.clear(); + + for (ggml_tensor_extra_cl_iq2_s * e : temp_tensor_extras_iq2_s_in_use) { + temp_tensor_extras_iq2_s.push_back(e); + } + temp_tensor_extras_iq2_s_in_use.clear(); + + for (ggml_tensor_extra_cl_iq2_xs * e : temp_tensor_extras_iq2_xs_in_use) { + temp_tensor_extras_iq2_xs.push_back(e); + } + temp_tensor_extras_iq2_xs_in_use.clear(); + + for (ggml_tensor_extra_cl_iq2_xxs * e : temp_tensor_extras_iq2_xxs_in_use) { + temp_tensor_extras_iq2_xxs.push_back(e); + } + temp_tensor_extras_iq2_xxs_in_use.clear(); + + for (ggml_tensor_extra_cl_q2_0 * e : temp_tensor_extras_q2_0_in_use) { + temp_tensor_extras_q2_0.push_back(e); + } + temp_tensor_extras_q2_0_in_use.clear(); + + for (ggml_tensor_extra_cl_iq1_m * e : temp_tensor_extras_iq1_m_in_use) { + temp_tensor_extras_iq1_m.push_back(e); + } + temp_tensor_extras_iq1_m_in_use.clear(); + + for (ggml_tensor_extra_cl_iq1_s * e : temp_tensor_extras_iq1_s_in_use) { + temp_tensor_extras_iq1_s.push_back(e); + } + temp_tensor_extras_iq1_s_in_use.clear(); + + for (ggml_tensor_extra_cl_iq3_s * e : temp_tensor_extras_iq3_s_in_use) { + temp_tensor_extras_iq3_s.push_back(e); + } + temp_tensor_extras_iq3_s_in_use.clear(); + + for (ggml_tensor_extra_cl_iq3_xxs * e : temp_tensor_extras_iq3_xxs_in_use) { + temp_tensor_extras_iq3_xxs.push_back(e); + } + temp_tensor_extras_iq3_xxs_in_use.clear(); + + for (ggml_tensor_extra_cl_iq4_xs * e : temp_tensor_extras_iq4_xs_in_use) { + temp_tensor_extras_iq4_xs.push_back(e); + } + temp_tensor_extras_iq4_xs_in_use.clear(); + + q8_0_soa_tensors.clear(); + q4_0_soa_tensors.clear(); + } + + // Pools for extras. Available extras are in `temp_tensor_extras`. Extras + // being used are in `temp_tensor_extras_in_use`. At the first run, new + // extras get created and put in `in_use`. When the buffer is reset via + // the `reset` callback, all extras in `in_use` get moved to available extras + // for reuse. + std::vector temp_tensor_extras; + std::vector temp_tensor_extras_in_use; + std::vector temp_tensor_extras_q1_0; + std::vector temp_tensor_extras_q1_0_in_use; + std::vector temp_tensor_extras_q4_0; + std::vector temp_tensor_extras_q4_0_in_use; + std::vector temp_tensor_extras_q4_1; + std::vector temp_tensor_extras_q4_1_in_use; + std::vector temp_tensor_extras_q5_0; + std::vector temp_tensor_extras_q5_0_in_use; + std::vector temp_tensor_extras_q5_1; + std::vector temp_tensor_extras_q5_1_in_use; + std::vector temp_tensor_extras_mxfp4; + std::vector temp_tensor_extras_mxfp4_in_use; + std::vector temp_tensor_extras_q8_0; + std::vector temp_tensor_extras_q8_0_in_use; + std::vector temp_tensor_extras_iq4_nl; + std::vector temp_tensor_extras_iq4_nl_in_use; + std::vector temp_tensor_extras_q4_K; + std::vector temp_tensor_extras_q4_K_in_use; + std::vector temp_tensor_extras_q5_K; + std::vector temp_tensor_extras_q5_K_in_use; + std::vector temp_tensor_extras_q2_K; + std::vector temp_tensor_extras_q3_K; + std::vector temp_tensor_extras_iq2_s; + std::vector temp_tensor_extras_iq2_xs; + std::vector temp_tensor_extras_iq2_xxs; + std::vector temp_tensor_extras_iq3_xxs; + std::vector temp_tensor_extras_q2_K_in_use; + std::vector temp_tensor_extras_q3_K_in_use; + std::vector temp_tensor_extras_iq2_s_in_use; + std::vector temp_tensor_extras_iq2_xs_in_use; + std::vector temp_tensor_extras_iq2_xxs_in_use; + std::vector temp_tensor_extras_q2_0; + std::vector temp_tensor_extras_q2_0_in_use; + std::vector temp_tensor_extras_iq1_s; + std::vector temp_tensor_extras_iq1_m; + std::vector temp_tensor_extras_iq1_m_in_use; + std::vector temp_tensor_extras_iq1_s_in_use; + std::vector temp_tensor_extras_iq3_s; + std::vector temp_tensor_extras_iq3_s_in_use; + std::vector temp_tensor_extras_iq3_xxs_in_use; + std::vector temp_tensor_extras_iq4_xs; + std::vector temp_tensor_extras_iq4_xs_in_use; + std::vector temp_tensor_extras_q6_K; + std::vector temp_tensor_extras_q6_K_in_use; + + // q8_0 tensors with AoS->SoA layout conversion installed by set_tensor. + // Two types of tensors get SOA'ed - normal weights and MoE weights. + // In Q8_0's case, we only have normal weights. If we ever have Q8_0 as MoE + // weights, they need to be added to this set in `set_tensors`. + std::unordered_set q8_0_soa_tensors; + + // Same for q4_0. KV-cache q4_0 tensors are allocated but never pass + // through set_tensor, so they stay AoS and aren't in this set. + // In Q4_0's case, in addition to normal weights, we have MoE weights. + std::unordered_set q4_0_soa_tensors; + + // The buffer_context is initially created by ggml_backend_buft_alloc_buffer + // before any tensor is initialized (at the beginning of alloc_tensor_range). + // Hence, there is always a buffer object in this vector. When each tensor is + // being initialized, this original buffer object will be released if both + // flattening and small allocation are enabled, and additional buffer + // objects will be created in init_tensor to represent flattened quantized + // weights. + std::vector buffer; + // These are image1d_buffer_t objects that wrap around the quants and scales. + // For Q4_0 quantization, there should be two of them - one for quants and + // one for scales. They should be populated only when flattening and small + // allocation are enabled. + std::vector img; + std::string name; +}; + +std::string read_file(const std::string & path); +cl_program build_program_from_source_ex( + cl_context ctx, cl_device_id dev, const char * program_buffer, + const std::string & compile_opts, bool fatal, + const char * tag = nullptr, cl_command_queue retry_queue = nullptr); +cl_program build_program_from_source( + ggml_backend_opencl_context * backend_ctx, const char * program_buffer, + const std::string & compile_opts, bool fatal = true); +cl_program build_program_from_binary( + cl_context ctx, cl_device_id dev, const char * program_buffer, + const std::string & compile_opts, size_t bin_size = 0); +bool use_adreno_bin_kernels(ggml_backend_opencl_context * backend_ctx); + +std::string ggml_opencl_make_compile_opts(const ggml_backend_opencl_context * backend_ctx); +void load_cl_kernels(ggml_backend_opencl_context * backend_ctx); +void sync_with_other_backends(ggml_backend_opencl_context * backend_ctx); +void sync_with_other_backends(ggml_backend_t backend); +void transpose_2d(ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, + cl_mem src, cl_mem dst, size_t size, cl_int stride, cl_int rows, + bool blocking = true, bool auto_local = false); +void transpose_2d_as_8b(ggml_backend_opencl_context * backend_ctx, cl_mem src, cl_mem dst, + size_t size, cl_int stride, cl_int rows, + bool blocking = true, bool rows_soa = false); +void transpose_2d_as_16b(ggml_backend_opencl_context * backend_ctx, cl_mem src, cl_mem dst, + size_t size, cl_int stride, cl_int rows, + bool blocking = true, bool auto_local = false); +void transpose_2d_as_32b(ggml_backend_opencl_context * backend_ctx, cl_mem src, cl_mem dst, + size_t size, cl_int stride, cl_int rows, + bool blocking = true, bool auto_local = false); +bool use_q4_0_bin_kernels(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_q4_k_bin_kernels(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_q5_k_bin_kernels(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_q6_k_bin_kernels(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_adreno_kernels(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_q2_k_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_q3_k_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_q2_0_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq2_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq2_xs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq2_xxs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq3_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq3_xxs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq1_m_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq1_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_iq4_xs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool adreno_e17_compiler_quirks(const ggml_backend_opencl_context * backend_ctx); +bool use_adreno_moe_kernels(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool enable_adreno_trans_weight(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_q6k_tiled(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_q4k_tiled(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool enable_adreno_trans_weight_q5_K(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_flat_gemv_for_large_m_q4_K(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool use_flat_gemv_for_large_m_q6_K(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor); +bool ggml_cl_is_q4_0_soa(const ggml_tensor * tensor); +bool ggml_cl_is_q8_0_soa(const ggml_tensor * tensor); +cl_mem ggml_cl_img_pool_get_or_create( + ggml_backend_opencl_context * backend_ctx, + std::map & pool, + cl_mem data_device, cl_ulong offset0, size_t required_bytes, + cl_channel_type channel_data_type); + +void ggml_backend_opencl_buffer_set_tensor( + ggml_backend_buffer_t buffer, ggml_tensor * tensor, + const void * data, size_t offset, size_t size); +void ggml_backend_opencl_buffer_get_tensor( + ggml_backend_buffer_t buffer, const ggml_tensor * tensor, + void * data, size_t offset, size_t size); + +extern std::vector g_ggml_backend_opencl_devices; +extern std::vector> g_ggml_backend_opencl_dev_ctxs; +extern struct ggml_backend_device_i ggml_backend_opencl_device_i; + +bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor); +void ggml_cl_load_kernels_repack(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_unpack(ggml_backend_opencl_context * backend_ctx); diff --git a/ggml/src/ggml-opencl/fa_tune.h b/ggml/src/ggml-opencl/fa_tune.h index 447f0cf7e04c..69c99c9081b3 100644 --- a/ggml/src/ggml-opencl/fa_tune.h +++ b/ggml/src/ggml-opencl/fa_tune.h @@ -3,8 +3,8 @@ // Flash-attention per-(dk,dv) tile tuning for the Adreno OpenCL backend. // Isolated from ggml-opencl.cpp so the tuning numbers are easy to find and // edit; the FA dispatch and kernel-compile logic stay in the main file. -// This header is a file section — it is #included exactly once, at the point -// in ggml-opencl.cpp where the ggml logging macros are already in scope. +// This header is a file section — it is #included exactly once by +// ops/flash_attn.cpp, where the ggml logging macros are already in scope. // Per-(dk, dv) FA config; shared by dispatch and supports_op. struct ggml_opencl_fa_dim { @@ -82,7 +82,7 @@ static void ggml_opencl_fa_apply_env_overrides() { // Copy the default table into the mutable runtime buffer and apply any // GGML_OPENCL_FA_TUNE overrides. A per-generation table can be added here // once it has been tuned on hardware. -static void ggml_cl_init_fa_dims_table() { +void ggml_cl_init_fa_dims_table() { const size_t count = sizeof(g_fa_dims_adreno_default) / sizeof(g_fa_dims_adreno_default[0]); for (size_t i = 0; i < count; ++i) { g_fa_dims_runtime[i] = g_fa_dims_adreno_default[i]; diff --git a/ggml/src/ggml-opencl/ggml-opencl.cpp b/ggml/src/ggml-opencl/ggml-opencl.cpp index 635dcc0114d6..8873b1ccd53d 100644 --- a/ggml/src/ggml-opencl/ggml-opencl.cpp +++ b/ggml/src/ggml-opencl/ggml-opencl.cpp @@ -1,41816 +1,2375 @@ -#define CL_TARGET_OPENCL_VERSION GGML_OPENCL_TARGET_VERSION -#define CL_USE_DEPRECATED_OPENCL_1_2_APIS - -// suppress warnings in CL headers for GCC and Clang -#pragma GCC diagnostic ignored "-Woverlength-strings" -#ifdef __clang__ -#pragma GCC diagnostic ignored "-Wgnu-anonymous-struct" -#endif - -#include "ggml-opencl.h" -#include "ggml-backend.h" -#include "ggml-impl.h" -#include "ggml-backend-impl.h" -#include "ggml.h" - -#include "cl-program-cache.h" - -#ifdef GGML_OPENCL_USE_ADRENO_BIN_KERNELS -#include "libdl.h" -#ifdef _WIN32 -#define KERNEL_LIB_NAME "adreno-opencl-kernels.dll" -#else -#define KERNEL_LIB_NAME "libadreno-opencl-kernels.so" -#endif // _WIN32 -#endif // GGML_OPENCL_USE_ADRENO_BIN_KERNELS - -typedef const void * (*get_adreno_bin_kernel_func_t)( - const char * name, - const char * gpu_name, - const char * compiler_ver, - size_t * out_size -); - -#include - -#include -#include +#include "cl-common.h" +#include "ops.h" #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#undef MIN -#undef MAX -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -#define MAX(a, b) ((a) > (b) ? (a) : (b)) -#define CEIL_DIV(M, N) (((M) + (N)-1) / (N)) - -#define UNUSED(x) (void)(x) - -#define CL_CHECK(err) \ - do { \ - cl_int err_ = (err); \ - if (err_ != CL_SUCCESS) { \ - GGML_LOG_ERROR("ggml_opencl: %s error %d at %s:%d\n", \ - #err, err_, __FILE__, __LINE__); \ - GGML_ASSERT(0); \ - } \ - } while (0) - -//------------------------------------------------------------------------------ -// OpenCL -//------------------------------------------------------------------------------ - -bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor); - -static bool ggml_cl_is_q4_0_soa(const ggml_tensor * tensor); -static bool ggml_cl_is_q8_0_soa(const ggml_tensor * tensor); -static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); -static void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); -static void ggml_cl_fa_decompose_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, cl_mem sums); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static void ggml_cl_mul_mat_kq_kqv_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool is_kq); -#endif - -// See https://gmplib.org/~tege/divcnst-pldi94.pdf figure 4.1. -// Precompute mp (m' in the paper) and L such that division -// can be computed using a multiply (high 32b of 64b result) -// and a shift: -// -// n/d = (mulhi(n, mp) + n) >> L; -struct fastdiv_vals { - uint32_t mp; - uint32_t L; - uint32_t d; - uint32_t pad; -}; -static_assert(sizeof(fastdiv_vals) == 16, "fastdiv_vals size incorrect"); - -static fastdiv_vals init_fastdiv_values(uint64_t d_64) { - GGML_ASSERT(d_64 != 0); - GGML_ASSERT(d_64 <= std::numeric_limits::max()); - - uint32_t d = (uint32_t)d_64; - - // compute L = ceil(log2(d)); - uint32_t L = 0; - while (L < 32 && (uint32_t{ 1 } << L) < d) { - L++; - } - - uint32_t mp = (uint32_t) ((uint64_t{ 1 } << 32) * ((uint64_t{ 1 } << L) - d) / d + 1); - // pack divisor as well to reduce error surface - return { mp, L, d, 0 }; -} -enum GPU_FAMILY { - ADRENO, - INTEL, - UNKNOWN, -}; +static ggml_backend_opencl_context * ggml_cl_init(ggml_backend_dev_t dev); +static bool ggml_opencl_is_device_supported(ggml_backend_dev_t dev); -enum ADRENO_GPU_GEN { - ADRENO_UNKNOWN, - A6X, - A7X, - A8X, - X1E, - X2E, -}; +static std::vector ggml_opencl_probe_devices(ggml_backend_reg * reg) { + std::vector found_devices; -enum ADRENO_CL_COMPILER_TYPE { - E031, - E17, - DX, -}; + struct cl_device; + struct cl_platform { + cl_platform_id id; + unsigned number; + char name[128]; + char vendor[128]; + struct cl_device * devices; + unsigned n_devices; + struct cl_device * default_device; + }; -struct ggml_cl_version { - cl_uint major = 0; - cl_uint minor = 0; -}; + struct cl_device { + struct cl_platform * platform; + cl_device_id id; + unsigned number; + cl_device_type type; + char name[128]; + char version[128]; + }; + enum { NPLAT = 16, NDEV = 16 }; -struct ggml_cl_compiler_version { - ADRENO_CL_COMPILER_TYPE type; - int major = -1; - int minor = -1; - int patch = -1; + struct cl_platform platforms[NPLAT]; + unsigned n_platforms = 0; + struct cl_device devices[NDEV]; + unsigned n_devices = 0; + struct cl_device * default_device = NULL; + unsigned default_platform_number = 0; - bool same(ADRENO_CL_COMPILER_TYPE t, int x, int y, int z) const { - return major == x && minor == y && patch == z && type == t; - } - bool newer_than(ADRENO_CL_COMPILER_TYPE t, int x, int y, int z) const { - return major*10000 + minor*100 + patch > x*10000 + y*100 + z && type == t; - } - bool newer_than_or_same(ADRENO_CL_COMPILER_TYPE t, int x, int y, int z) const { - return same(t, x, y, z) || newer_than(t, x, y, z); + cl_platform_id platform_ids[NPLAT]; + if (clGetPlatformIDs(NPLAT, platform_ids, &n_platforms) != CL_SUCCESS) { + GGML_LOG_ERROR("ggml_opencl: platform IDs not available.\n"); + return found_devices; } -}; - -static size_t align_to(size_t value, size_t to_alignment) { - GGML_ASSERT(to_alignment && "Invalid alignment (must be non-zero)"); - GGML_ASSERT((to_alignment & (to_alignment - 1)) == 0 && "to_alignment must be power-of-two"); - return ((value + to_alignment - 1) / to_alignment) * to_alignment; -} + for (unsigned i = 0; i < n_platforms; i++) { + struct cl_platform * p = &platforms[i]; + p->number = i; + p->id = platform_ids[i]; + CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_NAME, sizeof(p->name), &p->name, NULL)); + CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_VENDOR, sizeof(p->vendor), &p->vendor, NULL)); + cl_device_id device_ids[NDEV]; + cl_int clGetDeviceIDsError = clGetDeviceIDs(p->id, CL_DEVICE_TYPE_ALL, NDEV, device_ids, &p->n_devices); + if (clGetDeviceIDsError == CL_DEVICE_NOT_FOUND) { + p->n_devices = 0; + } else { + CL_CHECK(clGetDeviceIDsError); + } + p->devices = p->n_devices > 0 ? &devices[n_devices] : NULL; + p->default_device = NULL; -// Parses a version string of form "XX.YY ". On an error returns ggml_cl_version with all zeroes. -static ggml_cl_version parse_cl_version(std::string_view str) { - size_t major_str_begin = 0; - size_t major_str_end = str.find(".", major_str_begin); - if (major_str_end == std::string::npos) { - return {}; - } + for (unsigned j = 0; j < p->n_devices; j++) { + struct cl_device * d = &devices[n_devices]; + d->number = n_devices++; + d->id = device_ids[j]; + d->platform = p; + CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_NAME, sizeof(d->name), &d->name, NULL)); + CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_TYPE, sizeof(d->type), &d->type, NULL)); + CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_VERSION, sizeof(d->version), &d->version, NULL)); - size_t minor_str_begin = major_str_end + 1; - size_t minor_str_end = str.find(" ", minor_str_begin); - if (minor_str_end == std::string::npos) { - return {}; - } + if (p->default_device == NULL && d->type == CL_DEVICE_TYPE_GPU) { + p->default_device = d; + } + } - cl_uint version_major; - if (std::from_chars(str.data() + major_str_begin, str.data() + major_str_end, version_major).ec != std::errc{}) { - return {}; + if (default_device == NULL && p->default_device != NULL) { + default_device = p->default_device; + default_platform_number = i; + } } - cl_uint version_minor; - if (std::from_chars(str.data() + minor_str_begin, str.data() + minor_str_end, version_minor).ec != std::errc{}) { - return {}; + if (n_devices == 0) { + GGML_LOG_ERROR("ggml_opencl: could find any OpenCL devices.\n"); + return found_devices; } - return { version_major, version_minor }; -} -// Returns OpenCL platform's version. On an error returns ggml_cl_version with all zeroes. -static ggml_cl_version get_opencl_platform_version(cl_platform_id platform) { - size_t param_size; - CL_CHECK(clGetPlatformInfo(platform, CL_PLATFORM_VERSION, 0, nullptr, ¶m_size)); - std::unique_ptr param_storage(new char[param_size]); - CL_CHECK(clGetPlatformInfo(platform, CL_PLATFORM_VERSION, param_size, param_storage.get(), nullptr)); - - auto param_value = std::string_view(param_storage.get(), param_size); - const std::string version_prefix = "OpenCL "; // Suffix: "XX.YY " - if (param_value.find(version_prefix) != 0) { - return {}; - } - param_value.remove_prefix(version_prefix.length()); - return parse_cl_version(param_value); -} + char * user_platform_string = getenv("GGML_OPENCL_PLATFORM"); + char * user_device_string = getenv("GGML_OPENCL_DEVICE"); + int user_platform_number = -1; + int user_device_number = -1; + cl_device * candidate_devices = nullptr; + unsigned n_candidate_devices = 0; -// Returns the DEVICE's OpenCL version. On an error returns ggml_cl_version with all zeroes. -static ggml_cl_version get_opencl_device_version(cl_device_id device) { - size_t param_size; - if (clGetDeviceInfo(device, CL_DEVICE_VERSION, 0, nullptr, ¶m_size) != CL_SUCCESS || !param_size) { - return {}; - } - std::unique_ptr param_storage(new char[param_size]); - if (clGetDeviceInfo(device, CL_DEVICE_VERSION, param_size, param_storage.get(), nullptr) != CL_SUCCESS) { - return {}; + unsigned n; + if (user_platform_string != NULL && sscanf(user_platform_string, " %u", &n) == 1 && n < n_platforms) { + user_platform_number = (int)n; } - - auto param_value = std::string_view(param_storage.get(), param_size); - const std::string version_prefix = "OpenCL "; // "OpenCL . " - if (param_value.find(version_prefix) != 0) { - return {}; + if (user_device_string != NULL && sscanf(user_device_string, " %u", &n) == 1 && n < n_devices) { + user_device_number = (int)n; } - param_value.remove_prefix(version_prefix.length()); - return parse_cl_version(param_value); -} - -// Return a version to use in OpenCL C compilation. On an error returns ggml_cl_version with all zeroes. -static ggml_cl_version get_opencl_c_version(ggml_cl_version platform_version, cl_device_id device) { - size_t param_size; - -#if CL_TARGET_OPENCL_VERSION >= 300 - // CL_DEVICE_OPENCL_C_ALL_VERSIONS is an OpenCL 3.0 *device* query, so gating it on the - // *platform* version is not enough: a 3.0 platform can expose 2.0 devices, where the - // query returns CL_INVALID_VALUE and the old CL_CHECK aborted during backend init. - // Gate on the device version, and treat a failure as "fall back to the legacy query" - // rather than fatal -- a device may advertise 3.0 and still refuse the property. - const ggml_cl_version device_version = get_opencl_device_version(device); - if (platform_version.major >= 3 && device_version.major >= 3) { - cl_int err = clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_ALL_VERSIONS, 0, nullptr, ¶m_size); - if (err == CL_SUCCESS && param_size) { - std::unique_ptr versions(new cl_name_version[param_size]); - err = clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_ALL_VERSIONS, param_size, versions.get(), nullptr); - if (err == CL_SUCCESS) { - unsigned versions_count = param_size / sizeof(cl_name_version); - - cl_version version_max = 0; - for (unsigned i = 0; i < versions_count; i++) { - version_max = std::max(versions[i].version, version_max); + if (user_platform_number != -1 && user_device_number != -1) { + cl_platform* platform = &platforms[user_platform_number]; + if ((unsigned)user_device_number >= platform->n_devices) { + GGML_LOG_ERROR("ggml_opencl: invalid device number %d\n", user_device_number); + exit(1); + } + default_device = &platform->devices[user_device_number]; + candidate_devices = platform->devices; + n_candidate_devices = platform->n_devices; + } else { + // Choose a platform by matching a substring. + if (user_platform_number == -1 && user_platform_string != NULL && user_platform_string[0] != 0) { + for (unsigned i = 0; i < n_platforms; i++) { + struct cl_platform * p = &platforms[i]; + if (strstr(p->name, user_platform_string) != NULL || + strstr(p->vendor, user_platform_string) != NULL) { + user_platform_number = (int)i; + break; } - - return { CL_VERSION_MAJOR(version_max), CL_VERSION_MINOR(version_max) }; + } + if (user_platform_number == -1) { + GGML_LOG_ERROR("ggml_opencl: no platform matching '%s' was found.\n", user_platform_string); + exit(1); } } - // fall through to CL_DEVICE_OPENCL_C_VERSION below - } -#else - GGML_UNUSED(platform_version); -#endif // CL_TARGET_OPENCL_VERSION >= 300 - - if (clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_VERSION, 0, nullptr, ¶m_size) != CL_SUCCESS || !param_size) { - return {}; - } - std::unique_ptr param_storage(new char[param_size]); - if (clGetDeviceInfo(device, CL_DEVICE_OPENCL_C_VERSION, param_size, param_storage.get(), nullptr) != CL_SUCCESS) { - return {}; - } - auto param_value = std::string_view(param_storage.get(), param_size); + int platform_idx = user_platform_number != -1 ? user_platform_number : default_platform_number; + struct cl_platform * p = &platforms[platform_idx]; + candidate_devices = p->devices; + n_candidate_devices = p->n_devices; + default_device = p->default_device; + if (n_candidate_devices == 0) { + GGML_LOG_ERROR("ggml_opencl: selected platform '%s' does not have any devices.\n", p->name); + exit(1); + } - const std::string version_prefix = "OpenCL C "; // Suffix: "XX.YY " - if (param_value.find(version_prefix) != 0) { - return {}; - } - param_value.remove_prefix(version_prefix.length()); + if (user_device_number == -1 && user_device_string != NULL && user_device_string[0] != 0) { + for (unsigned i = 0; i < n_candidate_devices; i++) { + struct cl_device * d = &candidate_devices[i]; + if (strstr(d->name, user_device_string) != NULL) { + user_device_number = d->number; + break; + } + } + if (user_device_number == -1) { + GGML_LOG_ERROR("ggml_opencl: no device matching '%s' was found.\n", user_device_string); + exit(1); + } + } + if (user_device_number != -1) { + candidate_devices = &devices[user_device_number]; + n_candidate_devices = 1; + default_device = &candidate_devices[0]; + } - return parse_cl_version(param_value); -} + GGML_ASSERT(n_candidate_devices > 0); -static ADRENO_GPU_GEN get_adreno_gpu_gen(const char *device_name) { - if (strstr(device_name, "610") || strstr(device_name, "612") || - strstr(device_name, "613") || strstr(device_name, "615") || - strstr(device_name, "616") || strstr(device_name, "618") || - strstr(device_name, "619") || strstr(device_name, "620") || - strstr(device_name, "623") || strstr(device_name, "630") || - strstr(device_name, "640") || - strstr(device_name, "642") || strstr(device_name, "643") || - strstr(device_name, "644") || strstr(device_name, "650") || - strstr(device_name, "660") || strstr(device_name, "663") || - strstr(device_name, "680") || strstr(device_name, "685") || - strstr(device_name, "690")) { - return ADRENO_GPU_GEN::A6X; + if (default_device == NULL) { + default_device = &candidate_devices[0]; + } } - if (strstr(device_name, "730") || - strstr(device_name, "740") || - strstr(device_name, "750")) { - return ADRENO_GPU_GEN::A7X; - } + GGML_ASSERT(n_candidate_devices != 0 && candidate_devices); - if (strstr(device_name, "810") || - strstr(device_name, "830") || - strstr(device_name, "840") || - strstr(device_name, "850")) { - return ADRENO_GPU_GEN::A8X; + // Put the default device in front. + for (unsigned i = 1; i < n_candidate_devices; i++) { + if (&candidate_devices[i] == default_device) { + std::swap(candidate_devices[0], candidate_devices[i]); + default_device = &candidate_devices[0]; + break; + } } - if (strstr(device_name, "X1")) { - return ADRENO_GPU_GEN::X1E; - } + GGML_LOG_INFO("ggml_opencl: selected platform: '%s'\n", default_device->platform->name); - if (strstr(device_name, "X2")) { - return ADRENO_GPU_GEN::X2E; + std::vector device_ids; + for (auto dev = candidate_devices, dev_end = candidate_devices + n_candidate_devices; dev != dev_end; dev++) { + device_ids.push_back(dev->id); } - return ADRENO_GPU_GEN::ADRENO_UNKNOWN; -} - -static ggml_cl_compiler_version get_adreno_cl_compiler_version(const char *driver_version) { - std::string driver_ver_str(driver_version); - ADRENO_CL_COMPILER_TYPE type = ADRENO_CL_COMPILER_TYPE::E031; - size_t compiler_ver_pos = driver_ver_str.find("E031"); - size_t compiler_ver_len = 13; - size_t compiler_major_offset = 5; - size_t compiler_minor_offset = 8; - size_t compiler_patch_offset = 11; - - if (compiler_ver_pos == std::string::npos) { - compiler_ver_pos = driver_ver_str.find("E17"); - if (compiler_ver_pos != std::string::npos) { - type = ADRENO_CL_COMPILER_TYPE::E17; - compiler_ver_len = 12; - compiler_major_offset = 4; - compiler_minor_offset = 7; - compiler_patch_offset = 10; - } - } + cl_int err; + cl_context shared_context; + cl_context_properties properties[] = { (intptr_t) CL_CONTEXT_PLATFORM, (intptr_t) default_device->platform->id, 0 }; - if (compiler_ver_pos == std::string::npos) { - compiler_ver_pos = driver_ver_str.find("DX"); - if (compiler_ver_pos == std::string::npos) { - return {}; - } - type = ADRENO_CL_COMPILER_TYPE::DX; - compiler_ver_len = 11; - compiler_major_offset = 3; - compiler_minor_offset = 6; - compiler_patch_offset = 9; - } + CL_CHECK( + (shared_context = clCreateContext(properties, device_ids.size(), device_ids.data(), NULL, NULL, &err), err)); - std::string compiler_ver_str = driver_ver_str.substr(compiler_ver_pos, compiler_ver_len); - int major = std::atoi(compiler_ver_str.substr(compiler_major_offset, 2).c_str()); - int minor = std::atoi(compiler_ver_str.substr(compiler_minor_offset, 2).c_str()); - int patch = std::atoi(compiler_ver_str.substr(compiler_patch_offset, 2).c_str()); - return { type, major, minor, patch }; -} + for (auto dev = candidate_devices, dev_end = candidate_devices + n_candidate_devices; dev != dev_end; dev++) { + GGML_LOG_INFO("\nggml_opencl: device: '%s (%s)'\n", dev->name, dev->version); -// cl buffer wrapper -struct ggml_cl_buffer { - cl_mem buffer; - size_t size; + auto dev_ctx = std::unique_ptr(new ggml_backend_opencl_device_context{ + /*.platform =*/dev->platform->id, + /*.platform_nane =*/dev->platform->name, + /*.device =*/dev->id, + /*.device_name =*/dev->name, + /*.device_type =*/dev->type, + /*.device_version =*/dev->version, + /*.backend_ctx =*/nullptr, + /*.buffer_type =*/{}, + /*.context =*/shared_context, + }); - ggml_cl_buffer() - : buffer(nullptr), size(0) {} + found_devices.push_back(ggml_backend_device{ + /* .iface = */ ggml_backend_opencl_device_i, + /* .reg = */ reg, + /* .context = */ dev_ctx.get(), + }); - ~ggml_cl_buffer() { - if (buffer) { - CL_CHECK(clReleaseMemObject(buffer)); + if (!ggml_opencl_is_device_supported(&found_devices.back())) { + found_devices.pop_back(); + GGML_LOG_WARN("ggml_opencl: drop unsupported device '%s'.\n", dev->name); + continue; } - } - void allocate(cl_context context, size_t new_size) { - if (new_size > size) { - size = new_size; - if (buffer) { - CL_CHECK(clReleaseMemObject(buffer)); - } - cl_int err; - CL_CHECK((buffer = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err), err)); - } + g_ggml_backend_opencl_dev_ctxs.push_back(std::move(dev_ctx)); } -}; - -// Profiling -struct ProfilingInfo { - std::string op_name; - std::string kernel_name; - cl_kernel kernel; - cl_event evt; - - cl_ulong cmd_queued; - cl_ulong cmd_submit; - cl_ulong cmd_start; - cl_ulong cmd_end; - cl_ulong overhead_start; - cl_ulong overhead_end; - // For the times below, see spec for clGetEventProfilingInfo - // The time kernel spent in cmd queue - SUBMIT - QUEUED - cl_ulong cmd_queued_duration_ns; - // The time kernel spent for submission - START - SUBMIT - cl_ulong cmd_submit_duration_ns; - // Kernel execution time in nanoseconds - END - START - cl_ulong cmd_duration_ns; - // The time for the kernel to complete - COMPLETE - END - cl_ulong cmd_complete_duration_ns; - // Total time to finish the kernel - COMPLETE - QUEUED - cl_ulong cmd_total_duration_ns; - // Global and local work sizes. - size_t global_size[3]; - size_t local_size[3]; - // Op output size. - size_t output_size[4]; -}; + if (found_devices.size()) { + auto * dev_ctx = static_cast(found_devices.front().context); + GGML_LOG_INFO("ggml_opencl: default device: '%s (%s)'\n", dev_ctx->device_name.c_str(), + dev_ctx->device_version.c_str()); -static void populateProfilingInfo( - ProfilingInfo& info, cl_event evt, cl_kernel kernel, cl_uint work_dim, - size_t global_size[3], size_t local_size[3], - const ggml_tensor * tensor) { - info.op_name = tensor->name; - info.kernel = kernel; - info.evt = evt; - - // 0 means not specified, e.g., 2D workgroup, or NULL for driver to choose - info.local_size[0] = 0; - info.local_size[1] = 0; - info.local_size[2] = 0; - - info.global_size[0] = 0; - info.global_size[1] = 0; - info.global_size[2] = 0; - - if (local_size) { - for (cl_uint i = 0; i < work_dim; ++i) { - info.local_size[i] = local_size[i]; + if (dev_ctx->device_type != CL_DEVICE_TYPE_GPU) { + GGML_LOG_WARN("ggml_opencl: warning, the default device is not a GPU: '%s'.\n", + dev_ctx->device_name.c_str()); } } - for (cl_uint i = 0; i < work_dim; ++i) { - info.global_size[i] = global_size[i]; - } - - info.output_size[0] = tensor->ne[0]; - info.output_size[1] = tensor->ne[1]; - info.output_size[2] = tensor->ne[2]; - info.output_size[3] = tensor->ne[3]; + return found_devices; } -struct ggml_backend_opencl_context; +static void ggml_opencl_print_backend_info(ggml_backend_opencl_device_context * dev_ctx) { + GGML_ASSERT(dev_ctx); + GGML_ASSERT(dev_ctx->backend_ctx); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static void ggml_cl_adreno_xmem_attn_release_scratch(ggml_backend_opencl_context * backend_ctx); -#endif - -// backend device context -struct ggml_backend_opencl_device_context { - cl_platform_id platform; - std::string platform_name; - - cl_device_id device; - std::string device_name; - cl_device_type device_type; - std::string device_version; - - // Initialized by ggml_cl_init(). - ggml_backend_opencl_context * backend_ctx = nullptr; - - // Initialized by ggml_backend_opencl_device_get_buffer_type() - ggml_backend_buffer_type buffer_type; - - cl_context context = nullptr; - - GPU_FAMILY gpu_family = GPU_FAMILY::UNKNOWN; - ADRENO_GPU_GEN adreno_gen = ADRENO_GPU_GEN::ADRENO_UNKNOWN; - - std::regex *opfilter = nullptr; // regex of ops to not claim - std::string opfilter_str = ""; // regex string for opfilter - size_t global_mem_size = 0; -}; - -// Lazily-compiled flash-attention kernels and their per-(dk,dv) tile metadata. -// One map per (Q/KV dtype, decode/prefill, split) combination; the int maps -// hold tile dims (bm/bn), workgroup sizes and the n_kv split thresholds. -struct ggml_opencl_fa_kernels { - // f16 Q / f16 KV - std::map, cl_kernel> f16; - std::map, cl_kernel> f16_q1; - // f32 Q / f32 KV - std::map, cl_kernel> f32; - std::map, cl_kernel> f32_q1; - // f32 Q / f16 KV (mixed) - std::map, cl_kernel> f32_f16; - std::map, cl_kernel> f32_f16_split; // N_SPLIT>1 variant - std::map, cl_kernel> f32_f16_split_k_img; // DK=512 prefill split, K via image1d_buffer_t - std::map, cl_kernel> f32_f16_q1; - std::map, cl_kernel> f32_f16_q1_split; // flash-decoding K-split - // vec decode - std::map, cl_kernel> f32_f16_q1_vec; - bool f32_f16_vec_512_attempted = false; - std::map, cl_kernel> f32_f16_mq_decode; - std::map, size_t> f32_f16_mq_decode_wg; - std::map, int> f32_f16_mq_decode_hs; - std::set> f32_f16_mq_decode_attempted; - ggml_cl_buffer fd_partial; - cl_uint compute_units = 0; - // kv-head-coalesced vec decode - std::map, cl_kernel> f32_f16_q1_vec_mq; - // kv-head-coalesced + flash-decoding split - std::map, cl_kernel> f32_f16_q1_vec_mq_split; - // MQ_GQA=8 specializations - std::map, cl_kernel> f32_f16_q1_vec_mq_g8; - std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8; - // k-image variant of MQ_G8 vec_mq_split - std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_k_img; - // k-image variant of MQ_GQA=4 vec_mq_split - std::map, cl_kernel> f32_f16_q1_vec_mq_split_k_img; - // Cluster-parallel decode - std::map, cl_kernel> f32_f16_q1_vec_mq_split_c8; - std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_c8; - // NSG_SPLIT=2 specializations (WG=128): the c8 kernel's register footprint - // caps its per-kernel WG at 128 on X2, below the stock 256/192 requirement. - // 2 subgroups × FA_CL_NCL streams still gives 16 in-flight rows per WG. - std::map, cl_kernel> f32_f16_q1_vec_mq_split_c8_ns2; - std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_c8_ns2; - // FA_CL_C=32 / MQ_GQA=8 / NSG_SPLIT=2 specialization for the DK=DV=256 - // GQA=8 class (Qwen3.5/3.6-35B-A3B: 16 Q heads, 2 KV heads). o_acc = - // DV_VEC/32 × 8 = 128B/lane (in budget); the baseline fa1 path for this - // shape has NO MQ/FD at all and pays an 8× KV re-read per Q head. - std::map, cl_kernel> f32_f16_q1_vec_mq_split_g8_c32; - // alternative decode - std::map, cl_kernel> f32_f16_q1_local_tile; - // hybrid local-tile + MQ + FD-split kernel for DK=DV=128 only - std::map, cl_kernel> f32_f16_q1_local_mq_split; - std::map, cl_kernel> f32_f16_q1_local_mq_split_g8; - std::map, int> f32_f16_bm; - std::map, int> f32_f16_bn; - std::map, int> f32_f16_wg_size; - std::map, int> f32_f16_split_wg_size; - std::map, int> f32_f16_split_nkv_threshold; - // f32 Q / native q8_0 KV - std::map, cl_kernel> f32_q8_0_q1; // decode - std::map, cl_kernel> f32_q8_0_q1_vec; // DV-split + multi-subgroup decode - std::map, cl_kernel> f32_q8_0_q1_split; // flash-decoding pass 1 - // KV-head-coalesced + flash-decoding split for q8_0 KV - std::map, cl_kernel> f32_q8_0_q1_vec_mq_split; - std::map, cl_kernel> f32_q8_0_q1_vec_mq_split_g8; - // Cluster-parallel q8_0 decode - std::map, cl_kernel> f32_q8_0_q1_vec_mq_split_c8; - std::map, cl_kernel> f32_q8_0; // prefill (baseline) - std::map, cl_kernel> f32_q8_0_split; // N_SPLIT>1 variant - std::map, int> f32_q8_0_split_wg_size; // wg_size = bm*n_split - std::map, int> f32_q8_0_split_nkv_threshold; // use split when n_kv >= this - std::map, int> f32_q8_0_split_bm; // per-split BLOCK_M - // f32 Q / native q4_0 KV - std::map, cl_kernel> f32_q4_0_q1; - std::map, cl_kernel> f32_q4_0_q1_vec; // DV-split + multi-subgroup decode - std::map, cl_kernel> f32_q4_0_q1_split; - // kv-head-coalesced + flash-decoding split for q4_0 kv (dp4a K dot) - std::map, cl_kernel> f32_q4_0_q1_vec_mq_split; - std::map, cl_kernel> f32_q4_0_q1_vec_mq_split_g8; - // Cluster-parallel q4_0 decode - std::map, cl_kernel> f32_q4_0_q1_vec_mq_split_g8_c8; - std::map, cl_kernel> f32_q4_0_q1_vec_mq_split_c8; - std::map, cl_kernel> f32_q4_0; - std::map, cl_kernel> f32_q4_0_split; - std::map, int> f32_q4_0_split_wg_size; - std::map, int> f32_q4_0_split_nkv_threshold; - std::map, int> f32_q4_0_split_bm; - // shared: flash-decoding merge + prefill prepass (kv-pad, mask-pad, blk class) - std::map, cl_kernel> f32_merge; - std::map, cl_kernel> kv_pad_f16; - std::map, cl_kernel> mask_pad_f16; - std::map, cl_kernel> blk_f16; - // decomposed prefill: V^T, built with the prepass - std::map, cl_kernel> v_transpose_f16; - // generic prefill tile dims (f16 / f32 paths) - std::map, int> bm; - std::map, int> bn; - // attempted (variant, (dk, dv)) - // all attempted FA kernels appear here, but those not registered failed compilation - std::set>> variant_attempted; - - // FA bin kernels -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel_flash_attn_f32_f16_bin; - - cl_kernel kernel_repack_q_for_wmm; - cl_kernel kernel_repack_k_for_wmm; - cl_kernel kernel_repack_v_for_wmm; - cl_kernel kernel_repack_mask_for_wmm; -#endif -}; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -struct ggml_cl_adreno_xmem_attn_scratch { - cl_mem q_img = nullptr; - cl_mem k_img = nullptr; - cl_mem v_img = nullptr; - cl_mem out_img = nullptr; - cl_mem k_transpose_buf = nullptr; - cl_mem k_transpose_img1d = nullptr; - cl_mem k_packed_buf = nullptr; - cl_mem v_packed_buf = nullptr; - cl_mem score_buf = nullptr; - cl_mem prob_buf = nullptr; - cl_mem score_img1d = nullptr; - cl_mem prob_img1d = nullptr; - cl_mem softmax_stats_img2d = nullptr; - cl_mem xmem_qk = nullptr; - cl_mem xmem_pv = nullptr; - - int n_q = 0; - int n_kv = 0; - int n_kv_padded = 0; - int d_head_q = 0; - int d_head_v = 0; - int q_width = 0; - int kv_heads_total = 0; -}; - -struct ggml_cl_adreno_xmem_attn_state { - bool compiled = false; - bool logged = false; - - cl_kernel kernel_q_f32_to_img_scaled = nullptr; - cl_kernel kernel_kv_f32_to_img_gqa = nullptr; - cl_kernel kernel_kv_f16_to_img_gqa = nullptr; - cl_kernel kernel_img_to_f32 = nullptr; - cl_kernel kernel_k_gather = nullptr; - cl_kernel kernel_pack_k = nullptr; - cl_kernel kernel_qk_gemm = nullptr; - cl_kernel kernel_softmax_reduce_basic = nullptr; - cl_kernel kernel_softmax_apply_basic = nullptr; - cl_kernel kernel_mask_scores = nullptr; - cl_kernel kernel_pack_v = nullptr; - cl_kernel kernel_pv_gemm = nullptr; - - ggml_cl_adreno_xmem_attn_scratch scratch; -}; -#endif - -// backend context -struct ggml_backend_opencl_context { - int ref_count; - - cl_device_id device; - std::string device_name; - - ggml_cl_version platform_version; - ggml_cl_version opencl_c_version; - - // argmax and argsort are loaded in supports_op; argsort availability depends on the compiled kernel's workgroup limit. - bool kernels_loaded_argmax = false; - bool kernels_loaded_argsort = false; - // rest of the kernels are currently always loaded in alloc_buffer. - bool kernels_loaded = false; - - std::string driver_version; - - GPU_FAMILY gpu_family; - ADRENO_GPU_GEN adreno_gen; - - cl_int alignment; - size_t global_mem_size; - size_t max_alloc_size; - size_t max_workgroup_size; - cl_ulong local_mem_size; - bool fp16_support; - bool has_vector_subgroup_broadcast; - bool has_khr_subgroup_shuffle = false; - bool has_subgroup_shuffle = false; // cl_khr_subgroup_shuffle or cl_qcom_subgroup_shuffle - bool has_integer_dot = false; // cl_khr_integer_dot_product or cl_qcom_dot_product8 - bool has_qcom_subgroup_shuffle = false; // specifically cl_qcom_subgroup_shuffle - bool disable_fusion; - bool fuse_mm_glu = true; // opt-out GGML_OPENCL_FUSE_MM_GLU=0 (byte-identical gate+up GEMV + GLU, q4_K FFN) - bool fuse_rms_add = true; // opt-out GGML_OPENCL_FUSE_RMS_ADD=0 (fused rms_norm*w + residual) - bool f16_mrow = true; // opt-out GGML_OPENCL_F16_MROW=0 (multi-row-per-WG f16 decode GEMV for attn proj + lm_head) - int f16_mrow_rpt = 1; // GGML_OPENCL_F16_MROW_RPT={1,2,4,8,16} rows-per-subgroup register blocking - - // ragged moe, use int to directly pass to kernel - cl_uint adreno_use_moe_ragged; - cl_uint adreno_moe_ragged_skip_gran; - cl_uint adreno_use_moe_ragged_dp4; + auto * backend_ctx = dev_ctx->backend_ctx; - // whether fuse moe combine - cl_uint fuse_moe_combine; - - // whether to fold the MoE bias adds into swiglu_oai - cl_uint fuse_moe_bias_glu; - - // whether to fold the MoE down-projection bias add into the combine - cl_uint fuse_moe_bias_combine; - - bool adreno_has_large_buffer; - bool adreno_use_large_buffer; - bool adreno_use_bin_kernels; - get_adreno_bin_kernel_func_t get_adreno_bin_kernel_func = nullptr; - ggml_cl_compiler_version adreno_cl_compiler_version; - // The q6_K flat mul_mat codegen workarounds are needed by old E031 compilers only. - bool q6_k_flat_old_compiler; - - std::string kernel_compile_opts; // cached for lazy-compiled kernels. - - int adreno_wave_size; - - cl_bool non_uniform_workgroups; - size_t image_max_buffer_size; - size_t image2d_max_width; - size_t image2d_max_height; - size_t image3d_max_width; - size_t image3d_max_height; - size_t image3d_max_depth; - - cl_device_svm_capabilities svm_caps; - - cl_context context; - cl_command_queue queue; - - // On-disk compiled-program cache (see GGML_OPENCL_KERNEL_CACHE_DIR). - cl_program_cache_state program_cache; - bool program_cache_initialized = false; - - // prealloc buffers for transposing weights and activations - ggml_cl_buffer prealloc_quant_trans; - ggml_cl_buffer prealloc_scales_trans; - ggml_cl_buffer prealloc_act_trans; - // q8_1-quantized reordered MoE activations for the dp4a prefill GEMM. - ggml_cl_buffer prealloc_moe_qa; // int8 quants [tok_slots * ne00] - ggml_cl_buffer prealloc_moe_da; // per-block d [tok_slots * ne00/32] (half) - ggml_cl_buffer prealloc_moe_sa; // per-block s [tok_slots * ne00/32] (half) - // per-tile transposed qa/da and on-chip scratch for the ldck dp4a MoE GEMM - ggml_cl_buffer prealloc_moe_qa_trans; // int8 quants [tok_slots * ne00] - ggml_cl_buffer prealloc_moe_da_trans; // per-block d [tok_slots * ne00/32] (float) - ggml_cl_buffer prealloc_moe_qda_on_chip; - // scratch copy of the router weights to avoid dst aliasing - ggml_cl_buffer prealloc_moe_combine_w; - ggml_cl_buffer prealloc_splitk_partial; // [ksplit * M] partials for split-K GEMV - - // pool of persistent image1d_buffer views over kv-cache layers, keyed by - // (parent buffer, offset within parent) - // used by the img-variant KQ/KQV dispatch paths to avoid per-call - // clCreateSubBuffer + clCreateImage + pending-release-queue on long-context decode - struct ImagePoolKey { - uintptr_t buf; - uint64_t offset; - bool operator<(const ImagePoolKey & o) const { - if (buf != o.buf) return buf < o.buf; - return offset < o.offset; - } - }; - struct ImagePoolEntry { - cl_mem sub_buffer = nullptr; - cl_mem image = nullptr; - size_t k_bytes = 0; - cl_channel_type channel_data_type = CL_FLOAT; - }; - std::map kq_img_pool; - std::map kqv_img_pool; - - // pool for the on-device f16 buffer for kv-cache with non-FA quantized-K (q8_0/q4_0) - std::map dequant_f16_pool; - - // prealloc buffers for src0 and src1 - ggml_cl_buffer prealloc_src0; - ggml_cl_buffer prealloc_src1; - ggml_cl_buffer prealloc_top_k; - - // scratch for the decomposed flash attention prefill, sized per query chunk - ggml_cl_buffer prealloc_fa_vt; - ggml_cl_buffer prealloc_fa_kq; - ggml_cl_buffer prealloc_fa_kqv; - ggml_cl_buffer prealloc_fa_sums; - ggml_cl_buffer prealloc_fa_vtq; - ggml_cl_buffer prealloc_fa_vtd; - ggml_cl_buffer prealloc_fa_pq; - ggml_cl_buffer prealloc_fa_pd; - ggml_cl_buffer prealloc_fa_bmax; - ggml_cl_buffer prealloc_fa_bsum; - ggml_cl_buffer prealloc_fa_k8; - ggml_cl_buffer prealloc_fa_k8_scale; - ggml_cl_buffer prealloc_fa_q8; - ggml_cl_buffer prealloc_fa_q8_scale; + GGML_LOG_INFO("ggml_opencl: OpenCL device: %s\n", + backend_ctx->device_name.c_str()); + GGML_LOG_INFO("ggml_opencl: OpenCL driver: %s\n", + backend_ctx->driver_version.c_str()); + GGML_LOG_INFO("ggml_opencl: vector subgroup broadcast support: %s\n", + backend_ctx->has_vector_subgroup_broadcast ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: subgroup shuffle support: %s\n", + backend_ctx->has_subgroup_shuffle ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: device FP16 support: %s\n", + backend_ctx->fp16_support ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: khr dot product support: %s\n", + backend_ctx->has_integer_dot ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: mem base addr align: %u\n", + backend_ctx->alignment); + GGML_LOG_INFO("ggml_opencl: global mem size: %zu MB\n", + backend_ctx->global_mem_size/1024/1024); + GGML_LOG_INFO("ggml_opencl: max mem alloc size: %zu MB\n", + backend_ctx->max_alloc_size/1024/1024); + GGML_LOG_INFO("ggml_opencl: device max image buffer size (pixels): %zu\n", + backend_ctx->image_max_buffer_size); + GGML_LOG_INFO("ggml_opencl: device max image2d size: %zu x %zu\n", + backend_ctx->image2d_max_width, backend_ctx->image2d_max_height); + GGML_LOG_INFO("ggml_opencl: device max workgroup size: %zu\n", + backend_ctx->max_workgroup_size); + GGML_LOG_INFO("ggml_opencl: SVM coarse grain buffer support: %s\n", + backend_ctx->svm_caps & CL_DEVICE_SVM_COARSE_GRAIN_BUFFER ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: SVM fine grain buffer support: %s\n", + backend_ctx->svm_caps & CL_DEVICE_SVM_FINE_GRAIN_BUFFER ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: SVM fine grain system support: %s\n", + backend_ctx->svm_caps & CL_DEVICE_SVM_FINE_GRAIN_SYSTEM ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: SVM atomics support: %s\n", + backend_ctx->svm_caps & CL_DEVICE_SVM_ATOMICS ? "true" : "false"); + GGML_LOG_INFO("ggml_opencl: cl_qcom_subgroup_shuffle support: %s\n", + backend_ctx->has_qcom_subgroup_shuffle ? "true" : "false"); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer prealloc_adreno_xmem_const; - bool adreno_xmem_gemm_enabled = false; -#endif + // Print out configurations +#ifdef GGML_OPENCL_SOA_Q + GGML_LOG_INFO("ggml_opencl: flattening quantized weights representation as struct of arrays (GGML_OPENCL_SOA_Q)\n"); +#endif // GGML_OPENCL_SOA_Q - // prealloc buffers for MoE router table preprocess - bool toggle_reorder = false; - ggml_cl_buffer prealloc_post_router; - ggml_cl_buffer prealloc_emap; - ggml_cl_buffer prealloc_hist; - ggml_cl_buffer prealloc_tile_offset; - ggml_cl_buffer prealloc_total_tiles; - ggml_cl_buffer prealloc_slot_counter; - - cl_program program_add; - cl_program program_add_id; - cl_program program_moe_add_id_glu; - cl_program program_clamp; - cl_program program_cvt; - cl_program program_gelu; - cl_program program_gemv_noshuffle_general; - cl_program program_gemv_noshuffle; - cl_program program_get_rows; - cl_program program_set_rows; - cl_program program_glu; - cl_program program_im2col_f16; - cl_program program_im2col_f32; - cl_program program_mul_mat_Ab_Bi_8x4; - cl_program program_mul_mv_q4_0_f32; - cl_program program_mul_mv_q4_0_f32_v; - cl_program program_mul_mv_q4_0_f32_8x_flat; - cl_program program_mul_mv_q4_0_f32_1d_8x_flat; - cl_program program_mul_mv_q4_0_f32_1d_16x_flat; - cl_program program_mul_mv_q6_K; - cl_program program_mul_mv_q8_0_f32, program_mul_mv_q8_0_f32_flat; - cl_program program_mul_mv_mxfp4_f32; - cl_program program_mul_mv_mxfp4_f32_flat; - cl_program program_mul_mv_f16_f16; - cl_program program_mul_mv_f16_f32_1row; - cl_program program_mul_mv_f16_f32_l4; - cl_program program_mul_mv_f16_f32; - cl_program program_mul_mv_f32_f32; - cl_program program_mul; - cl_program program_mul_mat_f16_f32_tiled; - cl_program program_mul_mm_f16_f32_kqv; - cl_program program_mul_mm_f16_f32_kq; - cl_program program_div; - cl_program program_sub; - cl_program program_norm; - cl_program program_relu; - cl_program program_rms_norm; - cl_program program_group_norm; - cl_program program_rope; - cl_program program_silu; - cl_program program_sigmoid; - cl_program program_softmax_f32; - cl_program program_softmax_f16; - cl_program program_softmax_4_f32; - cl_program program_softmax_4_f16; - cl_program program_argsort_f32_i32; - cl_program program_sum_rows_f32; - cl_program program_pad; - cl_program program_upscale; - cl_program program_conv_2d_f16; - cl_program program_conv_2d_f32; - cl_program program_conv_2d_f16_f32; - cl_program program_tsembd; - cl_program program_gemv_moe_mxfp4_f32, program_gemm_moe_mxfp4_f32; - cl_program program_mul_mv_id_q4_0_f32_8x_flat; - cl_program program_mul_mv_id_q8_0_f32, program_mul_mv_id_q8_0_f32_flat; - cl_program program_mul_mv_id_mxfp4_f32; - cl_program program_mul_mv_id_mxfp4_f32_flat; - cl_program program_mul_mm_f32_f32_l4_lm; - cl_program program_mul_mm_f16_f32_l4_lm; - cl_program program_mul_mm_f16_f32_l4_lm_n8; - cl_program program_mul_mm_q8_0_f32_l4_lm; - - cl_kernel kernel_add, kernel_add_row, kernel_add_f16, kernel_add_row_f16; - cl_kernel kernel_mul, kernel_mul_row, kernel_mul_f16, kernel_mul_row_f16; - cl_kernel kernel_mul_mat_scale = nullptr; - cl_kernel kernel_div, kernel_div_row, kernel_div_f16, kernel_div_row_f16; - cl_kernel kernel_sub, kernel_sub_row, kernel_sub_f16, kernel_sub_row_f16; - cl_kernel kernel_add_id; - cl_kernel kernel_add_id_add_id_swiglu_oai; - cl_kernel kernel_scale_f32, kernel_scale_f32_4, kernel_scale_f32_nc; - cl_kernel kernel_scale_f16, kernel_scale_f16_4, kernel_scale_f16_nc; - cl_kernel kernel_sqr_cont_f32, kernel_sqr_cont_f32_4, kernel_sqr_cont_f16, kernel_sqr_cont_f16_4; - cl_kernel kernel_sqrt_cont_f32, kernel_sqrt_cont_f32_4, kernel_sqrt_cont_f16, kernel_sqrt_cont_f16_4; - cl_kernel kernel_mean_f32, kernel_mean_f32_4; - cl_kernel kernel_silu, kernel_silu_4, kernel_silu_nc; - cl_kernel kernel_silu_f16, kernel_silu_f16_4, kernel_silu_f16_nc; - cl_kernel kernel_gelu, kernel_gelu_4; - cl_kernel kernel_gelu_erf, kernel_gelu_erf_4; - cl_kernel kernel_gelu_quick, kernel_gelu_quick_4; - cl_kernel kernel_relu; - cl_kernel kernel_sigmoid_f32, kernel_sigmoid_f16; - cl_kernel kernel_sigmoid_f32_nc, kernel_sigmoid_f16_nc; - cl_kernel kernel_tri; - cl_kernel kernel_fill; - cl_kernel kernel_arange; - cl_kernel kernel_clamp, kernel_clamp_nc; - cl_kernel kernel_geglu, kernel_reglu, kernel_swiglu, kernel_swiglu_oai, kernel_swiglu_clamp, kernel_geglu_erf, - kernel_geglu_quick, kernel_geglu_f16, kernel_reglu_f16, kernel_swiglu_f16, kernel_swiglu_oai_f16, kernel_swiglu_clamp_f16, - kernel_geglu_erf_f16, kernel_geglu_quick_f16; - cl_kernel kernel_norm, kernel_norm_mul_add; - cl_kernel kernel_rms_norm, kernel_rms_norm_mul; - cl_kernel kernel_rms_norm_mul_add = nullptr; // fused rms_norm(x)*w + b (residual) - cl_kernel kernel_l2_norm_f32; - cl_kernel kernel_group_norm, kernel_group_norm_mul_add; - cl_kernel kernel_diag_f32; - cl_kernel kernel_soft_max, kernel_soft_max_4; - cl_kernel kernel_soft_max_f16, kernel_soft_max_4_f16; - cl_kernel kernel_fa_decompose_soft_max_4_f16, kernel_fa_decompose_scale_rows_f32; - cl_kernel kernel_mul_mm_f16_f32_kq_p8 = nullptr; - cl_kernel kernel_mul_mm_q8_f32_kqv = nullptr; - cl_kernel kernel_fa_p8_fixup = nullptr; - cl_kernel kernel_fa_kqv_direct_f16 = nullptr; - cl_kernel kernel_fa_kqv_direct_reduce = nullptr; - cl_kernel kernel_fa_v_transpose_q8 = nullptr; - cl_kernel kernel_fa_q8_rows_f16 = nullptr; - cl_kernel kernel_fa_q8_rows_f32 = nullptr; - cl_kernel kernel_mul_mm_q8_kq_p8 = nullptr; - cl_kernel kernel_mul_mm_q8_kq_p8_dk512 = nullptr; - ggml_opencl_fa_kernels fa; #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_adreno_xmem_attn_state adreno_xmem_attn; -#endif - cl_kernel kernel_top_k_f32, kernel_top_k_merge_f32; - cl_kernel kernel_top_k_mask[2], kernel_top_k_mask_fill[2]; - cl_kernel kernel_lightning_indexer; - cl_kernel kernel_get_rows_f32, kernel_get_rows_f16, kernel_get_rows_i32, kernel_get_rows_q4_0; - cl_kernel kernel_set_rows_f32_i64, kernel_set_rows_f32_i32, kernel_set_rows_f16_i64, kernel_set_rows_f16_i32; - cl_kernel kernel_set_rows_q8_0_i64, kernel_set_rows_q8_0_i32; - cl_kernel kernel_set_rows_q8_0_soa_i64, kernel_set_rows_q8_0_soa_i32; - cl_kernel kernel_set_rows_q4_0_i64, kernel_set_rows_q4_0_i32; - cl_kernel kernel_set_rows_q4_0_soa_i64, kernel_set_rows_q4_0_soa_i32; - cl_kernel kernel_rope_norm_f32, kernel_rope_norm_f16, kernel_rope_neox_f32, kernel_rope_neox_f16; - cl_kernel kernel_rope_multi_f32, kernel_rope_multi_f16, kernel_rope_vision_f32, kernel_rope_vision_f16; - cl_kernel kernel_cpy_f16_f16, kernel_cpy_f16_f32, kernel_cpy_f32_f16, kernel_cpy_f32_f32, kernel_cpy_i32_i32, kernel_cpy_i32_f32, kernel_cpy_f32_i32; - cl_kernel kernel_cpy_f32_f32_pack = nullptr; - cl_kernel kernel_cpy_f32_f32_flat = nullptr; - cl_kernel kernel_mul_mat_f32_f32; - cl_kernel kernel_mul_mv_f32_f32_r2 = nullptr; - cl_kernel kernel_fwht[2] = {}; - size_t fwht_workgroup_size[2] = {}; - cl_kernel kernel_mul_mat_f16_f16; - cl_kernel kernel_mul_mat_f16_f32_1row; - cl_program program_mul_mv_f16_f32_mrow; - cl_kernel kernel_mul_mat_f16_f32_mrow = nullptr; // multi-row decode GEMV (attn proj + lm_head) - cl_kernel kernel_mul_mat_f16_f32_mrow_r2 = nullptr; - cl_kernel kernel_mul_mat_f16_f32_mrow_r4 = nullptr; - cl_kernel kernel_mul_mat_f16_f32_mrow_h8 = nullptr; - cl_kernel kernel_mul_mat_f16_f32_mrow_h8r2 = nullptr; - cl_kernel kernel_mul_mat_f16_f32; - cl_kernel kernel_mul_mat_f16_f32_l4; - cl_kernel kernel_mul_mat_f16_f32_l4_dr; - cl_kernel kernel_mul_mat_f16_f32_l4_dr_ls; - cl_kernel kernel_mul_mat_f16_f32_l4_dr_lq; - cl_kernel kernel_mul_mat_f16_f32_l4_x8 = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_x8_pair = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa4 = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa4_img = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_y8 = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_y8_gqa = nullptr; - cl_kernel kernel_mul_mat_f16_f32_l4_y8_gqa_img = nullptr; - cl_kernel kernel_mul_mat_f16_f32_tiled; - cl_kernel kernel_adreno_xmem_pack_src_f32; - cl_kernel kernel_adreno_xmem_prepack_weight_f16; - cl_kernel kernel_gemm_xmem_f16_f32_os8; - cl_kernel kernel_adreno_xmem_store_dst_f32; - cl_kernel kernel_mul_mm_f16_f32_kqv; - cl_kernel kernel_mul_mm_f16_f32_kq; - cl_kernel kernel_mul_mat_q4_0_f32, kernel_mul_mat_q4_0_f32_v; - cl_kernel kernel_convert_block_q1_0, kernel_restore_block_q1_0; - cl_kernel kernel_convert_block_q4_0, kernel_restore_block_q4_0; - cl_kernel kernel_convert_block_q4_0_trans4_ns, kernel_restore_block_q4_0_trans4_ns; - cl_kernel kernel_convert_block_q4_1, kernel_restore_block_q4_1; - cl_kernel kernel_convert_block_q4_1_trans4_ns, kernel_restore_block_q4_1_trans4_ns; - cl_kernel kernel_convert_block_q5_0, kernel_restore_block_q5_0; - cl_kernel kernel_convert_block_q5_0_trans4_ns, kernel_restore_block_q5_0_trans4_ns; - cl_kernel kernel_convert_block_q5_1, kernel_restore_block_q5_1; - cl_kernel kernel_convert_block_q5_1_trans4_ns, kernel_restore_block_q5_1_trans4_ns; - cl_kernel kernel_convert_block_q4_k_trans4_ns, kernel_restore_block_q4_k_trans4_ns; - cl_kernel kernel_convert_block_q5_k_trans4_ns, kernel_restore_block_q5_k_trans4_ns; - cl_kernel kernel_convert_block_q6_k_trans4_ns, kernel_restore_block_q6_k_trans4_ns; - cl_kernel kernel_convert_block_mxfp4, kernel_convert_block_mxfp4_trans, kernel_restore_block_mxfp4, kernel_restore_block_mxfp4_trans; - cl_kernel kernel_convert_block_mxfp4_trans4_ns, kernel_restore_block_mxfp4_trans4_ns; - cl_kernel kernel_convert_block_q8_0, kernel_restore_block_q8_0, kernel_restore_block_q8_0_trans; - cl_kernel kernel_dequant_q8_0_f16_view_aos; - cl_kernel kernel_dequant_q8_0_f32_view_aos; - cl_kernel kernel_dequant_q4_0_f16_view_aos; - cl_kernel kernel_dequant_q4_0_f32_view_aos; - cl_kernel kernel_convert_block_q6_K_noshuffle, kernel_restore_block_q6_K_noshuffle; - cl_kernel kernel_convert_bf16_to_f16, kernel_convert_f16_to_bf16; - cl_kernel kernel_mul_mat_q4_0_f32_8x_flat; - cl_kernel kernel_convert_block_q4_0_noshuffle; - cl_kernel kernel_restore_block_q4_0_noshuffle; - cl_kernel kernel_convert_block_q4_1_noshuffle; - cl_kernel kernel_restore_block_q4_1_noshuffle; - cl_kernel kernel_convert_block_q5_0_noshuffle; - cl_kernel kernel_restore_block_q5_0_noshuffle; - cl_kernel kernel_convert_block_q5_1_noshuffle; - cl_kernel kernel_restore_block_q5_1_noshuffle; - cl_kernel kernel_convert_block_q4_K_noshuffle; - cl_kernel kernel_restore_block_q4_K_noshuffle; - cl_kernel kernel_convert_block_q4_K, kernel_restore_block_q4_K; - cl_kernel kernel_convert_block_q5_K, kernel_restore_block_q5_K; - cl_kernel kernel_convert_block_q5_K_noshuffle; - cl_kernel kernel_restore_block_q5_K_noshuffle; - cl_kernel kernel_convert_block_q6_K, kernel_restore_block_q6_K; - cl_kernel kernel_convert_block_iq4_nl, kernel_restore_block_iq4_nl; - cl_kernel kernel_convert_block_iq4_nl_noshuffle; - cl_kernel kernel_restore_block_iq4_nl_noshuffle; - cl_kernel kernel_mul_mv_q1_0_f32, kernel_mul_mv_q1_0_f32_flat; - cl_kernel kernel_mul_mat_q4_0_f32_1d_8x_flat, kernel_mul_mat_q4_0_f32_1d_16x_flat; - cl_kernel kernel_mul_mv_q4_1_f32; - cl_kernel kernel_mul_mv_q4_1_f32_flat; - cl_kernel kernel_mul_mv_q5_0_f32; - cl_kernel kernel_mul_mv_q5_0_f32_flat; - cl_kernel kernel_mul_mv_q5_1_f32; - cl_kernel kernel_mul_mv_q5_1_f32_flat; - cl_kernel kernel_convert_block_q2_K, kernel_restore_block_q2_K; - cl_kernel kernel_mul_mv_q2_K_f32_flat; - cl_kernel kernel_mul_mm_q2_k_f32_l4_lm; - cl_kernel kernel_convert_block_q2_k_noshuffle; - cl_kernel kernel_restore_block_q2_k_noshuffle; - cl_kernel kernel_gemv_noshuffle_q2_k_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_q2_k_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_q2_k_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_q2_k_q8_1_dp4a_narrow = nullptr; - int q2_k_mv_rows = 4; - int q2_k_mv_nsg = 4; - cl_kernel kernel_mul_mv_q2_K_f32; - cl_kernel kernel_convert_block_q3_K, kernel_restore_block_q3_K; - cl_kernel kernel_mul_mv_q3_K_f32_flat; - cl_kernel kernel_mul_mm_q3_k_f32_l4_lm; - cl_kernel kernel_convert_block_q3_k_noshuffle, kernel_restore_block_q3_k_noshuffle; - cl_kernel kernel_gemv_noshuffle_q3_k_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_q3_k_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_q3_k_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_q3_k_q8_1_dp4a_narrow = nullptr; - int q3_k_mv_rows = 2; - int q3_k_mv_nsg = 8; - cl_kernel kernel_mul_mv_q3_K_f32; - cl_kernel kernel_convert_block_iq2_s, kernel_restore_block_iq2_s; - cl_kernel kernel_mul_mv_iq2_s_f32_flat; - cl_kernel kernel_mul_mm_iq2_s_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq2_s_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_s_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_s_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_s_q8_1_dp4a_narrow = nullptr; - int iq2_s_mv_nsg = 8; - ggml_cl_buffer iq2_s_grid_buffer; - cl_mem iq2_s_grid_image = nullptr; - cl_kernel kernel_mul_mv_iq2_s_f32; - cl_kernel kernel_convert_block_iq2_xs, kernel_restore_block_iq2_xs; - cl_kernel kernel_mul_mv_iq2_xs_f32_flat; - cl_kernel kernel_mul_mm_iq2_xs_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq2_xs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_xs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a_narrow = nullptr; - int iq2_xs_mv_nsg = 4; - ggml_cl_buffer iq2_xs_grid_buffer; - cl_mem iq2_xs_grid_image = nullptr; - cl_kernel kernel_mul_mv_iq2_xs_f32; - cl_kernel kernel_convert_block_iq2_xxs, kernel_restore_block_iq2_xxs; - cl_kernel kernel_mul_mv_iq2_xxs_f32_flat; - cl_kernel kernel_mul_mm_iq2_xxs_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq2_xxs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_xxs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a_narrow = nullptr; - int iq2_xxs_mv_nsg = 4; - ggml_cl_buffer iq2_xxs_grid_buffer; - cl_mem iq2_xxs_grid_image = nullptr; - cl_kernel kernel_mul_mv_iq2_xxs_f32; - cl_kernel kernel_convert_block_q2_0, kernel_restore_block_q2_0; - cl_kernel kernel_mul_mv_q2_0_f32_flat; - cl_kernel kernel_mul_mm_q2_0_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_q2_0_f32 = nullptr; - cl_kernel kernel_gemv_noshuffle_q2_0_f32_wide = nullptr; - size_t q2_0_mv_workgroup_size = 512; - size_t q2_0_mv_workgroup_size_wide = 512; - cl_kernel kernel_gemm_noshuffle_q2_0_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_q2_0_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_q2_0_q8_1_dp4a_narrow = nullptr; - int q2_0_mv_nsg = 32; - cl_kernel kernel_mul_mv_q2_0_f32; - cl_kernel kernel_convert_block_iq1_m, kernel_restore_block_iq1_m; - cl_kernel kernel_mul_mv_iq1_m_f32_flat; - cl_kernel kernel_mul_mm_iq1_m_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq1_m_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq1_m_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq1_m_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq1_m_q8_1_dp4a_narrow = nullptr; - int iq1_m_mv_nsg = 4; - cl_kernel kernel_mul_mv_iq1_m_f32; - cl_kernel kernel_convert_block_iq1_s, kernel_restore_block_iq1_s; - cl_kernel kernel_mul_mv_iq1_s_f32_flat; - cl_kernel kernel_mul_mm_iq1_s_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq1_s_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq1_s_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq1_s_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq1_s_q8_1_dp4a_narrow = nullptr; - int iq1_s_mv_nsg = 4; - ggml_cl_buffer iq1_s_grid_buffer; - cl_mem iq1_s_grid_image = nullptr; - cl_kernel kernel_mul_mv_iq1_s_f32; - cl_kernel kernel_convert_block_iq3_xxs, kernel_restore_block_iq3_xxs; - cl_kernel kernel_mul_mv_iq3_xxs_f32_flat; - cl_kernel kernel_mul_mm_iq3_xxs_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq3_xxs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq3_xxs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a_narrow = nullptr; - int iq3_xxs_mv_nsg = 4; - ggml_cl_buffer iq3_xxs_grid_buffer; - cl_mem iq3_xxs_grid_image = nullptr; - cl_kernel kernel_mul_mv_iq3_xxs_f32; - cl_kernel kernel_convert_block_iq3_s, kernel_restore_block_iq3_s; - cl_kernel kernel_mul_mv_iq3_s_f32_flat; - cl_kernel kernel_mul_mm_iq3_s_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq3_s_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq3_s_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq3_s_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq3_s_q8_1_dp4a_narrow = nullptr; - int iq3_s_mv_nsg = 4; - ggml_cl_buffer iq3_s_grid_buffer; - cl_mem iq3_s_grid_image = nullptr; - cl_kernel kernel_mul_mv_iq3_s_f32; - cl_kernel kernel_convert_block_iq4_xs, kernel_restore_block_iq4_xs; - cl_kernel kernel_convert_block_iq4_xs_noshuffle = nullptr, kernel_restore_block_iq4_xs_noshuffle = nullptr; - cl_kernel kernel_mul_mv_iq4_xs_f32_flat; - cl_kernel kernel_mul_mm_iq4_xs_f32_l4_lm; - cl_kernel kernel_gemv_noshuffle_iq4_xs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq4_xs_f32 = nullptr; - cl_kernel kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a = nullptr; - cl_kernel kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a_narrow = nullptr; - int iq4_xs_mv_nsg = 8; - cl_kernel kernel_mul_mv_iq4_xs_f32; - cl_kernel kernel_mul_mv_q4_K_f32; - cl_kernel kernel_mul_mv_q4_K_f32_flat; - cl_kernel kernel_mul_mv_q5_K_f32; - cl_kernel kernel_mul_mv_q5_K_f32_flat; - cl_kernel kernel_mul_mv_q6_K_f32; - cl_kernel kernel_mul_mv_q6_K_f32_flat; - cl_kernel kernel_mul_mv_mxfp4_f32, kernel_mul_mv_mxfp4_f32_flat; - cl_kernel kernel_mul_mv_q8_0_f32, kernel_mul_mv_q8_0_f32_flat; - cl_kernel kernel_mul_mv_iq4_nl_f32; - cl_kernel kernel_mul_mv_iq4_nl_f32_flat; - cl_kernel kernel_solve_tri_f32; - cl_kernel kernel_im2col_f32, kernel_im2col_f16; - cl_kernel kernel_im2col_3d_f32, kernel_im2col_3d_f16; - cl_kernel kernel_argmax_f32_i32; - cl_kernel kernel_argsort_f32_i32; - cl_kernel kernel_sum_rows_f32, kernel_sum_rows_f32_4; - cl_kernel kernel_dsv4_hc_pre = nullptr; - cl_kernel kernel_dsv4_hc_post[2] = {}; - size_t local_dsv4_hc_pre = 0; - size_t local_dsv4_hc_post[2] = {}; - cl_kernel kernel_cumsum_blk, kernel_cumsum_add; - cl_kernel kernel_repeat_f32, kernel_repeat_f16, kernel_repeat_i32; - cl_kernel kernel_pad; - cl_kernel kernel_tanh_f32, kernel_tanh_f32_4, kernel_tanh_f32_nc; - cl_kernel kernel_tanh_f16, kernel_tanh_f16_4, kernel_tanh_f16_nc; - cl_kernel kernel_neg_f32, kernel_neg_f32_4, kernel_neg_f32_nc; - cl_kernel kernel_neg_f16, kernel_neg_f16_4, kernel_neg_f16_nc; - cl_kernel kernel_exp_f32, kernel_exp_f32_4, kernel_exp_f32_nc; - cl_kernel kernel_exp_f16, kernel_exp_f16_4, kernel_exp_f16_nc; - cl_kernel kernel_expm1_f32, kernel_expm1_f32_4, kernel_expm1_f32_nc; - cl_kernel kernel_expm1_f16, kernel_expm1_f16_4, kernel_expm1_f16_nc; - cl_kernel kernel_abs_f32, kernel_abs_f32_4, kernel_abs_f32_nc; - cl_kernel kernel_abs_f16, kernel_abs_f16_4, kernel_abs_f16_nc; - cl_kernel kernel_sgn_f32, kernel_sgn_f32_4, kernel_sgn_f32_nc, kernel_sgn_f16, kernel_sgn_f16_4, kernel_sgn_f16_nc; - cl_kernel kernel_step_f32, kernel_step_f32_4, kernel_step_f32_nc, kernel_step_f16, kernel_step_f16_4, kernel_step_f16_nc; - cl_kernel kernel_elu_f32, kernel_elu_f32_4, kernel_elu_f32_nc, kernel_elu_f16, kernel_elu_f16_4, kernel_elu_f16_nc; - cl_kernel kernel_xielu_f32 = nullptr; - cl_kernel kernel_xielu_f16 = nullptr; - cl_kernel kernel_hardswish_f32, kernel_hardswish_f32_4, kernel_hardswish_f32_nc, kernel_hardswish_f16, kernel_hardswish_f16_4, kernel_hardswish_f16_nc; - cl_kernel kernel_hardsigmoid_f32, kernel_hardsigmoid_f32_4, kernel_hardsigmoid_f32_nc, kernel_hardsigmoid_f16, kernel_hardsigmoid_f16_4, kernel_hardsigmoid_f16_nc; - cl_kernel kernel_floor_f32, kernel_floor_f32_4, kernel_floor_f32_nc, kernel_floor_f16, kernel_floor_f16_4, kernel_floor_f16_nc; - cl_kernel kernel_ceil_f32, kernel_ceil_f32_4, kernel_ceil_f32_nc, kernel_ceil_f16, kernel_ceil_f16_4, kernel_ceil_f16_nc; - cl_kernel kernel_round_f32, kernel_round_f32_4, kernel_round_f32_nc, kernel_round_f16, kernel_round_f16_4, kernel_round_f16_nc; - cl_kernel kernel_trunc_f32, kernel_trunc_f32_4, kernel_trunc_f32_nc, kernel_trunc_f16, kernel_trunc_f16_4, kernel_trunc_f16_nc; - cl_kernel kernel_log_f32, kernel_log_f32_4, kernel_log_f32_nc, kernel_log_f16, kernel_log_f16_4, kernel_log_f16_nc; - cl_kernel kernel_softplus_f32, kernel_softplus_f32_4, kernel_softplus_f32_nc; - cl_kernel kernel_softplus_f16, kernel_softplus_f16_4, kernel_softplus_f16_nc; - cl_kernel kernel_upscale; - cl_kernel kernel_upscale_bilinear; - cl_kernel kernel_concat_b1, kernel_concat_b2, kernel_concat_b4, kernel_concat_b8, kernel_concat_b4_pack; - cl_kernel kernel_conv_2d_f16; - cl_kernel kernel_conv_2d_f32; - cl_kernel kernel_conv_2d_f16_f32; - cl_kernel kernel_conv2d_dw_f32_f32, kernel_conv2d_dwf16_f32; - cl_kernel kernel_ssm_conv_f32_f32, kernel_ssm_conv_f32_f32_4; - // [size_idx][kda][tgpp][replay] where size_idx: 0=S_V=16, 1=32, 2=64, 3=128; kda: 0 or 1. - // tgpp 0 = TG variant (COLS_PER_LANE_GROUP=1), tgpp 1 = prefill variant (COLS_PER_LANE_GROUP=4). - cl_kernel kernel_gated_delta_net_f32[4][2][2][2] = {}; - cl_kernel kernel_ssm_scan_f32 = nullptr; - cl_kernel kernel_ssm_scan_f32_mamba2_d128 = nullptr; - cl_kernel kernel_ssm_scan_f32_mamba2_d256 = nullptr; - - cl_kernel kernel_timestep_embedding; - cl_kernel kernel_gemv_moe_q4_0_f32_ns, kernel_gemm_moe_q4_0_f32_ns, kernel_gemm_moe_q4_0_f32_ns_bin; - cl_kernel kernel_gemm_moe_q8_0_f32_ns; - cl_kernel kernel_gemv_moe_q4_1_f32_ns, kernel_gemm_moe_q4_1_f32_ns, kernel_gemm_moe_q4_1_f32_ns_bin; - cl_kernel kernel_gemv_moe_q5_0_f32_ns, kernel_gemm_moe_q5_0_f32_ns; - cl_kernel kernel_gemv_moe_q5_1_f32_ns, kernel_gemm_moe_q5_1_f32_ns; - cl_kernel kernel_gemv_moe_q4_k_f32_ns, kernel_gemm_moe_q4_k_f32_ns, kernel_gemm_moe_q4_k_f32_ns_bin; - cl_kernel kernel_gemv_moe_q4_k_f32_ns_wimg = nullptr; // weight-as-texture MoE decode GEMV (opt-in) - cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a = nullptr; // dp4a (int8) prefill GEMM variant - cl_kernel kernel_moe_reorder_quant_a_q8_1; // fused reorder + q8_1 quant for the dp4a GEMM - cl_kernel kernel_transpose_activation_q8; // per-tile transpose of q8_1 activations for the ldck dp4a GEMM - cl_kernel kernel_gemm_moe_q8_1_dp4a_q80 = nullptr; // generic dp4a MoE GEMM (MOE_QT=80), opt-in - cl_kernel kernel_moe_expand_scale_q8_0 = nullptr; // q8_0 per-block d -> uniform scale[16] - cl_kernel kernel_gemm_moe_q8_1_dp4a_q50 = nullptr; // generic dp4a MoE GEMM (MOE_QT=50, q5_0), opt-in - cl_kernel kernel_moe_expand_scale_q5_0 = nullptr; // q5_0 d -> uniform scale[2]/min[1] per 32-block - cl_kernel kernel_gemm_moe_q8_1_dp4a_q5k = nullptr; // generic dp4a MoE GEMM (MOE_QT=5, q5_K), opt-in - cl_kernel kernel_moe_expand_scale_q5_K = nullptr; // q5_K 6-bit s[] -> uniform scale[16]/min[8] - cl_kernel kernel_gemv_moe_q5_k_f32_ns, kernel_gemm_moe_q5_k_f32_ns; - cl_kernel kernel_gemv_moe_q6_k_f32_ns, kernel_gemm_moe_q6_k_f32_ns, kernel_gemm_moe_q6_k_f32_ns_bin; - cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a = nullptr; // dp4a (int8) q6_K MoE prefill GEMM - cl_kernel kernel_gemv_moe_mxfp4_f32, kernel_gemm_moe_mxfp4_f32; - cl_kernel kernel_gemv_moe_mxfp4_f32_ns, kernel_gemm_moe_mxfp4_f32_ns, kernel_gemm_moe_mxfp4_f32_ns_bin; - cl_kernel kernel_gemv_moe_mxfp4_f32_ns_wimg = nullptr; // weight-as-texture MoE decode GEMV - cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a = nullptr; // dp4a (int8) mxfp4 MoE prefill GEMM - cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a = nullptr; // dp4a (int8) q4_0 MoE prefill GEMM - cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) mxfp4 MoE prefill GEMM - cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin = nullptr; // binary dp4a (int8) mxfp4 MoE prefill GEMM using ldck - cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 mxfp4 MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_0 MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_1 MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_0 MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_1 MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q4_k MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q5_k MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr; // binary malu int8 q6_k MoE prefill GEMM (A850) - cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q4_0 MoE prefill GEMM - cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q4_k MoE prefill GEMM - cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_bin = nullptr; // binary dp4a (int8) q6_k MoE prefill GEMM - cl_kernel kernel_moe_reorder_b; - cl_kernel kernel_moe_reorder_b_f16 = nullptr; // f16 B for the coopmat mxfp4 MoE GEMM - cl_kernel kernel_gemm_moe_mxfp4_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix mxfp4 MoE prefill GEMM, A850 only - cl_kernel kernel_gemm_moe_q4_0_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix q4_0 MoE prefill GEMM, A850 only - cl_kernel kernel_gemm_moe_q4_1_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix q4_1 MoE prefill GEMM, A850 only - cl_kernel kernel_gemm_moe_q5_0_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix q5_0 MoE prefill GEMM, A850 only - cl_kernel kernel_gemm_moe_q5_1_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix q5_1 MoE prefill GEMM, A850 only - cl_kernel kernel_gemm_moe_q4_k_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix q4_k MoE prefill GEMM, A850 only - cl_kernel kernel_gemm_moe_q5_k_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix q5_k MoE prefill GEMM, A850 only - cl_kernel kernel_gemm_moe_q6_k_f32_ns_coopmat = nullptr; // cl_qcom_kernel_cooperative_matrix q6_k MoE prefill GEMM, A850 only - cl_kernel kernel_moe_histogram, kernel_moe_scan, kernel_moe_fill, kernel_moe_scatter; - cl_kernel kernel_moe_scatter_stable = nullptr; // deterministic slot assignment - cl_kernel kernel_moe_zero_dst; - cl_kernel kernel_moe_combine_f32 = nullptr; // fused router-weight mul + cross-expert sum - cl_kernel kernel_moe_combine_bias_f32 = nullptr; // same, with the down-projection bias add folded in - cl_kernel kernel_mul_mv_id_f32_f32; - cl_kernel kernel_mul_mm_id_f32_f32; - cl_kernel kernel_mul_mv_id_q4_0_f32_8x_flat; - cl_kernel kernel_mul_mv_id_q8_0_f32, kernel_mul_mv_id_q8_0_f32_flat; - cl_kernel kernel_mul_mv_id_mxfp4_f32; - cl_kernel kernel_mul_mv_id_mxfp4_f32_flat; - cl_kernel kernel_mul_mm_f32_f32_l4_lm; - cl_kernel kernel_gemv_f32_f32_mc; // multi-column (small-N) f32 GEMV for spec/MTP verify - cl_kernel kernel_gemv_f32_f32_mcr = nullptr; - cl_kernel kernel_mul_mm_f16_f32_l4_lm; - cl_kernel kernel_mul_mm_f16_f32_l4_lm_n8; - cl_kernel kernel_mul_mm_q1_0_f32_l4_lm; - cl_kernel kernel_mul_mm_q4_0_f32_l4_lm; - cl_kernel kernel_mul_mm_q4_1_f32_l4_lm; - cl_kernel kernel_mul_mm_q5_0_f32_l4_lm; - cl_kernel kernel_mul_mm_q5_1_f32_l4_lm; - cl_kernel kernel_mul_mm_q8_0_f32_l4_lm; - cl_kernel kernel_mul_mm_q4_k_f32_l4_lm; - cl_kernel kernel_mul_mm_q5_k_f32_l4_lm; - cl_kernel kernel_mul_mm_q6_k_f32_l4_lm; - cl_kernel kernel_mul_mm_iq4_nl_f32_l4_lm; - - std::vector profiling_info; - std::vector profiling_results; - - void flush_profiling_batch() { - if (profiling_info.empty()) { - return; - } - - // Populate profiling info - for (ProfilingInfo & info : profiling_info) { - cl_ulong cmd_queued; - cl_ulong cmd_submit; - cl_ulong cmd_start; - cl_ulong cmd_end; - cl_ulong cmd_complete; - - CL_CHECK(clWaitForEvents(1, &info.evt)); - CL_CHECK(clGetEventProfilingInfo( - info.evt, CL_PROFILING_COMMAND_QUEUED, sizeof(cl_ulong), &cmd_queued, NULL)); - CL_CHECK(clGetEventProfilingInfo( - info.evt, CL_PROFILING_COMMAND_SUBMIT, sizeof(cl_ulong), &cmd_submit, NULL)); - CL_CHECK(clGetEventProfilingInfo( - info.evt, CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &cmd_start, NULL)); - CL_CHECK(clGetEventProfilingInfo( - info.evt, CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &cmd_end, NULL)); - CL_CHECK(clGetEventProfilingInfo( - info.evt, CL_PROFILING_COMMAND_COMPLETE, sizeof(cl_ulong), &cmd_complete, NULL)); - CL_CHECK(clReleaseEvent(info.evt)); - info.evt = nullptr; - - char kernel_name[512]; - CL_CHECK(clGetKernelInfo(info.kernel, CL_KERNEL_FUNCTION_NAME, - sizeof(kernel_name), kernel_name, NULL)); - info.kernel_name = kernel_name; - - info.cmd_queued = cmd_queued; - info.cmd_submit = cmd_submit; - info.cmd_start = cmd_start; - info.cmd_end = cmd_end; - - info.cmd_queued_duration_ns = cmd_submit - cmd_queued; - info.cmd_submit_duration_ns = cmd_start - cmd_submit; - info.cmd_duration_ns = cmd_end - cmd_start; - info.cmd_complete_duration_ns = cmd_complete - cmd_end; - info.cmd_total_duration_ns = cmd_complete - cmd_queued; - } - profiling_results.insert(profiling_results.end(), - std::make_move_iterator(profiling_info.begin()), - std::make_move_iterator(profiling_info.end())); - profiling_info.clear(); + GGML_LOG_INFO("ggml_opencl: using kernels optimized for Adreno (GGML_OPENCL_USE_ADRENO_KERNELS)\n"); + if (backend_ctx->adreno_xmem_gemm_enabled) { + GGML_LOG_INFO("ggml_opencl: Adreno xmem F16xF32 GEMM enabled (temporary weight prepack)\n"); } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS - void write_profiling_info() { - if (profiling_results.empty()) { - return; - } - - // Dump a csv - FILE * fperf = fopen("cl_profiling.csv", "w"); - if (!fperf) { - GGML_LOG_ERROR("Failed to open cl_profiling.csv\n"); - return; - } - - fprintf(fperf, "op name, kernel name, exec duration (ms), global size, local size, output size\n"); - for (const ProfilingInfo & info : profiling_results) { - fprintf(fperf, "%s,%s,%f,%zux%zux%zu,%zux%zux%zu,%zux%zux%zux%zu\n", - info.op_name.c_str(), info.kernel_name.c_str(), - info.cmd_duration_ns/1.e6f, - info.global_size[0], info.global_size[1], info.global_size[2], - info.local_size[0], info.local_size[1], info.local_size[2], - info.output_size[0], info.output_size[1], info.output_size[2], info.output_size[3]); - } - fclose(fperf); - - // Dump a simple chrome trace - FILE * ftrace = fopen("cl_trace.json", "w"); - if (!ftrace) { - GGML_LOG_ERROR("Failed to open cl_trace.json\n"); - return; - } - - fprintf(ftrace, "[\n"); - for (const ProfilingInfo & info : profiling_results) { - fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"B\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Host\"},\n", - info.kernel_name.c_str(), info.cmd_queued/1000); - fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"E\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Host\"},\n", - info.kernel_name.c_str(), info.cmd_submit/1000); - - fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"B\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Device\"},\n", - info.kernel_name.c_str(), info.cmd_start/1000); - fprintf(ftrace, "{\"name\": \"%s\", \"cat\": \"OpenCL\", \"ph\": \"E\", \"ts\": %" PRIu64 ", \"pid\": \"\", \"tid\": \"Device\"},\n", - info.kernel_name.c_str(), info.cmd_end/1000); + if (backend_ctx->adreno_use_large_buffer) { + if (!backend_ctx->adreno_has_large_buffer) { + GGML_LOG_INFO("ggml_opencl: Adreno large buffer requested but not supported by driver, will use regular buffer\n"); + backend_ctx->adreno_use_large_buffer = false; + } else { + GGML_LOG_INFO("ggml_opencl: Adreno large buffer enabled\n"); } - fprintf(ftrace, "]\n"); - fclose(ftrace); } - size_t get_kernel_workgroup_size(cl_kernel kernel) const { - size_t workgroup_size = 0; - size_t ret_size = 0; - CL_CHECK( - clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE, - sizeof(size_t), &workgroup_size, &ret_size)); - GGML_ASSERT(sizeof(size_t) == ret_size); - return workgroup_size; + if (dev_ctx->opfilter) { + // for information only, the actual regex object is created in ggml_opencl_is_device_supported + GGML_LOG_INFO("ggml_opencl: opfilter regex = \"%s\"\n", dev_ctx->opfilter_str.c_str()); } - void enqueue_ndrange_kernel(cl_kernel kernel, cl_uint work_dim, size_t *global_work_size, size_t *local_work_size, const ggml_tensor * tensor) { - // From the spec on clEnqueueNDRangeKernel: - // If the device associated with command_queue is an OpenCL 2.1 or newer device, - // and global_work_size is NULL or the value in any passed dimension is zero, - // then the kernel command will trivially succeed after its event dependencies - // are satisfied and subsequently update its completion event. - // So this ensures such cases always return trivially without causing errors in - // case of an older device. - for (cl_uint i = 0; i < work_dim; i++) { - if (global_work_size[i] == 0) { - return; - } - } #ifdef GGML_OPENCL_PROFILING - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - - profiling_info.emplace_back(); - populateProfilingInfo(profiling_info.back(), evt, kernel, work_dim, global_work_size, local_work_size, tensor); - if (profiling_info.size() >= 2048) { - flush_profiling_batch(); - } -#else - GGML_UNUSED(tensor); - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, work_dim, NULL, global_work_size, local_work_size, 0, NULL, NULL)); + GGML_LOG_INFO("ggml_opencl: OpenCL profiling enabled\n"); #endif - } +} - const void * get_adreno_bin_kernel(const std::string &kernel_name, size_t *bin_size) const { - if (!get_adreno_bin_kernel_func) { - return nullptr; - } +// check if device should be accepted +static bool ggml_opencl_is_device_supported(ggml_backend_dev_t dev) { + GGML_ASSERT(dev); + GGML_ASSERT(dev->context); - size_t sz = 0; - const void * kernel_bin = get_adreno_bin_kernel_func( - kernel_name.c_str(), device_name.c_str(), driver_version.c_str(), &sz); - if (bin_size) { - *bin_size = sz; - } - return kernel_bin; - } + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; + GGML_ASSERT(dev_ctx->platform); + GGML_ASSERT(dev_ctx->device); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Transpose kernels - cl_program program_transpose; - - cl_kernel kernel_transpose_32; - cl_kernel kernel_transpose_32_16; - cl_kernel kernel_transpose_16; - cl_kernel kernel_transpose_8_buf; - cl_kernel kernel_transpose_16_buf; - cl_kernel kernel_transpose_32_buf; - cl_kernel kernel_transpose_16_4x1; - - // Gemm and Gemv related programs, kernels, etc - cl_kernel kernel_gemm_noshuffle_q4_0_f32; - cl_kernel kernel_gemv_noshuffle_q4_0_f32; - cl_kernel kernel_gemv_noshuffle_q4_0_f32_mc3; // multi-column (N=3) verify GEMV (spec/MTP) - cl_kernel kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin; - cl_kernel kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin; - cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin; - cl_kernel kernel_gemv_noshuffle_q4_0_f32_32b_trans; - cl_kernel kernel_gemv_noshuffle_q4_0_f32_4096_1_11008; - cl_kernel kernel_gemv_noshuffle_q4_0_f32_4096_1_4096; - cl_kernel kernel_gemv_noshuffle_q4_0_f32_11008_1_4096; - cl_kernel kernel_gemv_noshuffle_q4_0_f32_32000_1_4096; - cl_kernel kernel_gemv_noshuffle_q4_1_f32; - cl_kernel kernel_gemv_noshuffle_q4_1_f32_mc3; // multi-column (N=3) verify GEMV (spec/MTP) - cl_kernel kernel_gemm_noshuffle_q4_1_f32; - cl_kernel kernel_gemm_noshuffle_q8_0_f32, kernel_gemm_noshuffle_q8_0_f32_bin; - cl_kernel kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin = nullptr; - cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a = nullptr; // dp4a (int8) dense q8_0 prefill GEMM (opt-in) - cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4 = nullptr; - cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg = nullptr; // q8_0 dense dp4a, weights via texture (opt-in) - cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin = nullptr; - cl_kernel kernel_gemv_noshuffle_q8_0_f32; - cl_kernel kernel_gemv_noshuffle_q8_0_f32_splitk; // split-K across WGs (small-M decode) - cl_kernel kernel_gemv_noshuffle_q8_0_f32_mc; // multi-column (N 2..4) verify GEMV - cl_kernel kernel_gemm_noshuffle_q1_0_f32; - cl_kernel kernel_gemv_noshuffle_q1_0_f32; - cl_kernel kernel_gemv_noshuffle_q1_0_f32_nsg1 = nullptr; - int min_m_gemv_nsg1_q1_0 = 0; - cl_kernel kernel_gemv_noshuffle_q4_k_f32; - cl_kernel kernel_gemv_noshuffle_q4_k_f32_o4; // 4-output-per-WI, long-vocab lm_head - cl_kernel kernel_gemv_noshuffle_q4_k_f32_tiled; // tiled-wide layout (opt-in) - cl_kernel kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a = nullptr; - cl_kernel kernel_gemv_noshuffle_q4_k_f32_splitk; // split-K across WGs (small-M decode) - cl_kernel kernel_gemv_splitk_reduce_f32; // sums split-K per-slice partials - cl_kernel kernel_gemv_noshuffle_q4_k_f32_glu; // fused gate+up GEMV + GLU (FFN) - cl_kernel kernel_convert_block_q4_k_tiled_ns; // tiled-wide convert (opt-in) - cl_kernel kernel_gemv_noshuffle_q4_k_f32_mc3; // multi-column (N=3) verify GEMV - cl_kernel kernel_gemm_noshuffle_q4_k_f32; - cl_kernel kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin; - cl_kernel kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin; - cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin; - cl_kernel kernel_gemv_noshuffle_q4_k_f32_32b_trans; - cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a = nullptr; // dp4a (int8) dense prefill GEMM - cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4 = nullptr; - cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg = nullptr; // dp4a dense prefill GEMM, weights via texture (X1 opt-in) - cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow = nullptr; - cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow_wimg = nullptr; - int tile_n_dp4a_q4_k = 32; - int tile_n_dp4a_narrow_q4_k = 32; - int max_n_dp4a_narrow_q4_k = 16; - cl_kernel kernel_gemm_noshuffle_q5_k_q8_1_dp4a = nullptr; // dp4a (int8) dense q5_K prefill GEMM - cl_kernel kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4 = nullptr; - cl_kernel kernel_gemm_noshuffle_q6_k_q8_1_dp4a = nullptr; // dp4a (int8) dense q6_K prefill GEMM - cl_kernel kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4 = nullptr; - cl_kernel kernel_quant_a_q8_1; // plain activation q8_1 pre-pass - cl_kernel kernel_gemm_noshuffle_q4_k_f32_r1; - cl_kernel kernel_gemm_noshuffle_q4_k_f32_kimg; - cl_kernel kernel_gemm_noshuffle_q4_k_f32_cok; - cl_kernel kernel_gemv_noshuffle_q6_K_f32; - cl_kernel kernel_gemv_noshuffle_q6_K_f32_o4; - cl_kernel kernel_gemv_noshuffle_q6_K_f32_o4_global; // weights via __global (opt-in) - cl_kernel kernel_gemv_noshuffle_q6_K_f32_tiled; // tiled-wide layout (opt-in) - cl_kernel kernel_gemv_noshuffle_q6_K_f32_tiled_mc3; // tiled multi-column (N 2..4) verify lm_head - cl_kernel kernel_gemm_noshuffle_q6_K_f32_tiled; // batched (N>1) over the tiled layout - cl_kernel kernel_convert_block_q6_k_tiled_ns; // tiled-wide convert (opt-in) - cl_kernel kernel_gemv_noshuffle_q6_K_f32_mc3; // multi-column (N=3) verify GEMV - cl_kernel kernel_gemm_noshuffle_q6_K_f32; - cl_kernel kernel_gemm_noshuffle_q6_K_f32_cok; - cl_kernel kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin; - cl_kernel kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin; - cl_kernel kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin; - cl_kernel kernel_gemv_noshuffle_q6_k_f32_32b_trans; - cl_kernel kernel_gemv_noshuffle_q5_k_f32; - cl_kernel kernel_gemv_noshuffle_q5_k_f32_mc3; // multi-column (N=3) verify GEMV (spec/MTP) - cl_kernel kernel_gemm_noshuffle_q5_k_f32; - cl_kernel kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin; - cl_kernel kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin; - cl_kernel kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin; - cl_kernel kernel_gemv_noshuffle_q5_k_f32_32b_trans; - cl_kernel kernel_gemv_noshuffle_q5_0_f32; - cl_kernel kernel_gemm_noshuffle_q5_0_f32; - cl_kernel kernel_gemm_noshuffle_q5_0_q8_1_dp4a = nullptr; // dp4a (int8) dense q5_0 prefill GEMM - cl_kernel kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg = nullptr; // q5_0 dense dp4a, qs plane via texture (opt-in) - cl_kernel kernel_gemv_noshuffle_q5_1_f32; - cl_kernel kernel_gemm_noshuffle_q5_1_f32; - cl_kernel kernel_gemv_noshuffle_iq4_nl_f32; - cl_kernel kernel_gemm_noshuffle_iq4_nl_f32; - cl_kernel kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a = nullptr; // dp4a (int8) dense IQ4_NL prefill GEMM - cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a = nullptr; // dp4a (int8) dense q4_0 prefill GEMM - cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 = nullptr; - cl_kernel kernel_pack_b_f16_coopmat = nullptr; - cl_kernel kernel_gemm_noshuffle_q4_0_f32_coopmat = nullptr; - cl_kernel kernel_gemm_noshuffle_q5_0_f32_coopmat = nullptr; - cl_kernel kernel_gemm_noshuffle_q8_0_f32_coopmat = nullptr; - cl_kernel kernel_gemm_noshuffle_q4_k_f32_coopmat = nullptr; - cl_kernel kernel_gemm_noshuffle_q5_k_f32_coopmat = nullptr; - cl_kernel kernel_gemm_noshuffle_q6_k_f32_coopmat = nullptr; - cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c4 = nullptr; - cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 = nullptr; - int nsg_coopk_dp4a_q4_0 = 8; - int rows_coopk_dp4a_q4_0 = 4; - cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_c4 = nullptr; - cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_c2 = nullptr; - int nsg_coopk_dp4a_q4_k = 8; - int rows_coopk_dp4a_q4_k = 4; - cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 = nullptr; - cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 = nullptr; - int nsg_coopk_dp4a_q4_k_bin_c4 = 8; - int nsg_coopk_dp4a_q4_k_bin_c2 = 8; - cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = nullptr; - cl_kernel kernel_quant_a_q8_1_k4 = nullptr; - int nsg_coopk_dp4a_q4_k_bin_c8 = 4; - cl_mem coopk_c8_qa_image = nullptr; - cl_mem coopk_c8_qa_buffer = nullptr; - size_t coopk_c8_qa_image_bytes = 0; - cl_mem coopk_c8_ds_image = nullptr; - cl_mem coopk_c8_ds_buffer = nullptr; - size_t coopk_c8_ds_image_bytes = 0; - cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c4 = nullptr; - cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 = nullptr; - int nsg_coopk_dp4a_q6_k = 8; - int rows_coopk_dp4a_q6_k = 4; - cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = nullptr; - cl_kernel kernel_quant_a_q8_1_k4h = nullptr; - int nsg_coopk_dp4a_q6_k_bin_c8 = 4; -#endif // GGML_OPENCL_USE_ADRENO_KERNELS + if (strstr(dev_ctx->device_name.c_str(), "Adreno") || + strstr(dev_ctx->device_name.c_str(), "Qualcomm") || + strstr(dev_ctx->device_version.c_str(), "Adreno")) { + dev_ctx->gpu_family = GPU_FAMILY::ADRENO; - ~ggml_backend_opencl_context() { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - for (cl_kernel kernel : { - kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8, - kernel_quant_a_q8_1_k4, - kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8, - kernel_quant_a_q8_1_k4h - } - ) { - if (kernel != nullptr) { - CL_CHECK(clReleaseKernel(kernel)); - } - } - for (cl_mem image : {coopk_c8_qa_image, coopk_c8_ds_image}) { - if (image != nullptr) { - CL_CHECK(clReleaseMemObject(image)); - } - } -#endif - for (cl_kernel kernel : { - kernel_gemv_f32_f32_mcr, - kernel_mul_mat_scale, - kernel_xielu_f32, - kernel_xielu_f16, - kernel_mul_mm_f16_f32_kq_p8, - kernel_mul_mm_q8_f32_kqv, - kernel_fa_p8_fixup, - kernel_fa_v_transpose_q8, - kernel_fa_kqv_direct_f16, - kernel_fa_kqv_direct_reduce, - kernel_fa_q8_rows_f16, - kernel_fa_q8_rows_f32, - kernel_mul_mm_q8_kq_p8, - kernel_mul_mm_q8_kq_p8_dk512 - }) { - if (kernel != nullptr) { - CL_CHECK(clReleaseKernel(kernel)); - } - } - if (kernel_dsv4_hc_pre) { - CL_CHECK(clReleaseKernel(kernel_dsv4_hc_pre)); - } - for (int i = 0; i < 2; ++i) { - if (kernel_dsv4_hc_post[i]) { - CL_CHECK(clReleaseKernel(kernel_dsv4_hc_post[i])); - } - } - if (iq1_s_grid_image) { - CL_CHECK(clReleaseMemObject(iq1_s_grid_image)); - } - if (iq3_xxs_grid_image) { - CL_CHECK(clReleaseMemObject(iq3_xxs_grid_image)); - } - if (iq3_s_grid_image) { - CL_CHECK(clReleaseMemObject(iq3_s_grid_image)); - } - if (iq2_xxs_grid_image) { - CL_CHECK(clReleaseMemObject(iq2_xxs_grid_image)); - } - if (iq2_xs_grid_image) { - CL_CHECK(clReleaseMemObject(iq2_xs_grid_image)); - } - if (iq2_s_grid_image) { - CL_CHECK(clReleaseMemObject(iq2_s_grid_image)); + // Usually device version contains the detailed device name + dev_ctx->adreno_gen = get_adreno_gpu_gen(dev_ctx->device_version.c_str()); + if (dev_ctx->adreno_gen == ADRENO_GPU_GEN::ADRENO_UNKNOWN) { + dev_ctx->adreno_gen = get_adreno_gpu_gen(dev_ctx->device_name.c_str()); } + } else if (strstr(dev_ctx->device_name.c_str(), "Intel")) { + dev_ctx->gpu_family = GPU_FAMILY::INTEL; + } else { + GGML_LOG_WARN("ggml_opencl: unsupported GPU '%s'.\n", dev_ctx->device_name.c_str()); + dev_ctx->gpu_family = GPU_FAMILY::UNKNOWN; + return false; } - void free() { - clFinish(queue); + ggml_cl_version platform_version = get_opencl_platform_version(dev_ctx->platform); - ref_count--; - if (ref_count == 0) { - if (fa.fd_partial.buffer) { - CL_CHECK(clReleaseMemObject(fa.fd_partial.buffer)); - fa.fd_partial.buffer = nullptr; - fa.fd_partial.size = 0; - } -#ifdef GGML_OPENCL_PROFILING - flush_profiling_batch(); - write_profiling_info(); - profiling_results.clear(); -#endif - // release pooled image1d_buffer views over KV cache layers. - for (auto & kv : kq_img_pool) { - if (kv.second.image) { CL_CHECK(clReleaseMemObject(kv.second.image)); } - if (kv.second.sub_buffer) { CL_CHECK(clReleaseMemObject(kv.second.sub_buffer)); } - } - kq_img_pool.clear(); - for (auto & kv : kqv_img_pool) { - if (kv.second.image) { CL_CHECK(clReleaseMemObject(kv.second.image)); } - if (kv.second.sub_buffer) { CL_CHECK(clReleaseMemObject(kv.second.sub_buffer)); } - } - kqv_img_pool.clear(); - for (auto & kv : dequant_f16_pool) { - if (kv.second.image) { CL_CHECK(clReleaseMemObject(kv.second.image)); } - } - dequant_f16_pool.clear(); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_adreno_xmem_attn_release_scratch(this); -#endif - } + // Check device OpenCL version, OpenCL 2.0 or above is required + ggml_cl_version opencl_c_version = get_opencl_c_version(platform_version, dev_ctx->device); + if (opencl_c_version.major < 2) { + GGML_LOG_WARN("ggml_opencl: OpenCL 2.0 or above is required\n"); + return false; } -}; - -// All registered devices with a default device in the front. -static std::vector g_ggml_backend_opencl_devices; -// All device contexts associated with the devices above. -// The devices live as long as the process, so do the contexts. -static std::vector> g_ggml_backend_opencl_dev_ctxs; -inline std::string read_file(const std::string &path) { - std::ifstream ifs(path); - if (!ifs) { - return ""; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (dev_ctx->gpu_family != GPU_FAMILY::ADRENO) { + GGML_LOG_WARN("ggml_opencl: Adreno-specific kernels should not be enabled for non-Adreno GPUs; " + "run on an Adreno GPU or recompile with CMake option `-DGGML_OPENCL_USE_ADRENO_KERNELS=OFF`\n"); + return false; } - std::string text; - ifs.seekg(0, std::ios::end); - text.resize(ifs.tellg()); - ifs.seekg(0, std::ios::beg); - ifs.read(&text[0], text.size()); - return text; -} - -// fatal=false returns NULL on compile failure instead of aborting; used for -// optional FA variants that may exhaust the Adreno compiler at large DK. -// when the compiler returns CL_OUT_OF_HOST_MEMORY/CL_OUT_OF_RESOURCES (seen with DK>=256/512) -// for FA programs, do clFinish the queue to free up resources, then rebuild (up to 3x) -// if retry_queue is provided -static cl_program build_program_from_source_ex(cl_context ctx, cl_device_id dev, const char* program_buffer, const std::string &compile_opts, bool fatal, const char *tag = nullptr, cl_command_queue retry_queue = nullptr) { - if (tag) { GGML_LOG_INFO("ggml_opencl: compiling %s\n", tag); } - cl_program p; - char *program_log; - size_t program_size; - size_t log_size; - int err; - - program_size = strlen(program_buffer); - - const int max_attempts = retry_queue ? 3 : 1; - for (int attempt = 0; attempt < max_attempts; ++attempt) { - p = clCreateProgramWithSource(ctx, 1, (const char**)&program_buffer, &program_size, &err); - if(err < 0) { - GGML_LOG_ERROR("OpenCL error creating program"); - if (fatal) exit(1); - return NULL; - } +#endif - err = clBuildProgram(p, 0, NULL, compile_opts.c_str(), NULL, NULL); - if (err == CL_SUCCESS) { - return p; - } + size_t ext_str_size; + CL_CHECK(clGetDeviceInfo(dev_ctx->device, CL_DEVICE_EXTENSIONS, 0, NULL, &ext_str_size)); - const bool transient = (err == CL_OUT_OF_HOST_MEMORY || err == CL_OUT_OF_RESOURCES); - if (retry_queue && transient && attempt + 1 < max_attempts) { - clReleaseProgram(p); - GGML_LOG_WARN("ggml_opencl: transient compile failure (err=%d)%s%s — clFinish + retry (%d/%d)\n", - err, tag ? " building " : "", tag ? tag : "", attempt + 2, max_attempts); - clFinish(retry_queue); // drain in-flight ops holding driver host-heap - continue; - } + std::vector ext_buffer(ext_str_size + 1); + CL_CHECK(clGetDeviceInfo(dev_ctx->device, CL_DEVICE_EXTENSIONS, ext_str_size, ext_buffer.data(), NULL)); + ext_buffer[ext_str_size] = '\0'; - clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); - program_log = (char*) malloc(log_size + 1); - program_log[log_size] = '\0'; - clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL); - GGML_LOG_ERROR("ggml_opencl: kernel compile error (err=%d)%s%s:\n\n%s\n", err, tag ? " building " : "", tag ? tag : "", program_log); - free(program_log); - clReleaseProgram(p); - if (fatal) { - exit(1); - } - return nullptr; + // Check if ext_buffer contains cl_khr_fp16 + bool fp16_support = strstr(ext_buffer.data(), "cl_khr_fp16") != NULL; + if (!fp16_support) { + GGML_LOG_WARN("ggml_opencl: device does not support FP16\n"); + return false; } - return NULL; -} - -static cl_program build_program_from_source(ggml_backend_opencl_context * backend_ctx, const char* program_buffer, const std::string &compile_opts, bool fatal = true) { - cl_context ctx = backend_ctx->context; - cl_device_id dev = backend_ctx->device; - // Try the on-disk binary cache first. Falls through silently on miss or - // any failure; never blocks the build path. Disabled cache => nullptr. - cl_program p_cached = cl_program_cache_try_load( - backend_ctx->program_cache, ctx, dev, program_buffer, compile_opts); - if (p_cached != nullptr) { - return p_cached; + // If OpenCL 3.0 is supported, then check for cl_khr_subgroups, which becomes + // optional in OpenCL 3.0 (cl_khr_subgroup is mandatory in OpenCL 2.x) + if (opencl_c_version.major == 3 && strstr(ext_buffer.data(), "cl_khr_subgroups") == NULL && + strstr(ext_buffer.data(), "cl_intel_subgroups") == NULL) { + GGML_LOG_WARN("ggml_opencl: device does not support subgroups (cl_khr_subgroups or cl_intel_subgroups) " + "(note that subgroups is an optional feature in OpenCL 3.0)\n"); + return false; } - cl_program p = build_program_from_source_ex(ctx, dev, program_buffer, compile_opts, fatal); + clGetDeviceInfo(dev_ctx->device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(size_t), &dev_ctx->global_mem_size, NULL); - // Best-effort save of the freshly-built binary (no-op if cache disabled). - if (p != nullptr) { - cl_program_cache_try_save(backend_ctx->program_cache, p, dev, program_buffer, compile_opts); + const char * str_opfilter = getenv("GGML_OPENCL_OPFILTER"); + if (str_opfilter) { + dev_ctx->opfilter_str = str_opfilter; + dev_ctx->opfilter = new std::regex(str_opfilter, std::regex_constants::icase); } - return p; + + return true; } -static cl_program build_program_from_binary(cl_context ctx, cl_device_id dev, const char* program_buffer, const std::string &compile_opts, size_t bin_size = 0) { - cl_program p; - char *program_log; - size_t log_size; - int err; +// Initialize device if it is supported (returns nullptr if it is not). +static ggml_backend_opencl_context * ggml_cl_init(ggml_backend_dev_t dev) { + GGML_ASSERT(dev); + GGML_ASSERT(dev->context); - p = clCreateProgramWithBinary(ctx, 1, &dev, &bin_size, (const unsigned char**)&program_buffer, NULL, &err); - if(err < 0) { - GGML_LOG_ERROR("OpenCL error creating program from binary"); - exit(1); - } + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; + GGML_ASSERT(dev_ctx->platform); + GGML_ASSERT(dev_ctx->device); - err = clBuildProgram(p, 0, NULL, compile_opts.c_str(), NULL, NULL); - if(err < 0) { - clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size); - program_log = (char*) malloc(log_size + 1); - program_log[log_size] = '\0'; - clGetProgramBuildInfo(p, dev, CL_PROGRAM_BUILD_LOG, log_size + 1, program_log, NULL); - GGML_LOG_ERROR("ggml_opencl: kernel compile error:\n\n%s\n", program_log); - free(program_log); - exit(1); + if (dev_ctx->backend_ctx) { + return dev_ctx->backend_ctx; } - return p; -} + auto backend_ctx = std::make_unique(); + backend_ctx->device = dev_ctx->device; + backend_ctx->gpu_family = GPU_FAMILY::UNKNOWN; -static void load_cl_kernels_argmax(ggml_backend_opencl_context *backend_ctx) { - auto opencl_c_std = - std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + std::to_string(backend_ctx->opencl_c_version.minor); - std::string compile_opts = std::string("-cl-std=") + opencl_c_std; - - if (!backend_ctx->kernels_loaded_argmax) { - cl_int err; -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "argmax.cl.h" - }; -#else - const std::string kernel_src = read_file("argmax.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_argmax_f32_i32 = clCreateKernel(prog, "kernel_argmax_f32_i32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - backend_ctx->kernels_loaded_argmax = true; - } -} + // ref_count get increased in ggml_backend_opencl_device_init + // This function is also used to retrieve backend context, so we don't want + // to increase ref_count for each call. We only want to increase ref_count + // when the associated device is initialized + backend_ctx->ref_count = 0; -static std::string ggml_cl_q2_k_mm_options(const ggml_backend_opencl_context * backend_ctx) { - const bool x2 = backend_ctx->gpu_family == ADRENO && - (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - int bk = x2 ? 16 : 32; - bool half = x2; - if (const char * env = getenv("GGML_OPENCL_LM_BK")) { - const int value = atoi(env); - if (value == 16 || value == 32) { - bk = value; - } - } - if (const char * env = getenv("GGML_OPENCL_LM_HALF")) { - half = atoi(env) != 0; - } - return " -DBK=" + std::to_string(bk) + " -DLM_HALF=" + std::to_string(half ? 1 : 0); -} + backend_ctx->gpu_family = dev_ctx->gpu_family; + backend_ctx->adreno_gen = dev_ctx->adreno_gen; + if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO) { + ggml_cl_init_fa_dims_table(); -static std::string ggml_cl_q3_k_mm_options(const ggml_backend_opencl_context * backend_ctx) { - const bool x2 = backend_ctx->gpu_family == ADRENO && - (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - int bk = x2 ? 16 : 32; - bool half = x2; - if (const char * env = getenv("GGML_OPENCL_LM_BK")) { - const int value = atoi(env); - if (value == 16 || value == 32) { - bk = value; - } - } - if (const char * env = getenv("GGML_OPENCL_LM_HALF")) { - half = atoi(env) != 0; + // Use wave size of 64 for all Adreno GPUs. + backend_ctx->adreno_wave_size = 64; } - return " -DBK=" + std::to_string(bk) + " -DLM_HALF=" + std::to_string(half ? 1 : 0); -} -static void load_cl_kernels_argsort(ggml_backend_opencl_context *backend_ctx) { - // compiler options for general kernels - auto opencl_c_std = - std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + std::to_string(backend_ctx->opencl_c_version.minor); - std::string compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable -cl-unsafe-math-optimizations" - " -cl-finite-math-only -cl-fast-relaxed-math"; - - // argsort - if (!backend_ctx->kernels_loaded_argsort) { - cl_int err; -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "argsort.cl.h" - }; -#else - const std::string kernel_src = read_file("argsort.cl"); -#endif - backend_ctx->program_argsort_f32_i32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + // Populate backend device name + backend_ctx->device_name = dev_ctx->device_name; - CL_CHECK((backend_ctx->kernel_argsort_f32_i32 = clCreateKernel(backend_ctx->program_argsort_f32_i32, "kernel_argsort_f32_i32", &err), err)); - backend_ctx->kernels_loaded_argsort = true; - } -} + // A local ref of cl_device_id for convenience + cl_device_id device = backend_ctx->device; -static bool use_adreno_bin_kernels(ggml_backend_opencl_context * backend_ctx) { -#ifndef GGML_OPENCL_USE_ADRENO_BIN_KERNELS - GGML_UNUSED(backend_ctx); - return false; -#else - if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO) { - return false; - } - return backend_ctx->adreno_use_bin_kernels; -#endif // GGML_OPENCL_USE_ADRENO_BIN_KERNELS -} + ggml_cl_version platform_version = get_opencl_platform_version(dev_ctx->platform); + ggml_cl_version opencl_c_version = get_opencl_c_version(platform_version, device); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static bool ggml_cl_coopk_dp4a_enabled(const ggml_backend_opencl_context * backend_ctx) { - static const char * const env = getenv("GGML_OPENCL_COOPK_DP4A"); - if (env && *env && atoi(env) == 0) { - return false; - } - if (!backend_ctx->has_integer_dot) { - return false; - } - if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO) { - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::ADRENO_UNKNOWN || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X) { - return false; - } - if (backend_ctx->adreno_cl_compiler_version.type == ADRENO_CL_COMPILER_TYPE::E17) { - return false; - } - } - return true; -} - -static bool ggml_cl_coopk_dp4a_narrow_on(const ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * op, int rows) { - if (!ggml_cl_coopk_dp4a_enabled(backend_ctx)) { - return false; - } - // Each lane handles rows output rows; subgroups split K for the same rows. - // Full row groups and 32-value K blocks avoid tail checks in the kernels. - return op->ne[1] >= 2 && op->ne[1] <= 4 - && rows > 0 && (op->src[0]->ne[1] % (64 * rows)) == 0 - && (op->src[0]->ne[0] % 32) == 0; -} - -// COOPK_NSG sizes the local reduction buffer, so a smaller workgroup requires a rebuild. -static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * backend_ctx, - const char * kernel_src, const char * kernel_name, - const std::string & opts_base, int & nsg, bool fatal = true) { - while (nsg >= 2) { - const std::string opts = opts_base + " -DCOOPK_NSG=" + std::to_string(nsg); - cl_program program = build_program_from_source(backend_ctx, kernel_src, opts, fatal); - if (program == nullptr) { - return nullptr; - } - cl_int err; - cl_kernel kernel = clCreateKernel(program, kernel_name, &err); - if (err != CL_SUCCESS) { - CL_CHECK(clReleaseProgram(program)); - if (fatal) { - CL_CHECK(err); - } - return nullptr; - } - size_t max_workgroup_size = 0; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, - sizeof(max_workgroup_size), &max_workgroup_size, NULL)); - CL_CHECK(clReleaseKernel(kernel)); - if ((size_t) 64 * nsg <= max_workgroup_size) { - return program; - } - CL_CHECK(clReleaseProgram(program)); - nsg /= 2; - } - return nullptr; -} - -static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl"); -#endif - cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), - "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, - backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8, false); - if (program == nullptr) { - return; - } - - cl_int err; + backend_ctx->platform_version = platform_version; + backend_ctx->opencl_c_version = opencl_c_version; - cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", &err); - if (err != CL_SUCCESS) { - CL_CHECK(clReleaseProgram(program)); - return; - } + // Check driver version + size_t driver_version_str_size; + CL_CHECK(clGetDeviceInfo(device, CL_DRIVER_VERSION, 0, NULL, &driver_version_str_size)); + std::vector driver_version(driver_version_str_size + 1); + CL_CHECK(clGetDeviceInfo(device, CL_DRIVER_VERSION, driver_version_str_size, driver_version.data(), NULL)); + driver_version[driver_version_str_size] = '\0'; + backend_ctx->driver_version = driver_version.data(); - cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4", &err); - CL_CHECK(clReleaseProgram(program)); - if (err != CL_SUCCESS) { - CL_CHECK(clReleaseKernel(gemm)); - return; - } + backend_ctx->adreno_cl_compiler_version = get_adreno_cl_compiler_version(driver_version.data()); + backend_ctx->has_vector_subgroup_broadcast = + (backend_ctx->adreno_cl_compiler_version.type == E031 && backend_ctx->adreno_cl_compiler_version.major >= 47) || + (backend_ctx->adreno_cl_compiler_version.type == DX && backend_ctx->adreno_cl_compiler_version.major >= 17) || + (backend_ctx->adreno_cl_compiler_version.type == E17); - if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { - CL_CHECK(clReleaseKernel(gemm)); - CL_CHECK(clReleaseKernel(quant)); - return; - } + // The q6_K flat mul_mat miscompile is a defect of the older E031 compilers, not a + // property of any GPU generation: it reproduces on E031.38 (Adreno 642L) and E031.41 + // (Adreno 740) and is fixed by E031.45 (Adreno 619). Gate on the compiler so parts + // that do not need the workarounds do not pay for them. The explicit type check is + // required: newer_than_or_same() is false for every non-E031 compiler, so negating it + // alone would enable the workarounds on E17/DX. + backend_ctx->q6_k_flat_old_compiler = + backend_ctx->adreno_cl_compiler_version.type == E031 && + !backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 45, 0, 0); - backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = gemm; - backend_ctx->kernel_quant_a_q8_1_k4 = quant; -} + size_t ext_str_size; + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, 0, NULL, &ext_str_size)); + std::vector ext_buffer(ext_str_size + 1); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, ext_str_size, ext_buffer.data(), NULL)); + ext_buffer[ext_str_size] = '\0'; // ensure it is null terminated -static void load_cl_kernel_coopk_q6_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl"); -#endif - cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), - "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, - backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8, false); - if (program == nullptr) { - return; + // check support for qcom_subgroup_shuffle + if (strstr(ext_buffer.data(), "cl_qcom_subgroup_shuffle") != NULL) { + backend_ctx->has_qcom_subgroup_shuffle = true; } - cl_int err; + // Check if ext_buffer contains cl_khr_fp16 + backend_ctx->fp16_support = strstr(ext_buffer.data(), "cl_khr_fp16") != NULL; - cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", &err); - if (err != CL_SUCCESS) { - CL_CHECK(clReleaseProgram(program)); - return; - } + // check Adreno large buffer support + backend_ctx->adreno_has_large_buffer = strstr(ext_buffer.data(), "cl_qcom_large_buffer") != NULL; - cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4h", &err); - CL_CHECK(clReleaseProgram(program)); - if (err != CL_SUCCESS) { - CL_CHECK(clReleaseKernel(gemm)); - return; - } + // subgroup shuffle support (N_SPLIT>1 FA kernel) + backend_ctx->has_qcom_subgroup_shuffle = strstr(ext_buffer.data(), "cl_qcom_subgroup_shuffle") != NULL; + backend_ctx->has_khr_subgroup_shuffle = strstr(ext_buffer.data(), "cl_khr_subgroup_shuffle") != NULL; + backend_ctx->has_subgroup_shuffle = backend_ctx->has_khr_subgroup_shuffle || backend_ctx->has_qcom_subgroup_shuffle; - if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { - CL_CHECK(clReleaseKernel(gemm)); - CL_CHECK(clReleaseKernel(quant)); - return; - } + // check for cl_khr_integer_dot_product + // cl_qcom_dot_product8 uses signed * unsigned + // while cl_khr_integer_dot_product uses signed * signed -- we stick with khr for now + backend_ctx->has_integer_dot = + strstr(ext_buffer.data(), "cl_khr_integer_dot_product") != NULL; - backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = gemm; - backend_ctx->kernel_quant_a_q8_1_k4h = quant; -} + cl_uint base_align_in_bits; + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MEM_BASE_ADDR_ALIGN, sizeof(cl_uint), &base_align_in_bits, NULL)); + GGML_ASSERT(base_align_in_bits % 8u == 0); + backend_ctx->alignment = base_align_in_bits / 8u; -static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx, - const std::string & kernel_src, const char * kernel_name, - int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) { - const std::string base_opts = backend_ctx->kernel_compile_opts - + " -DCOOPK_ROWS=" + std::to_string(rows); - for (int cols = 4; cols >= 2; cols -= 2) { - int nsg_eff = nsg; - cl_program program = ggml_cl_build_program_coopk( - backend_ctx, kernel_src.c_str(), kernel_name, - base_opts + " -DCOOPK_COLS=" + std::to_string(cols), nsg_eff); - if (program == nullptr) { - return; - } - cl_int err; - cl_kernel kernel = clCreateKernel(program, kernel_name, &err); - if (err != CL_SUCCESS) { kernel = nullptr; } - CL_CHECK(clReleaseProgram(program)); - if (cols == 4) { - kernel_c4 = kernel; - nsg = nsg_eff; - if (kernel == nullptr) { - return; - } - } else { - // Both widths share one stored subgroup count for launch. - if (kernel != nullptr && nsg_eff != nsg) { - CL_CHECK(clReleaseKernel(kernel)); - kernel = nullptr; - } - kernel_c2 = kernel; - } - } -} + backend_ctx->global_mem_size = dev_ctx->global_mem_size; -static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx) { - if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO || !ggml_cl_coopk_dp4a_enabled(backend_ctx)) { - return; - } + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(size_t), &backend_ctx->max_alloc_size, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE_MAX_BUFFER_SIZE, sizeof(size_t), &backend_ctx->image_max_buffer_size, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(size_t), &backend_ctx->image2d_max_width, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(size_t), &backend_ctx->image2d_max_height, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof(size_t), &backend_ctx->image3d_max_width, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof(size_t), &backend_ctx->image3d_max_height, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof(size_t), &backend_ctx->image3d_max_depth, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &backend_ctx->max_workgroup_size, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), &backend_ctx->local_mem_size, NULL)); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_SVM_CAPABILITIES, sizeof(cl_device_svm_capabilities), &backend_ctx->svm_caps, 0)); - // Q4_0 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_coopk_q4_0_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_coopk_q4_0_q8_1_dp4a.cl"); + if (opencl_c_version.major >= 3) { + // Assume it is not available for 3.0, since it is optional in 3.0. + // If compiling against 3.0, then we can query. + backend_ctx->non_uniform_workgroups = false; +#if CL_TARGET_OPENCL_VERSION >= 300 + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_NON_UNIFORM_WORK_GROUP_SUPPORT, sizeof(cl_bool), + &backend_ctx->non_uniform_workgroups, 0)); #endif - ggml_cl_coopk_build_narrow(backend_ctx, kernel_src, "kernel_gemm_coopk_q4_0_q8_1_dp4a", - backend_ctx->rows_coopk_dp4a_q4_0, backend_ctx->nsg_coopk_dp4a_q4_0, - backend_ctx->kernel_gemm_coopk_q4_0_q8_1_dp4a_c4, - backend_ctx->kernel_gemm_coopk_q4_0_q8_1_dp4a_c2); - GGML_LOG_CONT("."); + } else { + GGML_ASSERT(opencl_c_version.major == 2); + // Non-uniform workgroup sizes is mandatory feature in v2.x. + backend_ctx->non_uniform_workgroups = true; } - // Q4_K +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno xmem F16xF32 GEMM, default on adreno, opt out with GGML_OPENCL_ADRENO_XMEM_GEMM=0. + // This helps models with f16 attention weights, e.g., gpt-oss-20b-f16 { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_coopk_q4_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a.cl"); -#endif - ggml_cl_coopk_build_narrow(backend_ctx, kernel_src, "kernel_gemm_coopk_q4_k_q8_1_dp4a", - backend_ctx->rows_coopk_dp4a_q4_k, backend_ctx->nsg_coopk_dp4a_q4_k, - backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4, - backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c2); - - static const bool use_coopk_bin = [] { - const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); - return !env || !*env || atoi(env) != 0; - }(); - - if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { - const std::string base_opts = backend_ctx->kernel_compile_opts - + " -DCOOPK_Q_BIN=1 -DCOOPK_ROWS=" + std::to_string(backend_ctx->rows_coopk_dp4a_q4_k); - for (int cols = 4; cols >= 2; cols -= 2) { - int & nsg = (cols == 4) ? backend_ctx->nsg_coopk_dp4a_q4_k_bin_c4 - : backend_ctx->nsg_coopk_dp4a_q4_k_bin_c2; - int nsg_eff = nsg; - cl_program program = ggml_cl_build_program_coopk( - backend_ctx, kernel_src.c_str(), "kernel_gemm_coopk_q4_k_q8_1_dp4a", - base_opts + " -DCOOPK_COLS=" + std::to_string(cols), nsg_eff); - if (program == nullptr) { - continue; - } - cl_int err; - cl_kernel kernel = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a", &err); - if (err != CL_SUCCESS) { kernel = nullptr; } - CL_CHECK(clReleaseProgram(program)); - if (cols == 4) { - backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 = kernel; - } else { - backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 = kernel; - } - nsg = nsg_eff; - } - load_cl_kernel_coopk_q4_k_bin_c8(backend_ctx); - } - GGML_LOG_CONT("."); + const char * xmem_env = getenv("GGML_OPENCL_ADRENO_XMEM_GEMM"); + backend_ctx->adreno_xmem_gemm_enabled = backend_ctx->gpu_family == GPU_FAMILY::ADRENO && + (xmem_env ? atoi(xmem_env) != 0 : true); } - - // Q6_K - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_coopk_q6_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a.cl"); #endif - ggml_cl_coopk_build_narrow(backend_ctx, kernel_src, "kernel_gemm_coopk_q6_k_q8_1_dp4a", - backend_ctx->rows_coopk_dp4a_q6_k, backend_ctx->nsg_coopk_dp4a_q6_k, - backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4, - backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c2); - - static const bool use_coopk_bin = [] { - const char * env = getenv("GGML_OPENCL_COOPK_Q6_K_BIN"); - return !env || !*env || atoi(env) != 0; - }(); - - if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { - load_cl_kernel_coopk_q6_k_bin_c8(backend_ctx); - } - GGML_LOG_CONT("."); - } -} -static void load_cl_kernels_coopmat(ggml_backend_opencl_context * backend_ctx) { - if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO || !strstr(backend_ctx->device_name.c_str(), "850")) { - return; - } + // determine whether to use large buffer for Adreno + backend_ctx->adreno_use_large_buffer = getenv("GGML_OPENCL_ADRENO_USE_LARGE_BUFFER") != nullptr && + backend_ctx->gpu_family == GPU_FAMILY::ADRENO; - cl_int err; - const std::string opts = "-cl-std=CL" + std::to_string(backend_ctx->opencl_c_version.major) + "." + - std::to_string(backend_ctx->opencl_c_version.minor) + - (backend_ctx->adreno_use_large_buffer ? " -qcom-enable-large-buffer" : ""); + backend_ctx->kernel_compile_opts = ggml_opencl_make_compile_opts(backend_ctx.get()); + CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, + sizeof(backend_ctx->fa.compute_units), &backend_ctx->fa.compute_units, NULL)); - // pack_b_f16_coopmat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "pack_b_f16_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("pack_b_f16_coopmat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); - if (!prog) { - return; - } - CL_CHECK((backend_ctx->kernel_pack_b_f16_coopmat = clCreateKernel(prog, "kernel_pack_b_f16_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + // ragged moe, unspecified or non-zero means enabled, set to 0 to disable + static const char * ragged_fp16_env = getenv("GGML_OPENCL_MOE_RAGGED_FP16"); + backend_ctx->adreno_use_moe_ragged = (ragged_fp16_env == NULL) ? 1 : (atoi(ragged_fp16_env) != 0); - // gemm_noshuffle_q4_0_f32_coopmat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q4_0_f32_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q4_0_f32_coopmat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_f32_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + // ragged moe, tile-skip granularity (columns per skip-group): 8 = quarter (default), + // 16 = half (legacy), 32 = disabled. Override with GGML_OPENCL_MOE_RAGGED_GRAN={8,16,32} + static const char * ragged_gran_env = getenv("GGML_OPENCL_MOE_RAGGED_GRAN"); + backend_ctx->adreno_moe_ragged_skip_gran = (ragged_gran_env != NULL) ? atoi(ragged_gran_env) : 8; - // gemm_noshuffle_q5_0_f32_coopmat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q5_0_f32_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q5_0_f32_coopmat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_f32_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + // whether fuse moe combine + static const char * fuse_moe_bias_glu_env = getenv("GGML_OPENCL_FUSE_MOE_BIAS_GLU"); + backend_ctx->fuse_moe_bias_glu = fuse_moe_bias_glu_env == NULL ? 1 : (atoi(fuse_moe_bias_glu_env) != 0); - // gemm_noshuffle_q8_0_f32_coopmat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q8_0_f32_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q8_0_f32_coopmat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + static const char * fuse_moe_bias_combine_env = getenv("GGML_OPENCL_FUSE_MOE_BIAS_COMBINE"); + backend_ctx->fuse_moe_bias_combine = fuse_moe_bias_combine_env == NULL ? 1 : (atoi(fuse_moe_bias_combine_env) != 0); - // gemm_noshuffle_q4_k_f32_coopmat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q4_k_f32_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q4_k_f32_coopmat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + static const char * fuse_moe_combine_env = getenv("GGML_OPENCL_FUSE_MOE_COMBINE"); + backend_ctx->fuse_moe_combine = fuse_moe_combine_env == NULL ? 1 : (atoi(fuse_moe_combine_env) != 0); - // gemm_noshuffle_q5_k_f32_coopmat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q5_k_f32_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q5_k_f32_coopmat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_f32_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + // ragged moe dp4 variant + static const char * ragged_dp4_env = getenv("GGML_OPENCL_MOE_RAGGED"); + backend_ctx->adreno_use_moe_ragged_dp4 = ragged_dp4_env == NULL ? 1 : (atoi(ragged_dp4_env) != 0); - // gemm_noshuffle_q6_k_f32_coopmat +#ifdef GGML_OPENCL_USE_ADRENO_BIN_KERNELS + // try loading adreno binary kernels if enabled + // if fails to load, builtin kernels will be used { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q6_k_f32_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32_coopmat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_f32_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + dl_handle * kernel_lib_handle = dl_load_library(KERNEL_LIB_NAME); + backend_ctx->adreno_use_bin_kernels = false; - // gemm_moe_mxfp4_f32_ns_coopmat - // built only on A850 (see the check above), a failed build is not fatal. - backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_mxfp4_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_mxfp4_f32_ns_coopmat.cl"); -#endif - // the router buffers are sub-buffers; read through texture promotion they give wrong values - std::string coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - // gemm_moe_q4_0_f32_ns_coopmat, same options as the mxfp4 one - backend_ctx->kernel_gemm_moe_q4_0_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_0_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_0_f32_ns_coopmat.cl"); -#endif - std::string q4_0_coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q4_0_coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q4_0_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (kernel_lib_handle) { + backend_ctx->get_adreno_bin_kernel_func = (get_adreno_bin_kernel_func_t)dl_get_sym(kernel_lib_handle, "get_adreno_kernels"); + if (backend_ctx->get_adreno_bin_kernel_func) { + GGML_LOG_INFO("ggml_opencl: loaded bin kernel library %s\n", KERNEL_LIB_NAME); + backend_ctx->adreno_use_bin_kernels = true; + } else { + GGML_LOG_INFO("ggml_opencl: bin kernel library %s is invalid, will use builtin kernels\n", KERNEL_LIB_NAME); + } + } else { + GGML_LOG_INFO("ggml_opencl: failed to load %s, will use builtin kernels\n", KERNEL_LIB_NAME); } } +#endif // GGML_OPENCL_USE_ADRENO_BIN_KERNELS - // gemm_moe_q4_1_f32_ns_coopmat, same options as the mxfp4 one - backend_ctx->kernel_gemm_moe_q4_1_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_1_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_1_f32_ns_coopmat.cl"); -#endif - std::string q4_1_coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q4_1_coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_1_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q4_1_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + cl_int err; - // gemm_moe_q5_0_f32_ns_coopmat, same options as the mxfp4 one - backend_ctx->kernel_gemm_moe_q5_0_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q5_0_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q5_0_f32_ns_coopmat.cl"); -#endif - std::string q5_0_coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q5_0_coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_0_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q5_0_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } + // A local ref of cl_context for convenience + cl_context context = backend_ctx->context = dev_ctx->context; - // gemm_moe_q5_1_f32_ns_coopmat, same options as the mxfp4 one - backend_ctx->kernel_gemm_moe_q5_1_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q5_1_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q5_1_f32_ns_coopmat.cl"); -#endif - std::string q5_1_coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q5_1_coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_1_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q5_1_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - - // gemm_moe_q4_k_f32_ns_coopmat, same options as the mxfp4 one - backend_ctx->kernel_gemm_moe_q4_k_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_k_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_k_f32_ns_coopmat.cl"); -#endif - std::string q4_k_coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q4_k_coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q4_k_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - - // gemm_moe_q5_k_f32_ns_coopmat, same options as the mxfp4 one - backend_ctx->kernel_gemm_moe_q5_k_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q5_k_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q5_k_f32_ns_coopmat.cl"); -#endif - std::string q5_k_coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q5_k_coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_k_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q5_k_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - - // gemm_moe_q6_k_f32_ns_coopmat, same options as the mxfp4 one - backend_ctx->kernel_gemm_moe_q6_k_f32_ns_coopmat = nullptr; - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q6_k_f32_ns_coopmat.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q6_k_f32_ns_coopmat.cl"); + //CL_CHECK((queue = clCreateCommandQueue(context, device, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err), + // (err != CL_INVALID_QUEUE_PROPERTIES && err != CL_INVALID_VALUE ? err : + // (queue = clCreateCommandQueue(context, device, 0, &err), err) + //))); + cl_command_queue_properties command_queue_props = 0; +#ifdef GGML_OPENCL_PROFILING + command_queue_props |= CL_QUEUE_PROFILING_ENABLE; #endif - std::string q6_k_coopmat_opts = - " -cl-std=CL3.0 " - " -qcom-ray-tracing-kernel " - " -qcom-disable-promote-pointer-to-texture "; - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q6_k_coopmat_opts, false); - if (prog) { - CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q6_k_f32_ns_coopmat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } -} + CL_CHECK((backend_ctx->queue = clCreateCommandQueue(context, device, command_queue_props, &err), err)); -#endif + // delay kernel loading until the first buffer is created + // load_cl_kernels(backend_ctx.get()); -static std::string ggml_opencl_make_compile_opts(const ggml_backend_opencl_context * backend_ctx) { - auto opencl_c_std = - std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + std::to_string(backend_ctx->opencl_c_version.minor); - std::string compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable -cl-unsafe-math-optimizations" - " -cl-finite-math-only -cl-fast-relaxed-math"; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Allocate intermediate buffers and images + size_t required_A_q_d_bytes = 311164928; + size_t required_A_s_d_bytes = 38895616; + size_t required_B_d_bytes = 45088768; - if (backend_ctx->adreno_use_large_buffer) { - compile_opts += " -qcom-enable-large-buffer "; + // Ensure buffer sizes do not exceed the maximum allocation size + size_t max_A_q_d_bytes = MIN(required_A_q_d_bytes, backend_ctx->max_alloc_size); + size_t max_A_s_d_bytes = MIN(required_A_s_d_bytes, backend_ctx->max_alloc_size); + size_t max_B_d_bytes = MIN(required_B_d_bytes, backend_ctx->max_alloc_size); + if (required_A_q_d_bytes > backend_ctx->max_alloc_size) { + GGML_LOG_WARN("ggml_opencl: A_q_d buffer size reduced from %zu to %zu due to device limitations.\n", + required_A_q_d_bytes, max_A_q_d_bytes); } - - return compile_opts; -} - -static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) { - if (backend_ctx->kernels_loaded) { - return; + if (required_A_s_d_bytes > backend_ctx->max_alloc_size) { + GGML_LOG_WARN("ggml_opencl: A_s_d buffer size reduced from %zu to %zu due to device limitations.\n", + required_A_s_d_bytes, max_A_s_d_bytes); } - - cl_int err; - const std::string & compile_opts = backend_ctx->kernel_compile_opts; - const std::string opencl_c_std = "CL" + std::to_string(backend_ctx->opencl_c_version.major) + - "." + std::to_string(backend_ctx->opencl_c_version.minor); - - GGML_LOG_INFO("ggml_opencl: loading OpenCL kernels"); - - // add - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "add.cl.h" - }; -#else - const std::string kernel_src = read_file("add.cl"); -#endif - backend_ctx->program_add = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_add = clCreateKernel(backend_ctx->program_add, "kernel_add", &err), err)); - CL_CHECK((backend_ctx->kernel_add_row = clCreateKernel(backend_ctx->program_add, "kernel_add_row", &err), err)); - CL_CHECK((backend_ctx->kernel_add_f16 = clCreateKernel(backend_ctx->program_add, "kernel_add_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_add_row_f16 = clCreateKernel(backend_ctx->program_add, "kernel_add_row_f16", &err), err)); - GGML_LOG_CONT("."); + if (required_B_d_bytes > backend_ctx->max_alloc_size) { + GGML_LOG_WARN("ggml_opencl: B_d buffer size reduced from %zu to %zu due to device limitations.\n", + required_B_d_bytes, max_B_d_bytes); } - // add_id - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "add_id.cl.h" - }; -#else - const std::string kernel_src = read_file("add_id.cl"); -#endif - backend_ctx->program_add_id = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + backend_ctx->prealloc_quant_trans.allocate(context, max_A_q_d_bytes); + backend_ctx->prealloc_scales_trans.allocate(context, max_A_s_d_bytes); + backend_ctx->prealloc_act_trans.allocate(context, max_B_d_bytes); +#endif // GGML_OPENCL_USE_ADRENO_KERNELS - CL_CHECK((backend_ctx->kernel_add_id = clCreateKernel(backend_ctx->program_add_id, "kernel_add_id", &err), err)); - GGML_LOG_CONT("."); + backend_ctx->disable_fusion = getenv("GGML_OPENCL_DISABLE_FUSION") != nullptr; + if (const char * env = getenv("GGML_OPENCL_FUSE_MM_GLU")) { + backend_ctx->fuse_mm_glu = atoi(env) != 0; } - - // mul_mat_id_utils - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mat_id_utils.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mat_id_utils.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_moe_zero_dst = clCreateKernel(prog, "kernel_moe_zero_dst", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (const char * env = getenv("GGML_OPENCL_FUSE_RMS_ADD")) { + backend_ctx->fuse_rms_add = atoi(env) != 0; } - - // moe_sort_by_expert - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "moe_sort_by_expert.cl.h" - }; -#else - const std::string kernel_src = read_file("moe_sort_by_expert.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_moe_histogram = clCreateKernel(prog, "kernel_moe_histogram", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_scan = clCreateKernel(prog, "kernel_moe_scan", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_fill = clCreateKernel(prog, "kernel_moe_fill", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_scatter = clCreateKernel(prog, "kernel_moe_scatter", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_scatter_stable = clCreateKernel(prog, "kernel_moe_scatter_stable", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (const char * env = getenv("GGML_OPENCL_F16_MROW")) { + backend_ctx->f16_mrow = atoi(env) != 0; } - - // moe_add_id_glu - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "moe_add_id_glu.cl.h" - }; -#else - const std::string kernel_src = read_file("moe_add_id_glu.cl"); -#endif - backend_ctx->program_moe_add_id_glu = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_add_id_add_id_swiglu_oai = - clCreateKernel(backend_ctx->program_moe_add_id_glu, "kernel_add_id_add_id_swiglu_oai", &err), err)); - GGML_LOG_CONT("."); + if (const char * env = getenv("GGML_OPENCL_F16_MROW_RPT")) { + const int v = atoi(env); + backend_ctx->f16_mrow_rpt = (v == 2 || v == 4 || v == 8 || v == 16) ? v : 1; } - // tri - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "tri.cl.h" - }; -#else - const std::string kernel_src = read_file("tri.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + dev_ctx->backend_ctx = backend_ctx.release(); + return dev_ctx->backend_ctx; +} - CL_CHECK((backend_ctx->kernel_tri = clCreateKernel(prog, "kernel_tri_f32", &err), err)); - GGML_LOG_CONT("."); +static void ggml_cl_free(ggml_backend_t backend) { + ggml_backend_opencl_context * ctx = (ggml_backend_opencl_context *) backend->context; + ctx->free(); +} - CL_CHECK(clReleaseProgram(prog)); - } +//------------------------------------------------------------------------------ +// Backend API +//------------------------------------------------------------------------------ - // fill - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "fill.cl.h" - }; -#else - const std::string kernel_src = read_file("fill.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); +// +// backend +// +static const char * ggml_backend_opencl_name(ggml_backend_t backend) { + return "OpenCL"; - CL_CHECK((backend_ctx->kernel_fill = clCreateKernel(prog, "kernel_fill_f32", &err), err)); - GGML_LOG_CONT("."); + UNUSED(backend); +} - CL_CHECK(clReleaseProgram(prog)); - } +static void ggml_backend_opencl_free(ggml_backend_t backend) { + ggml_cl_free(backend); +} - // arange - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "arange.cl.h" - }; -#else - const std::string kernel_src = read_file("arange.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); +static void ggml_backend_opencl_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { + GGML_UNUSED(backend); + GGML_UNUSED(tensor); + GGML_UNUSED(data); + GGML_UNUSED(offset); + GGML_UNUSED(size); +} - CL_CHECK((backend_ctx->kernel_arange = clCreateKernel(prog, "kernel_arange_f32", &err), err)); - GGML_LOG_CONT("."); +static void ggml_backend_opencl_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { + GGML_UNUSED(backend); + GGML_UNUSED(tensor); + GGML_UNUSED(data); + GGML_UNUSED(offset); + GGML_UNUSED(size); +} - CL_CHECK(clReleaseProgram(prog)); - } +static bool ggml_backend_opencl_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) { + GGML_UNUSED(backend); + GGML_UNUSED(src); + GGML_UNUSED(dst); + return false; +} - // clamp - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "clamp.cl.h" - }; -#else - const std::string kernel_src = read_file("clamp.cl"); -#endif - backend_ctx->program_clamp = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); +static void ggml_backend_opencl_synchronize(ggml_backend_t backend) { + auto * backend_ctx = static_cast(backend->context); - CL_CHECK((backend_ctx->kernel_clamp = clCreateKernel(backend_ctx->program_clamp, "kernel_clamp", &err), err)); - CL_CHECK((backend_ctx->kernel_clamp_nc = clCreateKernel(backend_ctx->program_clamp, "kernel_clamp_nc", &err), err)); - GGML_LOG_CONT("."); - } + cl_event evt; + CL_CHECK(clEnqueueBarrierWithWaitList(backend_ctx->queue, 0, nullptr, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); +} - // cpy - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "cpy.cl.h" - }; -#else - const std::string kernel_src = read_file("cpy.cl"); -#endif - const bool no_cpy_pack = backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X; +// Synchronizes the 'backend_ctx's device with others so that commands +// enqueued to it won't start until commands in the other devices have +// completed. +static bool ggml_cl_tensors_overlap(const ggml_tensor * x, const ggml_tensor * y) { + ggml_tensor_extra_cl * ex = (ggml_tensor_extra_cl *)x->extra; + ggml_tensor_extra_cl * ey = (ggml_tensor_extra_cl *)y->extra; + if (!ex || !ey || ex->data_device != ey->data_device) { return false; } + const cl_ulong xo = ex->offset + x->view_offs, xe = xo + ggml_nbytes(x); + const cl_ulong yo = ey->offset + y->view_offs, ye = yo + ggml_nbytes(y); + return xo < ye && yo < xe; +} - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), - no_cpy_pack ? compile_opts + " -DGGML_CL_NO_CPY_PACK" : compile_opts); +// Detect the MoE combine epilogue: router-weight MUL ([n_embd,k,nt] * [1,k,nt]) followed +// by k VIEWs of it and a (k-1)-long ADD reduction chain producing [n_embd, nt]. When it +// matches (and the output does not alias the inputs), the whole subgraph collapses to one +// weighted-sum-across-experts kernel. +static bool ggml_opencl_can_fuse_moe_combine(const struct ggml_cgraph * cgraph, int node_idx, + const ggml_tensor ** out_final_add) { + const ggml_tensor * mul = cgraph->nodes[node_idx]; + if (mul->op != GGML_OP_MUL) { return false; } + const ggml_tensor * experts = mul->src[0]; + const ggml_tensor * weights = mul->src[1]; + if (!experts || !weights) { return false; } + if (experts->type != GGML_TYPE_F32 || weights->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32) { return false; } - CL_CHECK((backend_ctx->kernel_cpy_f16_f16 = clCreateKernel(prog, "kernel_cpy_f16_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_cpy_f16_f32 = clCreateKernel(prog, "kernel_cpy_f16_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_cpy_f32_f16 = clCreateKernel(prog, "kernel_cpy_f32_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_cpy_f32_f32 = clCreateKernel(prog, "kernel_cpy_f32_f32", &err), err)); - if (!no_cpy_pack) { - CL_CHECK((backend_ctx->kernel_cpy_f32_f32_pack = clCreateKernel(prog, "kernel_cpy_f32_f32_pack", &err), err)); - } - { // optional: without it ggml_cl_cpy keeps the row-mapped kernel - cl_int err_flat = CL_SUCCESS; - cl_kernel k = clCreateKernel(prog, "kernel_cpy_f32_f32_flat", &err_flat); - if (err_flat == CL_SUCCESS) { - backend_ctx->kernel_cpy_f32_f32_flat = k; - } - } - CL_CHECK((backend_ctx->kernel_cpy_i32_i32 = clCreateKernel(prog, "kernel_cpy_i32_i32", &err), err)); - CL_CHECK((backend_ctx->kernel_cpy_i32_f32 = clCreateKernel(prog, "kernel_cpy_i32_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_cpy_f32_i32 = clCreateKernel(prog, "kernel_cpy_f32_i32", &err), err)); - GGML_LOG_CONT("."); - } + const int64_t n_embd = experts->ne[0]; + const int64_t k = experts->ne[1]; + const int64_t nt = experts->ne[2]; + if (k < 2 || k > 64 || experts->ne[3] != 1 || n_embd % 4 != 0) { return false; } + if (weights->ne[0] != 1 || weights->ne[1] != k || weights->ne[2] != nt || weights->ne[3] != 1) { return false; } + if (mul->ne[0] != n_embd || mul->ne[1] != k || mul->ne[2] != nt) { return false; } + // the fused kernel needs contiguous experts/weights and a contiguous 2D dst + if (!ggml_is_contiguous(experts) || !ggml_is_contiguous(weights)) { return false; } - // cvt - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "cvt.cl.h" - }; -#else - const std::string kernel_src = read_file("cvt.cl"); -#endif - backend_ctx->program_cvt = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_convert_block_q1_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q1_0", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q1_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q1_0", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_0_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_0_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_0_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_0_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_0", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_0", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_0_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_0_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_0_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_0_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_1_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_1_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_1_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_1_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_1 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_1", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_1 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_1", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_1_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_1_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_1_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_1_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_0", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_0", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_0_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_0_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_0_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_0_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_1_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_1_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_1_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_1_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_0_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_0_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_0_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_0_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_1 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_1", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_1 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_1", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_1_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_1_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_1_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_1_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_k_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_k_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_k_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_k_trans4_ns", &err), err)); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - CL_CHECK((backend_ctx->kernel_convert_block_q4_k_tiled_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_k_tiled_ns", &err), err)); -#endif - CL_CHECK((backend_ctx->kernel_convert_block_q5_k_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_k_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_k_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_k_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q6_k_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q6_k_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q6_k_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q6_k_trans4_ns", &err), err)); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - CL_CHECK((backend_ctx->kernel_convert_block_q6_k_tiled_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q6_k_tiled_ns", &err), err)); -#endif - CL_CHECK((backend_ctx->kernel_convert_block_mxfp4 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_mxfp4", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_mxfp4_trans = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_mxfp4_trans", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_mxfp4_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_mxfp4_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_mxfp4_trans4_ns = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_mxfp4_trans4_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_mxfp4_trans = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_mxfp4_trans", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_mxfp4 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_mxfp4", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q8_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q8_0", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q8_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q8_0", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q8_0_trans = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q8_0_trans", &err), err)); - CL_CHECK((backend_ctx->kernel_dequant_q8_0_f16_view_aos = clCreateKernel(backend_ctx->program_cvt, "kernel_dequant_q8_0_f16_view_aos", &err), err)); - CL_CHECK((backend_ctx->kernel_dequant_q8_0_f32_view_aos = clCreateKernel(backend_ctx->program_cvt, "kernel_dequant_q8_0_f32_view_aos", &err), err)); - CL_CHECK((backend_ctx->kernel_dequant_q4_0_f16_view_aos = clCreateKernel(backend_ctx->program_cvt, "kernel_dequant_q4_0_f16_view_aos", &err), err)); - CL_CHECK((backend_ctx->kernel_dequant_q4_0_f32_view_aos = clCreateKernel(backend_ctx->program_cvt, "kernel_dequant_q4_0_f32_view_aos", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_K = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_K", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_K = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_K", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q4_K_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q4_K_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q4_K_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q4_K_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_K = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_K", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_K = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_K", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q5_K_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q5_K_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q5_K_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q5_K_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q2_k_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q2_k_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q2_k_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q2_k_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q3_k_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q3_k_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q3_k_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q3_k_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq2_xxs = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq2_xxs", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq2_xxs = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq2_xxs", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq2_xs = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq2_xs", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq2_xs = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq2_xs", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq2_s = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq2_s", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq2_s = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq2_s", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q2_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q2_0", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q2_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q2_0", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq1_s = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq1_s", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq1_s = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq1_s", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq1_m = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq1_m", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq1_m = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq1_m", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq3_xxs = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq3_xxs", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq3_xxs = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq3_xxs", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq3_s = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq3_s", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq3_s = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq3_s", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq4_xs_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq4_xs_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq4_xs_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq4_xs_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq4_xs = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq4_xs", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq4_xs = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq4_xs", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q3_K = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q3_K", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q3_K = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q3_K", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q2_K = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q2_K", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q2_K = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q2_K", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q6_K = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q6_K", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q6_K = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q6_K", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_q6_K_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_q6_K_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_q6_K_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_q6_K_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq4_nl = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq4_nl", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq4_nl = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq4_nl", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_block_iq4_nl_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_block_iq4_nl_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_restore_block_iq4_nl_noshuffle = clCreateKernel(backend_ctx->program_cvt, "kernel_restore_block_iq4_nl_noshuffle", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_bf16_to_f16 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_bf16_to_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_convert_f16_to_bf16 = clCreateKernel(backend_ctx->program_cvt, "kernel_convert_f16_to_bf16", &err), err)); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - CL_CHECK((backend_ctx->kernel_moe_expand_scale_q8_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_moe_expand_scale_q8_0", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_expand_scale_q5_0 = clCreateKernel(backend_ctx->program_cvt, "kernel_moe_expand_scale_q5_0", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_expand_scale_q5_K = clCreateKernel(backend_ctx->program_cvt, "kernel_moe_expand_scale_q5_K", &err), err)); -#endif - GGML_LOG_CONT("."); - } + const int n_nodes = 1 + (int)k + (int)(k - 1); // MUL + k*VIEW + (k-1)*ADD + if (n_nodes >= 32) { return false; } + if (node_idx + n_nodes > cgraph->n_nodes) { return false; } - // diag - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "diag.cl.h" - }; -#else - const std::string kernel_src = read_file("diag.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + enum ggml_op ops[1 + 64 + 63]; + int n = 0; + ops[n++] = GGML_OP_MUL; + for (int j = 0; j < (int)k; ++j) { ops[n++] = GGML_OP_VIEW; } + for (int j = 0; j < (int)k - 1; ++j) { ops[n++] = GGML_OP_ADD; } + const int outs[] = { node_idx + n_nodes - 1 }; + if (!ggml_can_fuse_subgraph(cgraph, node_idx, n_nodes, ops, outs, 1)) { return false; } - CL_CHECK((backend_ctx->kernel_diag_f32 = clCreateKernel(prog, "kernel_diag_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + for (int j = 0; j < (int)k; ++j) { + const ggml_tensor * vw = cgraph->nodes[node_idx + 1 + j]; + if (vw->op != GGML_OP_VIEW || vw->src[0] != mul || vw->ne[0] != n_embd || vw->ne[1] != nt) { return false; } } + const ggml_tensor * final_add = cgraph->nodes[node_idx + n_nodes - 1]; + if (final_add->op != GGML_OP_ADD || final_add->type != GGML_TYPE_F32 || + final_add->ne[0] != n_embd || final_add->ne[1] != nt || final_add->ne[2] != 1) { return false; } + if (!ggml_is_contiguous(final_add)) { return false; } + // the fused kernel reads experts + writes final_add in one pass; bail if the + // pool allocator overlapped the output with the (large) experts input -- would race. + // The small weights input is copied to a private scratch in the dispatch, so its own + // aliasing with the output is handled there and does not block the fusion. + if (ggml_cl_tensors_overlap(experts, final_add)) { return false; } - // gelu - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gelu.cl.h" - }; -#else - const std::string kernel_src = read_file("gelu.cl"); -#endif - backend_ctx->program_gelu = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_gelu = clCreateKernel(backend_ctx->program_gelu, "kernel_gelu", &err), err)); - CL_CHECK((backend_ctx->kernel_gelu_4 = clCreateKernel(backend_ctx->program_gelu, "kernel_gelu_4", &err), err)); - CL_CHECK((backend_ctx->kernel_gelu_erf = clCreateKernel(backend_ctx->program_gelu, "kernel_gelu_erf", &err), err)); - CL_CHECK((backend_ctx->kernel_gelu_erf_4 = clCreateKernel(backend_ctx->program_gelu, "kernel_gelu_erf_4", &err), err)); - CL_CHECK((backend_ctx->kernel_gelu_quick = clCreateKernel(backend_ctx->program_gelu, "kernel_gelu_quick", &err), err)); - CL_CHECK((backend_ctx->kernel_gelu_quick_4 = clCreateKernel(backend_ctx->program_gelu, "kernel_gelu_quick_4", &err), err)); - GGML_LOG_CONT("."); - } + *out_final_add = final_add; + return true; +} - // glu - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "glu.cl.h" - }; -#else - const std::string kernel_src = read_file("glu.cl"); -#endif - backend_ctx->program_glu = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_geglu = clCreateKernel(backend_ctx->program_glu, "kernel_geglu", &err), err)); - CL_CHECK((backend_ctx->kernel_reglu = clCreateKernel(backend_ctx->program_glu, "kernel_reglu", &err), err)); - CL_CHECK((backend_ctx->kernel_swiglu = clCreateKernel(backend_ctx->program_glu, "kernel_swiglu", &err), err)); - CL_CHECK((backend_ctx->kernel_swiglu_oai = clCreateKernel(backend_ctx->program_glu, "kernel_swiglu_oai", &err), err)); - CL_CHECK((backend_ctx->kernel_swiglu_clamp = clCreateKernel(backend_ctx->program_glu, "kernel_swiglu_clamp", &err), err)); - CL_CHECK((backend_ctx->kernel_geglu_erf = clCreateKernel(backend_ctx->program_glu, "kernel_geglu_erf", &err), err)); - CL_CHECK((backend_ctx->kernel_geglu_quick = clCreateKernel(backend_ctx->program_glu, "kernel_geglu_quick", &err), err)); - CL_CHECK((backend_ctx->kernel_geglu_f16 = clCreateKernel(backend_ctx->program_glu, "kernel_geglu_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_reglu_f16 = clCreateKernel(backend_ctx->program_glu, "kernel_reglu_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_swiglu_f16 = clCreateKernel(backend_ctx->program_glu, "kernel_swiglu_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_swiglu_oai_f16 = clCreateKernel(backend_ctx->program_glu, "kernel_swiglu_oai_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_swiglu_clamp_f16 = clCreateKernel(backend_ctx->program_glu, "kernel_swiglu_clamp_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_geglu_erf_f16 = clCreateKernel(backend_ctx->program_glu, "kernel_geglu_erf_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_geglu_quick_f16 = clCreateKernel(backend_ctx->program_glu, "kernel_geglu_quick_f16", &err), err)); - GGML_LOG_CONT("."); +// Detect the gpt-oss MoE bias+activation epilogue on the PREFILL path: +// {MUL_MAT_ID(gate), ADD_ID(gate_bias), MUL_MAT_ID(up), ADD_ID(up_bias), GLU(swiglu_oai)}. +// The two matmuls still run as their own dispatches (the prefill GEMM is the vendor's); +// what collapses is the epilogue — both add_id passes are in-place read-modify-writes of a +// tensor the GLU immediately reads again, so they are three full passes over the same +// [n_ff, n_expert_used, n_tokens] f32 tensor where one suffices. +// +// The decode counterpart is handled by the mxfp4 fused GEMV arm in ggml_opencl_can_fuse, +// which folds the matmul too; this one deliberately fires only when that cannot (ne[2] > 1). +static bool ggml_opencl_can_fuse_moe_bias_glu(const struct ggml_cgraph * cgraph, int node_idx) { + if (node_idx + 4 >= cgraph->n_nodes) { + return false; } - // lightning_indexer - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "lightning_indexer.cl.h" - }; -#else - const std::string kernel_src = read_file("lightning_indexer.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_lightning_indexer = clCreateKernel(prog, "kernel_lightning_indexer", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + const enum ggml_op mg_ops[] = { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_GLU }; + const int mg_out[] = { node_idx + 4 }; + if (!ggml_can_fuse_subgraph(cgraph, node_idx, 5, mg_ops, mg_out, 1)) { + return false; } - // top_k - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "top_k.cl.h" - }; -#else - const std::string kernel_src = read_file("top_k.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_top_k_f32 = clCreateKernel(prog, "kernel_top_k_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_top_k_merge_f32 = clCreateKernel(prog, "kernel_top_k_merge_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // top_k_mask - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "top_k_mask.cl.h" - }; -#else - const std::string kernel_src = read_file("top_k_mask.cl"); -#endif - // Scores can contain NaN and -inf, so do not use the default fast-math options. - const std::string opts = "-cl-std=" + opencl_c_std + - (backend_ctx->adreno_use_large_buffer ? " -qcom-enable-large-buffer" : ""); - for (int i = 0; i < 2; ++i) { - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts + " -DMASK_F16=" + std::to_string(i == 0)); - CL_CHECK((backend_ctx->kernel_top_k_mask[i] = clCreateKernel(prog, "kernel_top_k_mask", &err), err)); - CL_CHECK((backend_ctx->kernel_top_k_mask_fill[i] = clCreateKernel(prog, "kernel_top_k_mask_fill", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - GGML_LOG_CONT("."); - } - - // get_rows - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "get_rows.cl.h" - }; -#else - const std::string kernel_src = read_file("get_rows.cl"); -#endif - backend_ctx->program_get_rows = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_get_rows_f32 = clCreateKernel(backend_ctx->program_get_rows, "kernel_get_rows_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_get_rows_i32 = clCreateKernel(backend_ctx->program_get_rows, "kernel_get_rows_i32", &err), err)); - CL_CHECK((backend_ctx->kernel_get_rows_f16 = clCreateKernel(backend_ctx->program_get_rows, "kernel_get_rows_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_get_rows_q4_0 = clCreateKernel(backend_ctx->program_get_rows, "kernel_get_rows_q4_0", &err), err)); - GGML_LOG_CONT("."); - } - - // solve_tri_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "solve_tri.cl.h" - }; -#else - const std::string kernel_src = read_file("solve_tri.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_solve_tri_f32 = clCreateKernel(prog, "kernel_solve_tri_f32", &err), err)); - GGML_LOG_CONT("."); - CL_CHECK(clReleaseProgram(prog)); - } - - // im2col_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "im2col_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("im2col_f32.cl"); -#endif - backend_ctx->program_im2col_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_im2col_f32 = clCreateKernel(backend_ctx->program_im2col_f32, "kernel_im2col_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // im2col_f16 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "im2col_f16.cl.h" - }; -#else - const std::string kernel_src = read_file("im2col_f16.cl"); -#endif - backend_ctx->program_im2col_f16 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_im2col_f16 = clCreateKernel(backend_ctx->program_im2col_f16, "kernel_im2col_f16", &err), err)); - GGML_LOG_CONT("."); - } - - // im2col_3d_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "im2col_3d_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("im2col_3d_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + const ggml_tensor * gmm = cgraph->nodes[node_idx]; + const ggml_tensor * gad = cgraph->nodes[node_idx+1]; + const ggml_tensor * umm = cgraph->nodes[node_idx+2]; + const ggml_tensor * uad = cgraph->nodes[node_idx+3]; + const ggml_tensor * glu = cgraph->nodes[node_idx+4]; - CL_CHECK((backend_ctx->kernel_im2col_3d_f32 = clCreateKernel(prog, "kernel_im2col_3d_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU_OAI) { + return false; } - - // im2col_3d_f16 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "im2col_3d_f16.cl.h" - }; -#else - const std::string kernel_src = read_file("im2col_3d_f16.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_im2col_3d_f16 = clCreateKernel(prog, "kernel_im2col_3d_f16", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // Prefill only — at one token the mxfp4 arm above folds the matmul as well. + if (gmm->src[1]->ne[2] == 1) { + return false; } - - // mul_mv_q4_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_0_f32.cl"); -#endif - backend_ctx->program_mul_mv_q4_0_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_q4_0_f32 = clCreateKernel(backend_ctx->program_mul_mv_q4_0_f32, "kernel_mul_mat_q4_0_f32", &err), err)); - GGML_LOG_CONT("."); + // Wiring: both matmuls share the activation and the expert selection, each add_id + // biases its own matmul, and the GLU consumes the two biased results as separate + // operands (so the same-buffer ne00_off/ne10_off split path is not in play). + if (gad->src[0] != gmm || uad->src[0] != umm || + glu->src[0] != gad || glu->src[1] != uad || + umm->src[1] != gmm->src[1] || umm->src[2] != gmm->src[2]) { + return false; } - - // mul_mv_q4_0_f32_v - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_0_f32_v.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_0_f32_v.cl"); -#endif - backend_ctx->program_mul_mv_q4_0_f32_v = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_q4_0_f32_v = clCreateKernel(backend_ctx->program_mul_mv_q4_0_f32_v, "kernel_mul_mat_q4_0_f32_v", &err), err)); - GGML_LOG_CONT("."); + // A swapped GLU would exchange the gate/up roles the fused kernel hard-codes. + if (ggml_get_op_params_i32(glu, 1)) { + return false; } - - // mul_mv_q4_0_f32_8x_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_0_f32_8x_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_0_f32_8x_flat.cl"); -#endif - backend_ctx->program_mul_mv_q4_0_f32_8x_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_q4_0_f32_8x_flat = clCreateKernel(backend_ctx->program_mul_mv_q4_0_f32_8x_flat, "kernel_mul_mat_q4_0_f32_8x_flat", &err), err)); - GGML_LOG_CONT("."); + if (gad->type != GGML_TYPE_F32 || uad->type != GGML_TYPE_F32 || glu->type != GGML_TYPE_F32) { + return false; } - - // mul_mv_q4_0_f32_1d_8x_flat - // This kernel does not compiler on Adreno cl compiler 38.01. Skip it for - // those compiler versions since it is anyway not used for Adreno. - if (backend_ctx->gpu_family != ADRENO || - backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 38, 11, 0) || - backend_ctx->adreno_cl_compiler_version.type == E17 || - backend_ctx->adreno_cl_compiler_version.type == DX) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_0_f32_1d_8x_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_0_f32_1d_8x_flat.cl"); -#endif - backend_ctx->program_mul_mv_q4_0_f32_1d_8x_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_q4_0_f32_1d_8x_flat = clCreateKernel(backend_ctx->program_mul_mv_q4_0_f32_1d_8x_flat, "kernel_mul_mat_q4_0_f32_1d_8x_flat", &err), err)); - GGML_LOG_CONT("."); + if (!gad->src[1] || gad->src[1]->type != GGML_TYPE_F32 || + !uad->src[1] || uad->src[1]->type != GGML_TYPE_F32) { + return false; } - - // mul_mv_q4_0_f32_1d_16x_flat - // This kernel does not compiler on Adreno cl compiler 38.01. Skip it for - // those compiler versions since it is anyway not used for Adreno. - if (backend_ctx->gpu_family != ADRENO || - backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 38, 11, 0) || - backend_ctx->adreno_cl_compiler_version.type == DX) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_0_f32_1d_16x_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_0_f32_1d_16x_flat.cl"); -#endif - backend_ctx->program_mul_mv_q4_0_f32_1d_16x_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_q4_0_f32_1d_16x_flat = clCreateKernel(backend_ctx->program_mul_mv_q4_0_f32_1d_16x_flat, "kernel_mul_mat_q4_0_f32_1d_16x_flat", &err), err)); - GGML_LOG_CONT("."); + if (!gad->src[2] || gad->src[2]->type != GGML_TYPE_I32 || uad->src[2] != gad->src[2]) { + return false; } - - // mul_mv_q4_1_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_1_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_1_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q4_1_f32 = clCreateKernel(prog, "kernel_mul_mv_q4_1_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // Full width on both operands: the kernel writes one output element per input pair. + if (!ggml_are_same_shape(gad, uad) || glu->ne[0] != gad->ne[0] || + glu->ne[1] != gad->ne[1] || glu->ne[2] != gad->ne[2] || glu->ne[3] != gad->ne[3]) { + return false; } - - // mul_mv_q4_1_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_1_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_1_f32_flat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q4_1_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q4_1_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (gad->ne[3] != 1) { + return false; } - - // mul_mv_q2_k_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q2_k_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q2_k_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_q2_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q2_K_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // The destination is addressed by (expert slot, token) rather than the GLU's flat row + // walk; those agree only for a contiguous destination. + if (!ggml_is_contiguous(glu) || !ggml_is_contiguous(gmm) || !ggml_is_contiguous(umm)) { + return false; } + return true; +} - // mul_mm_q2_k_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q2_k_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q2_k_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + ggml_cl_q2_k_mm_options(backend_ctx)); - CL_CHECK((backend_ctx->kernel_mul_mm_q2_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q2_k_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); +static bool ggml_opencl_can_fuse_moe_bias_combine(const struct ggml_cgraph * cgraph, int node_idx, + const ggml_tensor ** out_final_add) { + if (node_idx + 1 >= cgraph->n_nodes) { + return false; } - - // mul_mv_q2_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q2_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q2_k_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q2_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q2_K_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + const ggml_tensor * add = cgraph->nodes[node_idx]; + if (add->op != GGML_OP_ADD_ID) { + return false; } - - // mul_mv_q3_k_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q3_k_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q3_k_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_q3_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q3_K_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + const ggml_tensor * mul = cgraph->nodes[node_idx+1]; + if (mul->op != GGML_OP_MUL || mul->src[0] != add) { + return false; } - // mul_mm_q3_k_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q3_k_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q3_k_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + ggml_cl_q3_k_mm_options(backend_ctx)); - CL_CHECK((backend_ctx->kernel_mul_mm_q3_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q3_k_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + const ggml_tensor * final_add = NULL; + if (!ggml_opencl_can_fuse_moe_combine(cgraph, node_idx+1, &final_add)) { + return false; } -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string iq2_s_grid_src { - #include "iq2_s_grid.cl.h" - }; -#else - const std::string iq2_s_grid_src = read_file("iq2_s_grid.cl"); -#endif - - // mul_mv_iq2_s_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq2_s_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq2_s_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq2_s_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq2_s_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + const ggml_tensor * raw = add->src[0]; + const ggml_tensor * bias = add->src[1]; + const ggml_tensor * ids = add->src[2]; + if (!raw || !bias || !ids) { + return false; } - - // mul_mm_iq2_s_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq2_s_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq2_s_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq2_s_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq2_s_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (raw->type != GGML_TYPE_F32 || bias->type != GGML_TYPE_F32 || + ids->type != GGML_TYPE_I32 || add->type != GGML_TYPE_F32) { + return false; } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string iq2_xs_grid_src { - #include "iq2_xs_grid.cl.h" - }; -#else - const std::string iq2_xs_grid_src = read_file("iq2_xs_grid.cl"); -#endif - - // mul_mv_iq2_xs_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq2_xs_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq2_xs_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq2_xs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq2_xs_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // The combine reads the raw matmul output with the strides it computed from the + // add_id result, so the two must have the same layout. + if (!ggml_are_same_shape(raw, add) || !ggml_is_contiguous(raw)) { + return false; } - - // mul_mm_iq2_xs_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq2_xs_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq2_xs_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq2_xs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq2_xs_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (raw->nb[1] != add->nb[1] || raw->nb[2] != add->nb[2]) { + return false; } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string iq2_xxs_grid_src { - #include "iq2_xxs_grid.cl.h" - }; -#else - const std::string iq2_xxs_grid_src = read_file("iq2_xxs_grid.cl"); -#endif - - // mul_mv_iq2_xxs_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq2_xxs_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq2_xxs_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq2_xxs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq2_xxs_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // ids is indexed as [expert slot, token]; the combine walks the same two axes. + if (ids->ne[0] < add->ne[1] || ids->ne[1] < add->ne[2]) { + return false; } - // mul_mm_iq2_xxs_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq2_xxs_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq2_xxs_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq2_xxs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq2_xxs_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // Whole-run escape check: ADD_ID + MUL + k VIEWs + (k-1) ADDs, only the last node escapes. + const int k = (int)add->ne[1]; + const int n_nodes = 2 + k + (k - 1); + if (n_nodes >= 32 || node_idx + n_nodes > cgraph->n_nodes) { + return false; } - - // mul_mv_iq2_xxs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq2_xxs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq2_xxs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq2_xxs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq2_xxs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + enum ggml_op ops[32]; + int n = 0; + ops[n++] = GGML_OP_ADD_ID; + ops[n++] = GGML_OP_MUL; + for (int j = 0; j < k; ++j) ops[n++] = GGML_OP_VIEW; + for (int j = 0; j < k - 1; ++j) ops[n++] = GGML_OP_ADD; + const int outs[] = { node_idx + n_nodes - 1 }; + if (!ggml_can_fuse_subgraph(cgraph, node_idx, n_nodes, ops, outs, 1)) { + return false; } - // mul_mv_iq2_xs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq2_xs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq2_xs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq2_xs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq2_xs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + *out_final_add = final_add; + return true; +} - // mul_mv_iq2_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq2_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq2_s_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq2_s_f32 = clCreateKernel(prog, "kernel_mul_mv_iq2_s_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } +static bool ggml_opencl_can_fuse(const ggml_backend_opencl_context * backend_ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list ops) { - // fwht - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "fwht.cl.h" - }; -#else - const std::string kernel_src = read_file("fwht.cl"); -#endif - for (int i = 0; i < 2; ++i) { - const std::string opts = compile_opts + (i == 0 ? " -DSRC_TYPE=float" : " -DSRC_TYPE=half"); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - CL_CHECK((backend_ctx->kernel_fwht[i] = clCreateKernel(prog, "kernel_fwht", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - size_t nth = 128; - const size_t max_workgroup = backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fwht[i]); - while (nth > max_workgroup) { - nth /= 2; - } - backend_ctx->fwht_workgroup_size[i] = nth; + // glu(mul_mat(Wg,x), mul_mat(Wu,x)) - the FFN gate/up GEMVs + GLU. This is a + // non-linear subgraph (up does NOT consume gate), so the contiguous + // ggml_can_fuse below rejects it; use ggml_can_fuse_subgraph with the glu as + // the sole output and validate the edges explicitly. q4_K decode only; + // byte-identical to the per-op path. + if (ops.size() == 3 && ops.begin()[0] == GGML_OP_MUL_MAT && + ops.begin()[1] == GGML_OP_MUL_MAT && ops.begin()[2] == GGML_OP_GLU) { + const enum ggml_op glu_ops[] = { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU }; + const int glu_out[] = { node_idx + 2 }; + if (!ggml_can_fuse_subgraph(cgraph, node_idx, 3, glu_ops, glu_out, 1)) { + return false; } - GGML_LOG_CONT("."); - } - // mul_mv_q2_0_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q2_0_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q2_0_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_q2_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q2_0_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + const ggml_tensor *gate = cgraph->nodes[node_idx]; + const ggml_tensor *up = cgraph->nodes[node_idx+1]; + const ggml_tensor *glu = cgraph->nodes[node_idx+2]; - // mul_mm_q2_0_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q2_0_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q2_0_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_q2_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q2_0_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + if (ggml_get_src_scale(gate, 0) || ggml_get_src_scale(up, 0)) { + return false; + } - // mul_mv_q2_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q2_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q2_0_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_q2_0_f32 = clCreateKernel(prog, "kernel_mul_mv_q2_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string iq1_s_grid_src { - #include "iq1_s_grid.cl.h" - }; -#else - const std::string iq1_s_grid_src = read_file("iq1_s_grid.cl"); -#endif - - // mul_mv_iq1_s_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq1_s_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq1_s_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq1_s_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq1_s_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mm_iq1_s_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq1_s_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq1_s_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq1_s_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq1_s_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_iq1_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq1_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq1_s_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq1_s_f32 = clCreateKernel(prog, "kernel_mul_mv_iq1_s_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_iq1_m_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq1_m_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq1_m_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq1_m_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq1_m_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // decode GEMV path only (single token); prefill GEMM is separate + if (gate->ne[1] != 1 || up->ne[1] != 1) { + return false; + } + // both projections must be q4_K weights, f32 activation/output + if (gate->src[0]->type != GGML_TYPE_Q4_K || up->src[0]->type != GGML_TYPE_Q4_K || + gate->src[1]->type != GGML_TYPE_F32 || up->src[1]->type != GGML_TYPE_F32 || + gate->type != GGML_TYPE_F32 || up->type != GGML_TYPE_F32 || glu->type != GGML_TYPE_F32) { + return false; + } + // gate and up must share the same activation and have matching shape/stride + if (gate->src[1] != up->src[1] || + !ggml_are_same_shape(gate->src[0], up->src[0]) || + !ggml_are_same_stride(gate->src[0], up->src[0])) { + return false; + } + // GLU must read gate as src[0] and up as src[1], no swap (the fused + // epilogue applies the activation to gate, multiplies by up) + if (glu->src[0] != gate || glu->src[1] != up) { + return false; + } + if (ggml_get_op_params_i32(glu, 1) /* swapped */) { + return false; + } + // SWIGLU_OAI carries extra alpha/limit params -> not handled by the fused kernel + if (ggml_get_glu_op(glu) == GGML_GLU_OP_SWIGLU_OAI) { + return false; + } + // the fused kernel reads the standard noshuffle image layout; the tiled + // layout packs weights differently -> defer those to the per-op path + if (use_q4k_tiled(backend_ctx, gate->src[0]) || use_q4k_tiled(backend_ctx, up->src[0])) { + return false; + } + // q4_K bin kernel requires 32b transposed layout, not compatible with the fused gemv + if (use_q4_k_bin_kernels(backend_ctx, gate->src[0]) || use_q4_k_bin_kernels(backend_ctx, up->src[0])) { + return false; + } + // that noshuffle layout is only produced at set_tensor time when + // use_adreno_kernels() accepts the weight (ne0 >= 512 && ne1 >= 512). + // Smaller weights stay in the plain q4_K layout, which this kernel would + // misread -> defer them to the per-op path. Real FFN gate/up weights are + // far above the threshold, so production dispatch is unchanged. + if (!use_adreno_kernels(backend_ctx, gate->src[0]) || + !use_adreno_kernels(backend_ctx, up->src[0])) { + return false; + } + return true; } - // mul_mm_iq1_m_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq1_m_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq1_m_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq1_m_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq1_m_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (!ggml_can_fuse(cgraph, node_idx, ops)) { + return false; } - // mul_mv_iq1_m_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq1_m_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq1_m_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq1_m_f32 = clCreateKernel(prog, "kernel_mul_mv_iq1_m_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) { + const ggml_tensor *rms_norm = cgraph->nodes[node_idx]; + const ggml_tensor *mul = cgraph->nodes[node_idx+1]; -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string iq3_s_grid_src { - #include "iq3_s_grid.cl.h" - }; -#else - const std::string iq3_s_grid_src = read_file("iq3_s_grid.cl"); -#endif + GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32); + GGML_ASSERT(rms_norm->type == GGML_TYPE_F32); - // mul_mv_iq3_s_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq3_s_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq3_s_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq3_s_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq3_s_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + // rms_norm only supports f32 + if (mul->src[0]->type != GGML_TYPE_F32 || + mul->src[1]->type != GGML_TYPE_F32 || + mul->type != GGML_TYPE_F32) { + return false; + } - // mul_mm_iq3_s_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq3_s_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq3_s_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq3_s_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq3_s_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + // if rms_norm is the B operand, then we don't handle broadcast + if (rms_norm == mul->src[1] && + !ggml_are_same_shape(mul->src[0], rms_norm)) { + return false; + } - // mul_mv_iq3_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq3_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq3_s_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq3_s_f32 = clCreateKernel(prog, "kernel_mul_mv_iq3_s_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + // rms_norm assumes contiguous rows + if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) { + return false; + } + } else if (ops.size() == 3 && ops.begin()[0] == GGML_OP_NORM && ops.begin()[1] == GGML_OP_MUL && ops.begin()[2] == GGML_OP_ADD) { + const ggml_tensor *norm = cgraph->nodes[node_idx]; + const ggml_tensor *mul = cgraph->nodes[node_idx+1]; + const ggml_tensor *add = cgraph->nodes[node_idx+2]; + const ggml_tensor *w = mul->src[0] == norm ? mul->src[1] : mul->src[0]; + const ggml_tensor *b = add->src[0] == mul ? add->src[1] : add->src[0]; -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string iq3_xxs_grid_src { - #include "iq3_xxs_grid.cl.h" - }; -#else - const std::string iq3_xxs_grid_src = read_file("iq3_xxs_grid.cl"); -#endif + // norm fusion only supports F32 + if (norm->src[0]->type != GGML_TYPE_F32 || w->type != GGML_TYPE_F32 || b->type != GGML_TYPE_F32) { + return false; + } - // mul_mv_iq3_xxs_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq3_xxs_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq3_xxs_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq3_xxs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq3_xxs_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + if (norm->src[0]->ne[0] % 4 != 0) { + return false; + } - // mul_mm_iq3_xxs_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq3_xxs_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq3_xxs_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq3_xxs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq3_xxs_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + if (!ggml_is_contiguous(norm->src[0]) || !ggml_is_contiguous(w) || !ggml_is_contiguous(b)) { + return false; + } + } else if (ops.size() == 3 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL && ops.begin()[2] == GGML_OP_ADD) { + // rms_norm(x) * w + b, fused (residual). Mirrors the RMS_NORM+MUL gate + // plus the residual-add operand's constraints. + const ggml_tensor *rms_norm = cgraph->nodes[node_idx]; + const ggml_tensor *mul = cgraph->nodes[node_idx+1]; + const ggml_tensor *add = cgraph->nodes[node_idx+2]; + const ggml_tensor *w = mul->src[0] == rms_norm ? mul->src[1] : mul->src[0]; + const ggml_tensor *b = add->src[0] == mul ? add->src[1] : add->src[0]; - // mul_mv_iq3_xxs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq3_xxs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq3_xxs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq3_xxs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq3_xxs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32); + GGML_ASSERT(rms_norm->type == GGML_TYPE_F32); -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string iq4_xs_grid_src { - #include "iq4_xs_grid.cl.h" - }; -#else - const std::string iq4_xs_grid_src = read_file("iq4_xs_grid.cl"); -#endif + if (w->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32 || + b->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32) { + return false; + } + if (rms_norm->src[0]->ne[0] % 4 != 0) { + return false; + } + // if rms_norm is the B operand of mul, broadcast is not handled + if (rms_norm == mul->src[1] && !ggml_are_same_shape(mul->src[0], rms_norm)) { + return false; + } + // the residual must match the normed output shape (no add broadcast) + if (!ggml_are_same_shape(b, add)) { + return false; + } + // rms_norm assumes contiguous rows + if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1]) || + !ggml_is_contiguous_rows(b)) { + return false; + } + } else if (ops.size() == 3 && ops.begin()[0] == GGML_OP_GROUP_NORM && ops.begin()[1] == GGML_OP_MUL && ops.begin()[2] == GGML_OP_ADD) { + const ggml_tensor *gn = cgraph->nodes[node_idx]; + const ggml_tensor *mul = cgraph->nodes[node_idx+1]; + const ggml_tensor *add = cgraph->nodes[node_idx+2]; + const ggml_tensor *w = mul->src[0] == gn ? mul->src[1] : mul->src[0]; + const ggml_tensor *b = add->src[0] == mul ? add->src[1] : add->src[0]; - // mul_mv_iq4_xs_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq4_xs_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq4_xs_f32_flat.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq4_xs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq4_xs_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + if (gn->src[0]->type != GGML_TYPE_F32 || w->type != GGML_TYPE_F32 || b->type != GGML_TYPE_F32) { + return false; + } - // mul_mm_iq4_xs_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq4_xs_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq4_xs_f32_l4_lm.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_iq4_xs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq4_xs_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + if (!ggml_is_contiguous(gn->src[0]) || !ggml_is_contiguous(w) || !ggml_is_contiguous(b)) { + return false; + } } - // mul_mv_iq4_xs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq4_xs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq4_xs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_iq4_xs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq4_xs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + return true; +} - // mul_mv_q3_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q3_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q3_k_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); +static ggml_status ggml_backend_opencl_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) { + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - CL_CHECK((backend_ctx->kernel_mul_mv_q3_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q3_K_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + for (int i = 0; i < cgraph->n_nodes; i++) { + ggml_tensor * node = cgraph->nodes[i]; - // mul_mv_q4_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_k_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + // NOTE: this may oversynchronize by synchronizing with + // backends/devices which don't compute 'cgraph's + // dependencies. + sync_with_other_backends(backend); - CL_CHECK((backend_ctx->kernel_mul_mv_q4_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q4_K_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + if (ggml_is_empty(node) || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_NONE) { + continue; + } - // mul_mv_q4_k_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q4_k_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q4_k_f32_flat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { + continue; + } - CL_CHECK((backend_ctx->kernel_mul_mv_q4_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q4_K_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + if (!backend_ctx->disable_fusion && ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_NORM, GGML_OP_MUL, GGML_OP_ADD })) { + ggml_opencl_op_norm_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); + i += 2; + continue; + } + if (!backend_ctx->disable_fusion && ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_GROUP_NORM, GGML_OP_MUL, GGML_OP_ADD })) { + ggml_opencl_op_group_norm_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); + i += 2; + continue; + } + // Fuse the MoE combine: router-weight mul + cross-expert add chain -> + // one weighted-sum-across-experts kernel. + // Fold the gpt-oss MoE bias epilogue: add_id(gate_bias) + add_id(up_bias) + + // glu(swiglu_oai) -> one kernel, leaving the two matmuls as their own dispatches. + // Both add_ids are in-place passes over a tensor the GLU reads again, so this + // drops two full read+write passes per layer. Opt out GGML_OPENCL_FUSE_MOE_BIAS_GLU=0. + if (backend_ctx->fuse_moe_bias_glu && !backend_ctx->disable_fusion && + ggml_opencl_can_fuse_moe_bias_glu(cgraph, i)) { + ggml_cl_moe_bias_glu_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2], + cgraph->nodes[i+3], cgraph->nodes[i+4]); + i += 4; + continue; + } - // mul_mv_q5_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q5_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q5_0_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q5_0_f32 = clCreateKernel(prog, "kernel_mul_mv_q5_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_q5_0_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q5_0_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q5_0_f32_flat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q5_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q5_0_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_q5_1_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q5_1_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q5_1_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q5_1_f32 = clCreateKernel(prog, "kernel_mul_mv_q5_1_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_q5_1_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q5_1_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q5_1_f32_flat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q5_1_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q5_1_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_q5_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q5_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q5_k_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q5_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q5_K_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_q5_k_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q5_k_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q5_k_f32_flat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q5_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q5_K_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - - // mul_mv_q6_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q6_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q6_k_f32.cl"); -#endif - backend_ctx->program_mul_mv_q6_K = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q6_K_f32 = clCreateKernel(backend_ctx->program_mul_mv_q6_K, "kernel_mul_mv_q6_K_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_q6_k_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q6_k_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q6_k_f32_flat.cl"); -#endif - // The codegen workarounds in this kernel are a measured 13-20% loss on - // compilers that do not need them, so only the affected ones build them; - // everyone else gets the original source. - const std::string q6k_opts = backend_ctx->q6_k_flat_old_compiler - ? compile_opts + " -DADRENO_OLD_COMPILER=1" - : compile_opts; - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), q6k_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q6_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q6_K_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_q8_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q8_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q8_0_f32.cl"); -#endif - backend_ctx->program_mul_mv_q8_0_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q8_0_f32 = clCreateKernel(backend_ctx->program_mul_mv_q8_0_f32, "kernel_mul_mv_q8_0_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_q8_0_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q8_0_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q8_0_f32_flat.cl"); -#endif - backend_ctx->program_mul_mv_q8_0_f32_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q8_0_f32_flat = clCreateKernel(backend_ctx->program_mul_mv_q8_0_f32_flat, "kernel_mul_mv_q8_0_f32_flat", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_q1_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q1_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q1_0_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q1_0_f32 = clCreateKernel(prog, "kernel_mul_mv_q1_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_q1_0_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_q1_0_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_q1_0_f32_flat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_q1_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q1_0_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_iq4_nl_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq4_nl_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq4_nl_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_iq4_nl_f32 = clCreateKernel(prog, "kernel_mul_mv_iq4_nl_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_iq4_nl_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_iq4_nl_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_iq4_nl_f32_flat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_iq4_nl_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq4_nl_f32_flat", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_mxfp4_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_mxfp4_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_mxfp4_f32.cl"); -#endif - backend_ctx->program_mul_mv_mxfp4_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_mxfp4_f32 = clCreateKernel(backend_ctx->program_mul_mv_mxfp4_f32, "kernel_mul_mv_mxfp4_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_mxfp4_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_mxfp4_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_mxfp4_f32_flat.cl"); -#endif - backend_ctx->program_mul_mv_mxfp4_f32_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_mxfp4_f32_flat = clCreateKernel(backend_ctx->program_mul_mv_mxfp4_f32_flat, "kernel_mul_mv_mxfp4_f32_flat", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_f16_f16 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_f16_f16.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_f16_f16.cl"); -#endif - backend_ctx->program_mul_mv_f16_f16 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f16 = clCreateKernel(backend_ctx->program_mul_mv_f16_f16, "kernel_mul_mat_f16_f16", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_f16_f32_1row - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_f16_f32_1row.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_f16_f32_1row.cl"); -#endif - backend_ctx->program_mul_mv_f16_f32_1row = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_1row = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_1row, "kernel_mul_mat_f16_f32_1row", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_f16_f32_mrow (multi-row decode GEMV) - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_f16_f32_mrow.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_f16_f32_mrow.cl"); -#endif - backend_ctx->program_mul_mv_f16_f32_mrow = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_mrow = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_mrow, "kernel_mul_mat_f16_f32_mrow", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_mrow_r2 = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_mrow, "kernel_mul_mat_f16_f32_mrow_r2", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_mrow_r4 = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_mrow, "kernel_mul_mat_f16_f32_mrow_r4", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_mrow_h8 = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_mrow, "kernel_mul_mat_f16_f32_mrow_h8", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_mrow_h8r2 = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_mrow, "kernel_mul_mat_f16_f32_mrow_h8r2", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_f16_f32_l4 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_f16_f32_l4.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_f16_f32_l4.cl"); -#endif - backend_ctx->program_mul_mv_f16_f32_l4 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_l4 = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_l4_dr = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_dr", &err), err)); - if (backend_ctx->gpu_family == ADRENO) { - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_l4_dr_ls = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_dr_ls", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_l4_dr_lq = clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_dr_lq", &err), err)); + // Fold the MoE down-projection bias into the combine: add_id(down_bias) + the whole + // combine subgraph -> one kernel. Checked before the plain combine arm so the longer + // pattern wins. Opt out GGML_OPENCL_FUSE_MOE_BIAS_COMBINE=0. + if (backend_ctx->fuse_moe_bias_combine && backend_ctx->fuse_moe_combine && + !backend_ctx->disable_fusion) { + const ggml_tensor * bias_combine_out = nullptr; + if (ggml_opencl_can_fuse_moe_bias_combine(cgraph, i, &bias_combine_out)) { + ggml_cl_moe_bias_combine_fused(backend, node, cgraph->nodes[i+1], bias_combine_out); + i += 2 * (int)node->ne[1]; // ADD_ID + MUL + k VIEWs + (k-1) ADDs + continue; + } } - cl_int err_x8 = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_x8 = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_x8", &err_x8); - if (err_x8 != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_x8 = nullptr; } - - cl_int err_x8p = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_pair = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_x8_pair", &err_x8p); - if (err_x8p != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_x8_pair = nullptr; } - - cl_int err_x8g = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4 = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_x8_gqa4", &err_x8g); - if (err_x8g != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4 = nullptr; } - - cl_int err_x8gi = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4_img = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_x8_gqa4_img", &err_x8gi); - if (err_x8gi != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4_img = nullptr; } - - cl_int err_x8gi_r4 = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img", &err_x8gi_r4); - if (err_x8gi_r4 != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img = nullptr; } - - cl_int err_r2dk256 = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img", &err_r2dk256); - if (err_r2dk256 != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img = nullptr; } - - cl_int err_y8 = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_y8 = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_y8", &err_y8); - if (err_y8 != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_y8 = nullptr; } - - cl_int err_y8g = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_y8_gqa", &err_y8g); - if (err_y8g != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa = nullptr; } - - cl_int err_y8gi = CL_SUCCESS; - backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa_img = - clCreateKernel(backend_ctx->program_mul_mv_f16_f32_l4, "kernel_mul_mat_f16_f32_l4_y8_gqa_img", &err_y8gi); - if (err_y8gi != CL_SUCCESS) { backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa_img = nullptr; } - GGML_LOG_CONT("."); - } - - // mul_mv_f16_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_f16_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_f16_f32.cl"); -#endif - backend_ctx->program_mul_mv_f16_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32 = clCreateKernel(backend_ctx->program_mul_mv_f16_f32, "kernel_mul_mat_f16_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_f32_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_f32_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_f32_f32.cl"); -#endif - backend_ctx->program_mul_mv_f32_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_f32_f32 = clCreateKernel(backend_ctx->program_mul_mv_f32_f32, "kernel_mul_mat_f32_f32", &err), err)); - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X) { - cl_kernel kernel = clCreateKernel(backend_ctx->program_mul_mv_f32_f32, "kernel_mul_mv_f32_f32_r2", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (max_workgroup >= 64) { - backend_ctx->kernel_mul_mv_f32_f32_r2 = kernel; - } else { - CL_CHECK(clReleaseKernel(kernel)); + if (backend_ctx->fuse_moe_combine && !backend_ctx->disable_fusion) { + const ggml_tensor * combine_out = nullptr; + if (ggml_opencl_can_fuse_moe_combine(cgraph, i, &combine_out)) { + ggml_cl_moe_combine_fused(backend, node, combine_out); + i += 2 * (int)node->ne[1] - 1; // skip the k VIEWs + (k-1) ADDs + continue; } } - GGML_LOG_CONT("."); - } - - // mul_mat_f16_f32_tiled - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mat_f16_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mat_f16_f32.cl"); -#endif - backend_ctx->program_mul_mat_f16_f32_tiled = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mat_f16_f32_tiled = clCreateKernel(backend_ctx->program_mul_mat_f16_f32_tiled, "mul_mat_f16_f32", &err), err)); - GGML_LOG_CONT("."); - } - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // gemm_xmem_f16_f32_os8 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_xmem_f16_f32_os8.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_xmem_f16_f32_os8.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_adreno_xmem_pack_src_f32 = - clCreateKernel(prog, "adreno_xmem_pack_src_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_adreno_xmem_prepack_weight_f16 = - clCreateKernel(prog, "adreno_xmem_prepack_weight_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_xmem_f16_f32_os8 = - clCreateKernel(prog, "kernel_gemm_xmem_f16_f32_os8", &err), err)); - CL_CHECK((backend_ctx->kernel_adreno_xmem_store_dst_f32 = - clCreateKernel(prog, "adreno_xmem_store_dst_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS + // Fuse rms_norm + mul(weight) + add(residual). Checked before the + // rms_norm+mul fuse so the 3-op pattern wins over its 2-op prefix. + // Default on, opt-out GGML_OPENCL_FUSE_RMS_ADD=0. + if (!backend_ctx->disable_fusion && backend_ctx->fuse_rms_add && + ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD })) { + ggml_opencl_op_rms_norm_mul_add_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); + i += 2; + continue; + } + if (!backend_ctx->disable_fusion && ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) { + ggml_opencl_op_rms_norm_fused(backend, node, cgraph->nodes[i+1]); + i++; + continue; + } + // Fuse mul_mat(Wg,x) + mul_mat(Wu,x) + glu - fold the FFN's two decode + // GEMVs and the GLU into one dispatch. q4_K only (guarded below); the + // fused kernel uses the same accumulation/reduction order and the same + // scalar GLU formula -> coherent. Default on, opt-out GGML_OPENCL_FUSE_MM_GLU=0. #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno xmem SDPA - if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "sdpa_xmem_f32_f16_os8.cl.h" - }; -#else - const std::string kernel_src = read_file("sdpa_xmem_f32_f16_os8.cl"); -#endif - cl_program program = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - auto & xmem_attn = backend_ctx->adreno_xmem_attn; - CL_CHECK((xmem_attn.kernel_q_f32_to_img_scaled = - clCreateKernel(program, "adreno_xmem_attn_q_f32_to_img_scaled", &err), err)); - CL_CHECK((xmem_attn.kernel_kv_f32_to_img_gqa = - clCreateKernel(program, "adreno_xmem_attn_kv_f32_to_img_gqa", &err), err)); - CL_CHECK((xmem_attn.kernel_kv_f16_to_img_gqa = - clCreateKernel(program, "adreno_xmem_attn_kv_f16_to_img_gqa", &err), err)); - CL_CHECK((xmem_attn.kernel_img_to_f32 = - clCreateKernel(program, "adreno_xmem_attn_img_to_f32", &err), err)); - CL_CHECK((xmem_attn.kernel_k_gather = - clCreateKernel(program, "adreno_xmem_attn_k_gather", &err), err)); - CL_CHECK((xmem_attn.kernel_pack_k = - clCreateKernel(program, "adreno_xmem_attn_pack_k", &err), err)); - CL_CHECK((xmem_attn.kernel_qk_gemm = - clCreateKernel(program, "adreno_xmem_attn_qk_gemm", &err), err)); - CL_CHECK((xmem_attn.kernel_softmax_reduce_basic = - clCreateKernel(program, "adreno_xmem_attn_softmax_reduce_basic", &err), err)); - CL_CHECK((xmem_attn.kernel_softmax_apply_basic = - clCreateKernel(program, "adreno_xmem_attn_softmax_apply_basic", &err), err)); - CL_CHECK((xmem_attn.kernel_mask_scores = - clCreateKernel(program, "adreno_xmem_attn_mask_scores", &err), err)); - CL_CHECK((xmem_attn.kernel_pack_v = - clCreateKernel(program, "adreno_xmem_attn_pack_v", &err), err)); - CL_CHECK((xmem_attn.kernel_pv_gemm = - clCreateKernel(program, "adreno_xmem_attn_pv_gemm", &err), err)); - CL_CHECK(clReleaseProgram(program)); - xmem_attn.compiled = true; - GGML_LOG_CONT("."); - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - // mul_mm_f32_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_f32_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_f32_f32_l4_lm.cl"); -#endif - backend_ctx->program_mul_mm_f32_f32_l4_lm = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_f32_f32_l4_lm = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_mul_mm_f32_f32_l4_lm", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_f32_f32_mc = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mc", &err), err)); - - cl_kernel mcr = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mcr", &err); - if (err == CL_SUCCESS) { - if (backend_ctx->get_kernel_workgroup_size(mcr) >= 64) { - backend_ctx->kernel_gemv_f32_f32_mcr = mcr; - } else { - CL_CHECK(clReleaseKernel(mcr)); - } + // The fused executor (ggml_cl_mul_mat_q4_k_glu_fused) is image-path / + // Adreno-only (GGML_ABORT on the non-Adreno #else); gate the dispatch to + // match so the FFN GLU subgraph stays dormant on Intel/other drivers. + if (backend_ctx->fuse_mm_glu && !backend_ctx->disable_fusion && + ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU })) { + ggml_cl_mul_mat_q4_K_glu_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); + i += 2; + continue; } - - GGML_LOG_CONT("."); - } - - // mul_mm_f16_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_f16_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_f16_f32_l4_lm.cl"); -#endif - backend_ctx->program_mul_mm_f16_f32_l4_lm = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_f16_f32_l4_lm = clCreateKernel(backend_ctx->program_mul_mm_f16_f32_l4_lm, "kernel_mul_mm_f16_f32_l4_lm", &err), err)); - - const std::string narrow_opts = compile_opts + " -DBN=8 -DTN=1 -DKERNEL_NAME_LM=kernel_mul_mm_f16_f32_l4_lm_n8"; - backend_ctx->program_mul_mm_f16_f32_l4_lm_n8 = - build_program_from_source(backend_ctx, kernel_src.c_str(), narrow_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_f16_f32_l4_lm_n8 = clCreateKernel(backend_ctx->program_mul_mm_f16_f32_l4_lm_n8, "kernel_mul_mm_f16_f32_l4_lm_n8", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mm_q4_0_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q4_0_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q4_0_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q4_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q4_0_f32_l4_lm", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mm_q4_1_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q4_1_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q4_1_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q4_1_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q4_1_f32_l4_lm", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mm_q5_0_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q5_0_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q5_0_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q5_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q5_0_f32_l4_lm", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mm_q5_1_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q5_1_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q5_1_f32_l4_lm.cl"); #endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_q5_1_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q5_1_f32_l4_lm", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mm_q8_0_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q8_0_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q8_0_f32_l4_lm.cl"); -#endif - backend_ctx->program_mul_mm_q8_0_f32_l4_lm = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q8_0_f32_l4_lm = clCreateKernel(backend_ctx->program_mul_mm_q8_0_f32_l4_lm, "kernel_mul_mm_q8_0_f32_l4_lm", &err), err)); - GGML_LOG_CONT("."); + bool ok = ggml_cl_compute_forward(backend, node); + if (!ok) { + GGML_LOG_ERROR("%s: error: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op)); + } + GGML_ASSERT(ok); } - // mul_mm_q1_0_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q1_0_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q1_0_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q1_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q1_0_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } + return GGML_STATUS_SUCCESS; +} - // mul_mm_iq4_nl_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_iq4_nl_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_iq4_nl_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); +// The optimized gemm and gemv kernels are used for large matrices without batch. +// tensor is the quantized weights matrix. +static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *)dev->context; + ggml_backend_opencl_context * backend_ctx = dev_ctx->backend_ctx; - CL_CHECK((backend_ctx->kernel_mul_mm_iq4_nl_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq4_nl_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); + // reject ops that match the opfilter regex + if (dev_ctx->opfilter && std::regex_match(std::string(ggml_op_desc(op)), *dev_ctx->opfilter)) { + return false; } - // mul_mm_q4_k_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q4_k_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q4_k_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q4_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q4_k_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mm_q6_k_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q6_k_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q6_k_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q6_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q6_k_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mm_q5_k_f32_l4_lm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q5_k_f32_l4_lm.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q5_k_f32_l4_lm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_q5_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q5_k_f32_l4_lm", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mm_f16_f32_kq_kqv - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_f16_f32_kq_kqv.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_f16_f32_kq_kqv.cl"); -#endif - backend_ctx->program_mul_mm_f16_f32_kqv = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts+" -DKQV "); - backend_ctx->program_mul_mm_f16_f32_kq = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mm_f16_f32_kqv = clCreateKernel(backend_ctx->program_mul_mm_f16_f32_kqv, "mul_mm_f16_f32_kqv", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mm_f16_f32_kq = clCreateKernel(backend_ctx->program_mul_mm_f16_f32_kq, "mul_mm_f16_f32_kq", &err), err)); - GGML_LOG_CONT("."); - } - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string rows_src { - #include "flash_attn_q8_rows.cl.h" - }; - const std::string kq_src { - #include "mul_mm_q8_kq_p8.cl.h" - }; -#else - const std::string rows_src = read_file("flash_attn_q8_rows.cl"); - const std::string kq_src = read_file("mul_mm_q8_kq_p8.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, rows_src.c_str(), compile_opts, /*fatal=*/false); - if (prog != nullptr) { - CL_CHECK((backend_ctx->kernel_fa_q8_rows_f16 = clCreateKernel(prog, "kernel_fa_q8_rows_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_fa_q8_rows_f32 = clCreateKernel(prog, "kernel_fa_q8_rows_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - prog = build_program_from_source(backend_ctx, kq_src.c_str(), compile_opts, /*fatal=*/false); - if (prog != nullptr) { - CL_CHECK((backend_ctx->kernel_mul_mm_q8_kq_p8 = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - GGML_LOG_CONT("."); - } - - // mul_mm_q8_kq_p8_dk512 - if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q8_kq_p8_dk512.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q8_kq_p8_dk512.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts, /*fatal=*/false); - if (prog != nullptr) { - cl_kernel kernel = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8_dk512", &err); - CL_CHECK(clReleaseProgram(prog)); - if (err == CL_SUCCESS) { - backend_ctx->kernel_mul_mm_q8_kq_p8_dk512 = kernel; - } - } - GGML_LOG_CONT("."); - } - - // mul_mm_f16_f32_kq_p8 - if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_f16_f32_kq_p8.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_f16_f32_kq_p8.cl"); -#endif - cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), - compile_opts, /*fatal=*/false); - if (prog != nullptr) { - CL_CHECK((backend_ctx->kernel_mul_mm_f16_f32_kq_p8 = clCreateKernel(prog, "mul_mm_f16_f32_kq_p8", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - GGML_LOG_CONT("."); - } -#endif - - // mul - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul.cl.h" - }; -#else - const std::string kernel_src = read_file("mul.cl"); -#endif - backend_ctx->program_mul = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul = clCreateKernel(backend_ctx->program_mul, "kernel_mul", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_row = clCreateKernel(backend_ctx->program_mul, "kernel_mul_row", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_f16 = clCreateKernel(backend_ctx->program_mul, "kernel_mul_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_row_f16 = clCreateKernel(backend_ctx->program_mul, "kernel_mul_row_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_mul_mat_scale = clCreateKernel(backend_ctx->program_mul, "kernel_mul_mat_scale", &err), err)); - GGML_LOG_CONT("."); - } - - // norm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "norm.cl.h" - }; -#else - const std::string kernel_src = read_file("norm.cl"); -#endif - backend_ctx->program_norm = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_norm = clCreateKernel(backend_ctx->program_norm, "kernel_norm", &err), err)); - CL_CHECK((backend_ctx->kernel_norm_mul_add = clCreateKernel(backend_ctx->program_norm, "kernel_norm_mul_add", &err), err)); - GGML_LOG_CONT("."); - } - - // relu - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "relu.cl.h" - }; -#else - const std::string kernel_src = read_file("relu.cl"); -#endif - backend_ctx->program_relu = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_relu = clCreateKernel(backend_ctx->program_relu, "kernel_relu", &err), err)); - GGML_LOG_CONT("."); - } - - // rms_norm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "rms_norm.cl.h" - }; -#else - const std::string kernel_src = read_file("rms_norm.cl"); -#endif - backend_ctx->program_rms_norm = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_rms_norm = clCreateKernel(backend_ctx->program_rms_norm, "kernel_rms_norm", &err), err)); - CL_CHECK((backend_ctx->kernel_rms_norm_mul = clCreateKernel(backend_ctx->program_rms_norm, "kernel_rms_norm_mul", &err), err)); - CL_CHECK((backend_ctx->kernel_rms_norm_mul_add = clCreateKernel(backend_ctx->program_rms_norm, "kernel_rms_norm_mul_add", &err), err)); - GGML_LOG_CONT("."); - } - - // l2_norm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "l2_norm.cl.h" - }; -#else - const std::string kernel_src = read_file("l2_norm.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_l2_norm_f32 = clCreateKernel(prog, "kernel_l2_norm_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // rope - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "rope.cl.h" - }; -#else - const std::string kernel_src = read_file("rope.cl"); -#endif - backend_ctx->program_rope = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_rope_norm_f32 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_norm_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_rope_norm_f16 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_norm_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_rope_neox_f32 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_neox_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_rope_neox_f16 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_neox_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_rope_multi_f32 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_multi_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_rope_multi_f16 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_multi_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_rope_vision_f32 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_vision_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_rope_vision_f16 = clCreateKernel(backend_ctx->program_rope, "kernel_rope_vision_f16", &err), err)); - GGML_LOG_CONT("."); - } - - // scale - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "scale.cl.h" - }; -#else - const std::string kernel_src = read_file("scale.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_scale_f32_nc = clCreateKernel(prog, "kernel_scale_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_scale_f16 = clCreateKernel(prog, "kernel_scale_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_scale_f16_4 = clCreateKernel(prog, "kernel_scale_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_scale_f16_nc = clCreateKernel(prog, "kernel_scale_f16_nc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // silu - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "silu.cl.h" - }; -#else - const std::string kernel_src = read_file("silu.cl"); -#endif - backend_ctx->program_silu = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_silu = clCreateKernel(backend_ctx->program_silu, "kernel_silu", &err), err)); - CL_CHECK((backend_ctx->kernel_silu_4 = clCreateKernel(backend_ctx->program_silu, "kernel_silu_4", &err), err)); - CL_CHECK((backend_ctx->kernel_silu_nc = clCreateKernel(backend_ctx->program_silu, "kernel_silu_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_silu_f16 = clCreateKernel(backend_ctx->program_silu, "kernel_silu_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_silu_f16_4 = clCreateKernel(backend_ctx->program_silu, "kernel_silu_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_silu_f16_nc = clCreateKernel(backend_ctx->program_silu, "kernel_silu_f16_nc", &err), err)); - GGML_LOG_CONT("."); - } - - // softmax_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "softmax_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("softmax_f32.cl"); -#endif - backend_ctx->program_softmax_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_soft_max = clCreateKernel(backend_ctx->program_softmax_f32, "kernel_soft_max", &err), err)); - GGML_LOG_CONT("."); - } - - // softmax_f16 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "softmax_f16.cl.h" - }; -#else - const std::string kernel_src = read_file("softmax_f16.cl"); -#endif - backend_ctx->program_softmax_f16 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_soft_max_f16 = clCreateKernel(backend_ctx->program_softmax_f16, "kernel_soft_max_f16", &err), err)); - GGML_LOG_CONT("."); - } - - // softmax_4_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "softmax_4_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("softmax_4_f32.cl"); -#endif - backend_ctx->program_softmax_4_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_soft_max_4 = clCreateKernel(backend_ctx->program_softmax_4_f32, "kernel_soft_max_4", &err), err)); - GGML_LOG_CONT("."); - } - - // softmax_4_f16 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "softmax_4_f16.cl.h" - }; -#else - const std::string kernel_src = read_file("softmax_4_f16.cl"); -#endif - backend_ctx->program_softmax_4_f16 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_soft_max_4_f16 = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_soft_max_4_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_fa_decompose_soft_max_4_f16 = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_fa_decompose_soft_max_4_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_fa_decompose_scale_rows_f32 = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_fa_decompose_scale_rows_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_fa_p8_fixup = clCreateKernel(backend_ctx->program_softmax_4_f16, "kernel_fa_p8_fixup", &err), err)); - GGML_LOG_CONT("."); - } - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "flash_attn_pv_direct.cl.h" - }; -#else - const std::string kernel_src = read_file("flash_attn_pv_direct.cl"); -#endif - cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), - compile_opts, /*fatal=*/false); - if (prog != nullptr) { - CL_CHECK((backend_ctx->kernel_fa_kqv_direct_f16 = clCreateKernel(prog, "kernel_fa_kqv_direct_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_fa_kqv_direct_reduce = clCreateKernel(prog, "kernel_fa_kqv_direct_reduce", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - GGML_LOG_CONT("."); - } - - if (backend_ctx->gpu_family == ADRENO && backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_q8_f32_kqv.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_q8_f32_kqv.cl"); -#endif - cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), - compile_opts, /*fatal=*/false); - if (prog != nullptr) { - CL_CHECK((backend_ctx->kernel_mul_mm_q8_f32_kqv = clCreateKernel(prog, "kernel_mul_mm_q8_f32_kqv", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - GGML_LOG_CONT("."); - } -#endif - - // div - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "div.cl.h" - }; -#else - const std::string kernel_src = read_file("div.cl"); -#endif - std::string compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable -cl-finite-math-only "; - - backend_ctx->program_div = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_div = clCreateKernel(backend_ctx->program_div, "kernel_div", &err), err)); - CL_CHECK((backend_ctx->kernel_div_row = clCreateKernel(backend_ctx->program_div, "kernel_div_row", &err), err)); - CL_CHECK((backend_ctx->kernel_div_f16 = clCreateKernel(backend_ctx->program_div, "kernel_div_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_div_row_f16 = clCreateKernel(backend_ctx->program_div, "kernel_div_row_f16", &err), err)); - GGML_LOG_CONT("."); - } - - // sqr - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "sqr.cl.h" - }; -#else - const std::string kernel_src = read_file("sqr.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_sqr_cont_f32 = clCreateKernel(prog, "kernel_sqr_cont_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_sqr_cont_f32_4 = clCreateKernel(prog, "kernel_sqr_cont_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_sqr_cont_f16 = clCreateKernel(prog, "kernel_sqr_cont_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_sqr_cont_f16_4 = clCreateKernel(prog, "kernel_sqr_cont_f16_4", &err), err)); - - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // sqrt - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "sqrt.cl.h" - }; -#else - const std::string kernel_src = read_file("sqrt.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_sqrt_cont_f32 = clCreateKernel(prog, "kernel_sqrt_cont_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_sqrt_cont_f32_4 = clCreateKernel(prog, "kernel_sqrt_cont_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_sqrt_cont_f16 = clCreateKernel(prog, "kernel_sqrt_cont_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_sqrt_cont_f16_4 = clCreateKernel(prog, "kernel_sqrt_cont_f16_4", &err), err)); - - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mean - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mean.cl.h" - }; -#else - const std::string kernel_src = read_file("mean.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mean_f32 = clCreateKernel(prog, "kernel_mean_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_mean_f32_4 = clCreateKernel(prog, "kernel_mean_f32_4", &err), err)); - - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // sub - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "sub.cl.h" - }; -#else - const std::string kernel_src = read_file("sub.cl"); -#endif - backend_ctx->program_sub = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_sub = clCreateKernel(backend_ctx->program_sub, "kernel_sub", &err), err)); - CL_CHECK((backend_ctx->kernel_sub_row = clCreateKernel(backend_ctx->program_sub, "kernel_sub_row", &err), err)); - CL_CHECK((backend_ctx->kernel_sub_f16 = clCreateKernel(backend_ctx->program_sub, "kernel_sub_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_sub_row_f16 = clCreateKernel(backend_ctx->program_sub, "kernel_sub_row_f16", &err), err)); - GGML_LOG_CONT("."); - } - - // dsv4_hc - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "dsv4_hc.cl.h" - }; -#else - const std::string kernel_src = read_file("dsv4_hc.cl"); -#endif - for (int i = 0; i < 2; ++i) { - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + (i == 0 ? " -DHC_VEC=1" : " -DHC_VEC=4")); - if (i == 0) { - CL_CHECK((backend_ctx->kernel_dsv4_hc_pre = clCreateKernel(prog, "kernel_dsv4_hc_pre", &err), err)); - backend_ctx->local_dsv4_hc_pre = MIN((size_t) 64, backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_dsv4_hc_pre)); - } - CL_CHECK((backend_ctx->kernel_dsv4_hc_post[i] = clCreateKernel(prog, "kernel_dsv4_hc_post", &err), err)); - backend_ctx->local_dsv4_hc_post[i] = MIN((size_t) 64, backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_dsv4_hc_post[i])); - CL_CHECK(clReleaseProgram(prog)); - } - GGML_LOG_CONT("."); - } - - // sum_rows - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "sum_rows.cl.h" - }; -#else - const std::string kernel_src = read_file("sum_rows.cl"); -#endif - backend_ctx->program_sum_rows_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_sum_rows_f32 = clCreateKernel(backend_ctx->program_sum_rows_f32, "kernel_sum_rows_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_sum_rows_f32_4 = clCreateKernel(backend_ctx->program_sum_rows_f32, "kernel_sum_rows_f32_4", &err), err)); - GGML_LOG_CONT("."); - } - - // cumsum - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "cumsum.cl.h" - }; -#else - const std::string kernel_src = read_file("cumsum.cl"); -#endif - cl_program prog; - prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_cumsum_blk = clCreateKernel(prog, "kernel_cumsum_blk", &err), err)); - CL_CHECK((backend_ctx->kernel_cumsum_add = clCreateKernel(prog, "kernel_cumsum_add", &err), err)); - GGML_LOG_CONT("."); - CL_CHECK(clReleaseProgram(prog)); - } - - // sigmoid - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "sigmoid.cl.h" - }; -#else - const std::string kernel_src = read_file("sigmoid.cl"); -#endif - backend_ctx->program_sigmoid = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_sigmoid_f32 = clCreateKernel(backend_ctx->program_sigmoid, "kernel_sigmoid_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_sigmoid_f16 = clCreateKernel(backend_ctx->program_sigmoid, "kernel_sigmoid_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_sigmoid_f32_nc = clCreateKernel(backend_ctx->program_sigmoid, "kernel_sigmoid_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_sigmoid_f16_nc = clCreateKernel(backend_ctx->program_sigmoid, "kernel_sigmoid_f16_nc", &err), err)); - GGML_LOG_CONT("."); - } - - // group_norm - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "group_norm.cl.h" - }; -#else - const std::string kernel_src = read_file("group_norm.cl"); -#endif - backend_ctx->program_group_norm = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_group_norm = clCreateKernel(backend_ctx->program_group_norm, "kernel_group_norm", &err), err)); - CL_CHECK((backend_ctx->kernel_group_norm_mul_add = clCreateKernel(backend_ctx->program_group_norm, "kernel_group_norm_mul_add", &err), err)); - GGML_LOG_CONT("."); - } - - // repeat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "repeat.cl.h" - }; -#else - const std::string kernel_src = read_file("repeat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_repeat_f32 = clCreateKernel(prog, "kernel_repeat_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_repeat_f16 = clCreateKernel(prog, "kernel_repeat_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_repeat_i32 = clCreateKernel(prog, "kernel_repeat_i32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // pad - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "pad.cl.h" - }; -#else - const std::string kernel_src = read_file("pad.cl"); -#endif - if (!kernel_src.empty()) { - backend_ctx->program_pad = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_pad = clCreateKernel(backend_ctx->program_pad, "kernel_pad", &err), err)); - GGML_LOG_CONT("."); - } else { - GGML_LOG_WARN("ggml_opencl: pad kernel source not found or empty. Pad operations will not be available.\n"); - backend_ctx->program_pad = nullptr; - backend_ctx->kernel_pad = nullptr; - } - } - - // tanh - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "tanh.cl.h" - }; -#else - const std::string kernel_src = read_file("tanh.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_tanh_f32 = clCreateKernel(prog, "kernel_tanh_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_tanh_f32_4 = clCreateKernel(prog, "kernel_tanh_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_tanh_f32_nc = clCreateKernel(prog, "kernel_tanh_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_tanh_f16 = clCreateKernel(prog, "kernel_tanh_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_tanh_f16_4 = clCreateKernel(prog, "kernel_tanh_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_tanh_f16_nc = clCreateKernel(prog, "kernel_tanh_f16_nc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // neg - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "neg.cl.h" - }; -#else - const std::string kernel_src = read_file("neg.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_neg_f32 = clCreateKernel(prog, "kernel_neg_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_neg_f32_4 = clCreateKernel(prog, "kernel_neg_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_neg_f32_nc = clCreateKernel(prog, "kernel_neg_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_neg_f16 = clCreateKernel(prog, "kernel_neg_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_neg_f16_4 = clCreateKernel(prog, "kernel_neg_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_neg_f16_nc = clCreateKernel(prog, "kernel_neg_f16_nc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // exp - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "exp.cl.h" - }; -#else - const std::string kernel_src = read_file("exp.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_exp_f32 = clCreateKernel(prog, "kernel_exp_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_exp_f32_4 = clCreateKernel(prog, "kernel_exp_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_exp_f32_nc = clCreateKernel(prog, "kernel_exp_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_exp_f16 = clCreateKernel(prog, "kernel_exp_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_exp_f16_4 = clCreateKernel(prog, "kernel_exp_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_exp_f16_nc = clCreateKernel(prog, "kernel_exp_f16_nc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // expm1 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "expm1.cl.h" - }; -#else - const std::string kernel_src = read_file("expm1.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_expm1_f32 = clCreateKernel(prog, "kernel_expm1_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_expm1_f32_4 = clCreateKernel(prog, "kernel_expm1_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_expm1_f32_nc = clCreateKernel(prog, "kernel_expm1_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_expm1_f16 = clCreateKernel(prog, "kernel_expm1_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_expm1_f16_4 = clCreateKernel(prog, "kernel_expm1_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_expm1_f16_nc = clCreateKernel(prog, "kernel_expm1_f16_nc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // abs - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "abs.cl.h" - }; -#else - const std::string kernel_src = read_file("abs.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_abs_f32 = clCreateKernel(prog, "kernel_abs_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_abs_f32_4 = clCreateKernel(prog, "kernel_abs_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_abs_f32_nc = clCreateKernel(prog, "kernel_abs_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_abs_f16 = clCreateKernel(prog, "kernel_abs_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_abs_f16_4 = clCreateKernel(prog, "kernel_abs_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_abs_f16_nc = clCreateKernel(prog, "kernel_abs_f16_nc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // unary_ext (sgn, step, elu, hardswish, hardsigmoid, floor, ceil, round, trunc) - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "unary_ext.cl.h" - }; -#else - const std::string kernel_src = read_file("unary_ext.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); -#define CL_UNARY_EXT_K(op) \ - CL_CHECK((backend_ctx->kernel_##op##_f32 = clCreateKernel(prog, "kernel_" #op "_f32", &err), err)); \ - CL_CHECK((backend_ctx->kernel_##op##_f32_4 = clCreateKernel(prog, "kernel_" #op "_f32_4", &err), err)); \ - CL_CHECK((backend_ctx->kernel_##op##_f32_nc = clCreateKernel(prog, "kernel_" #op "_f32_nc", &err), err)); \ - CL_CHECK((backend_ctx->kernel_##op##_f16 = clCreateKernel(prog, "kernel_" #op "_f16", &err), err)); \ - CL_CHECK((backend_ctx->kernel_##op##_f16_4 = clCreateKernel(prog, "kernel_" #op "_f16_4", &err), err)); \ - CL_CHECK((backend_ctx->kernel_##op##_f16_nc = clCreateKernel(prog, "kernel_" #op "_f16_nc", &err), err)); - CL_UNARY_EXT_K(sgn) - CL_UNARY_EXT_K(step) - CL_UNARY_EXT_K(elu) - CL_UNARY_EXT_K(hardswish) - CL_UNARY_EXT_K(hardsigmoid) - CL_UNARY_EXT_K(floor) - CL_UNARY_EXT_K(ceil) - CL_UNARY_EXT_K(round) - CL_UNARY_EXT_K(trunc) - CL_UNARY_EXT_K(log) -#undef CL_UNARY_EXT_K - CL_CHECK((backend_ctx->kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // softplus - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "softplus.cl.h" - }; -#else - const std::string kernel_src = read_file("softplus.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_softplus_f32 = clCreateKernel(prog, "kernel_softplus_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_softplus_f32_4 = clCreateKernel(prog, "kernel_softplus_f32_4", &err), err)); - CL_CHECK((backend_ctx->kernel_softplus_f32_nc = clCreateKernel(prog, "kernel_softplus_f32_nc", &err), err)); - CL_CHECK((backend_ctx->kernel_softplus_f16 = clCreateKernel(prog, "kernel_softplus_f16", &err), err)); - CL_CHECK((backend_ctx->kernel_softplus_f16_4 = clCreateKernel(prog, "kernel_softplus_f16_4", &err), err)); - CL_CHECK((backend_ctx->kernel_softplus_f16_nc = clCreateKernel(prog, "kernel_softplus_f16_nc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // upscale - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "upscale.cl.h" - }; -#else - const std::string kernel_src = read_file("upscale.cl"); -#endif - if (!kernel_src.empty()) { - backend_ctx->program_upscale = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_upscale = clCreateKernel(backend_ctx->program_upscale, "kernel_upscale", &err), err)); - if (backend_ctx->program_upscale) { - cl_int err_bilinear; - backend_ctx->kernel_upscale_bilinear = clCreateKernel(backend_ctx->program_upscale, "kernel_upscale_bilinear", &err_bilinear); - if (err_bilinear != CL_SUCCESS) { - GGML_LOG_WARN("ggml_opencl: kernel_upscale_bilinear not found in upscale.cl. Bilinear upscale will not be available. Error: %d\n", err_bilinear); - backend_ctx->kernel_upscale_bilinear = nullptr; - } - } else { - backend_ctx->kernel_upscale_bilinear = nullptr; - } - GGML_LOG_CONT("."); - } else { - GGML_LOG_WARN("ggml_opencl: upscale kernel source not found or empty. Upscale operations will not be available.\n"); - backend_ctx->program_upscale = nullptr; - backend_ctx->kernel_upscale = nullptr; - backend_ctx->kernel_upscale_bilinear = nullptr; - } - } - - // concat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "concat.cl.h" - }; -#else - const std::string kernel_src = read_file("concat.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_concat_b1 = clCreateKernel(prog, "kernel_concat_b1", &err), err)); - CL_CHECK((backend_ctx->kernel_concat_b2 = clCreateKernel(prog, "kernel_concat_b2", &err), err)); - CL_CHECK((backend_ctx->kernel_concat_b4 = clCreateKernel(prog, "kernel_concat_b4", &err), err)); - CL_CHECK((backend_ctx->kernel_concat_b8 = clCreateKernel(prog, "kernel_concat_b8", &err), err)); - CL_CHECK((backend_ctx->kernel_concat_b4_pack = clCreateKernel(prog, "kernel_concat_b4_pack", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // timestep_embedding - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "tsembd.cl.h" - }; -#else - - const std::string kernel_src = read_file("tsembd.cl"); -#endif - if (!kernel_src.empty()) { - backend_ctx->program_tsembd = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_timestep_embedding = clCreateKernel(backend_ctx->program_tsembd, "kernel_timestep_embedding", &err), err)); - GGML_LOG_CONT("."); - } else { - GGML_LOG_WARN("ggml_opencl: timestep_embedding kernel source not found or empty. This op will not be available.\n"); - backend_ctx->program_tsembd = nullptr; - backend_ctx->kernel_timestep_embedding = nullptr; - } - } - - // set_rows - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "set_rows.cl.h" - }; -#else - const std::string kernel_src = read_file("set_rows.cl"); -#endif - backend_ctx->program_set_rows = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_set_rows_f32_i64 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_f32_i64", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_f32_i32 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_f32_i32", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_f16_i64 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_f16_i64", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_f16_i32 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_f16_i32", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q8_0_i64 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q8_0_i64", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q8_0_i32 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q8_0_i32", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q8_0_soa_i64 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q8_0_soa_i64", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q8_0_soa_i32 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q8_0_soa_i32", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q4_0_i64 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q4_0_i64", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q4_0_i32 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q4_0_i32", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q4_0_soa_i64 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q4_0_soa_i64", &err), err)); - CL_CHECK((backend_ctx->kernel_set_rows_q4_0_soa_i32 = clCreateKernel(backend_ctx->program_set_rows, "kernel_set_rows_q4_0_soa_i32", &err), err)); - GGML_LOG_CONT("."); - } - - // conv2d - { - #ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "conv2d.cl.h" - }; - const std::string kernel_src_f16_f32 { - #include "conv2d_f16_f32.cl.h" - }; - #else - const std::string kernel_src = read_file("conv2d.cl"); - const std::string kernel_src_f16_f32 = read_file("conv2d_f16_f32.cl"); - #endif - if (!kernel_src.empty()) { - backend_ctx->program_conv_2d_f16 = - build_program_from_source(backend_ctx, kernel_src.c_str(), (std::string(compile_opts) + " -DUSE_FP16=1").c_str()); - CL_CHECK((backend_ctx->kernel_conv_2d_f16 = clCreateKernel(backend_ctx->program_conv_2d_f16, "kernel_conv_2d", &err), err)); - GGML_LOG_CONT("."); - backend_ctx->program_conv_2d_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_conv_2d_f32 = clCreateKernel(backend_ctx->program_conv_2d_f32, "kernel_conv_2d", &err), err)); - GGML_LOG_CONT("."); - } else { - GGML_LOG_WARN("ggml_opencl: conv2d kernel source not found or empty. This op will not be available.\n"); - backend_ctx->program_conv_2d_f16 = nullptr; - backend_ctx->kernel_conv_2d_f16 = nullptr; - backend_ctx->program_conv_2d_f32 = nullptr; - backend_ctx->kernel_conv_2d_f32 = nullptr; - } - if (!kernel_src_f16_f32.empty()) { - backend_ctx->program_conv_2d_f16_f32 = - build_program_from_source(backend_ctx, kernel_src_f16_f32.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_conv_2d_f16_f32 = clCreateKernel(backend_ctx->program_conv_2d_f16_f32, "kernel_conv_2d", &err), err)); - GGML_LOG_CONT("."); - } else { - GGML_LOG_WARN("ggml_opencl: conv2d_f16_f32 kernel source not found or empty. This op will not be available.\n"); - backend_ctx->program_conv_2d_f16_f32 = nullptr; - backend_ctx->kernel_conv_2d_f16_f32 = nullptr; - } - } - - // conv2_dw - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "conv2_dw.cl.h" - }; -#else - const std::string kernel_src = read_file("conv2_dw.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_conv2d_dw_f32_f32 = clCreateKernel(prog, "kernel_conv2d_dw_f32_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_conv2d_dwf16_f32 = clCreateKernel(prog, "kernel_conv2d_dwf16_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // ssm_conv - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "ssm_conv.cl.h" - }; -#else - const std::string kernel_src = read_file("ssm_conv.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_ssm_conv_f32_f32 = clCreateKernel(prog, "kernel_ssm_conv_f32_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_ssm_conv_f32_f32_4 = clCreateKernel(prog, "kernel_ssm_conv_f32_f32_4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // ssm_scan - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "ssm_scan.cl.h" - }; -#else - const std::string kernel_src = read_file("ssm_scan.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_ssm_scan_f32 = clCreateKernel(prog, "kernel_ssm_scan_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_ssm_scan_f32_mamba2_d128 = clCreateKernel(prog, "kernel_ssm_scan_f32_mamba2_d128", &err), err)); - CL_CHECK((backend_ctx->kernel_ssm_scan_f32_mamba2_d256 = clCreateKernel(prog, "kernel_ssm_scan_f32_mamba2_d256", &err), err)); - - cl_kernel * kernels[] = { - &backend_ctx->kernel_ssm_scan_f32_mamba2_d128, - &backend_ctx->kernel_ssm_scan_f32_mamba2_d256 - }; - - // specialized kernels use subgroups and assume subgroup size is 64, - // if device does not support subgroups or subgroup size is not 64, - // release these kernels - for (int i = 0; i < 2; ++i) { - size_t subgroup_size = 0; -#if CL_TARGET_OPENCL_VERSION >= 210 - const size_t local_work_size[] = { 64, 1 }; - const cl_int subgroup_err = clGetKernelSubGroupInfo(*kernels[i], backend_ctx->device, CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE, - sizeof(local_work_size), local_work_size, sizeof(subgroup_size), &subgroup_size, nullptr); - if (subgroup_err != CL_SUCCESS) { - subgroup_size = 0; - } -#endif - // The specialized kernels reduce over one 64-lane subgroup. - if (subgroup_size != 64) { - CL_CHECK(clReleaseKernel(*kernels[i])); - *kernels[i] = nullptr; - } - } - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gated_delta_net: one kernel per (S_V, KDA, tgpp, replay). - { - #ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gated_delta_net.cl.h" - }; - #else - const std::string kernel_src = read_file("gated_delta_net.cl"); - #endif - - const int gdn_sizes[4] = { 16, 32, 64, 128 }; - const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1; - if (sg_size < 0) { - GGML_LOG_ERROR("Unsupported GPU Family: only Adreno and Intel are supported.\n"); - exit(1); - } - - for (int si = 0; si < 4; si++) { - const int S_V = gdn_sizes[si]; - - // MUST match the dispatcher heuristic in ggml_cl_gated_delta_net exactly. - int lanes_per_column; - if (S_V >= 128) { - lanes_per_column = 8; - } else { - lanes_per_column = std::min(S_V, sg_size); - } - - // Round LANES_PER_COLUMN down until it is: - // * power-of-two - // * divides both S_V and sg_size - while (lanes_per_column > 1 && - (((lanes_per_column & (lanes_per_column - 1)) != 0) || - (S_V % lanes_per_column) != 0 || - (sg_size % lanes_per_column) != 0)) { - lanes_per_column >>= 1; - } - - GGML_ASSERT(lanes_per_column >= 1); - GGML_ASSERT(((lanes_per_column & (lanes_per_column - 1)) == 0)); - GGML_ASSERT((S_V % lanes_per_column) == 0); - GGML_ASSERT((sg_size % lanes_per_column) == 0); - - const bool is_partial_reduce = (lanes_per_column != 1) && (lanes_per_column < sg_size); - int use_qcom_shuffle = 0; - if (is_partial_reduce) { - if (backend_ctx->has_qcom_subgroup_shuffle) { - use_qcom_shuffle = 1; - } - } - for (int kda = 0; kda < 2; kda++) { - for (int tgpp = 0; tgpp < 2; tgpp++) { - const int cpl = (tgpp == 0) ? 1 : 4; - const int spw = (tgpp == 0) ? 1 : 1; - - std::string opts = compile_opts; - opts += " -DS_V=" + std::to_string(S_V); - opts += " -DKDA=" + std::to_string(kda); - opts += " -DSUBGROUP_SIZE=" + std::to_string(sg_size); - opts += " -DLANES_PER_COLUMN=" + std::to_string(lanes_per_column); - opts += " -DCOLS_PER_LANE_GROUP=" + std::to_string(cpl); - opts += " -DUSE_QCOM_SUBGROUP_SHUFFLE=" + std::to_string(use_qcom_shuffle); - - // Since spw=1 is found to be optimal, SUBGROUPS_PER_WG > 1 code in - // the kernel is removed. If you want to experiment with spw > 1, - // Please remember to implement code to handle it. - opts += " -DSUBGROUPS_PER_WG=" + std::to_string(spw); - - for (int replay = 0; replay < 2; replay++) { - const std::string opts_rep = opts + " -DREPLAY=" + std::to_string(replay); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts_rep); - - CL_CHECK((backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay] = - clCreateKernel(prog, "kernel_gated_delta_net", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - } - } - } - } - GGML_LOG_CONT("."); - } - - // moe_combine (fused router-weight mul + cross-expert sum) - { - #ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "moe_combine.cl.h" - }; - #else - const std::string kernel_src = read_file("moe_combine.cl"); - #endif - cl_program prog = build_program_from_source( - backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_moe_combine_f32 = - clCreateKernel(prog, "kernel_moe_combine_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_combine_bias_f32 = - clCreateKernel(prog, "kernel_moe_combine_bias_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_id_f32_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_id_f32_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_id_f32_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mv_id_f32_f32 = clCreateKernel(prog, "kernel_mul_mv_id_f32_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mm_id_f32_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mm_id_f32_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mm_id_f32_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_mul_mm_id_f32_f32 = clCreateKernel(prog, "kernel_mul_mm_id_f32_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mv_id_q4_0_f32_8x_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_id_q4_0_f32_8x_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_id_q4_0_f32_8x_flat.cl"); -#endif - backend_ctx->program_mul_mv_id_q4_0_f32_8x_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_id_q4_0_f32_8x_flat = clCreateKernel(backend_ctx->program_mul_mv_id_q4_0_f32_8x_flat, "kernel_mul_mv_id_q4_0_f32_8x_flat", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_id_q8_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_id_q8_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_id_q8_0_f32.cl"); -#endif - backend_ctx->program_mul_mv_id_q8_0_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_id_q8_0_f32 = clCreateKernel(backend_ctx->program_mul_mv_id_q8_0_f32, "kernel_mul_mv_id_q8_0_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_id_q8_0_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_id_q8_0_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_id_q8_0_f32_flat.cl"); -#endif - backend_ctx->program_mul_mv_id_q8_0_f32_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_id_q8_0_f32_flat = clCreateKernel(backend_ctx->program_mul_mv_id_q8_0_f32_flat, "kernel_mul_mv_id_q8_0_f32_flat", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_id_mxfp4_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_id_mxfp4_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_id_mxfp4_f32.cl"); -#endif - backend_ctx->program_mul_mv_id_mxfp4_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_id_mxfp4_f32 = clCreateKernel(backend_ctx->program_mul_mv_id_mxfp4_f32, "kernel_mul_mv_id_mxfp4_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // mul_mv_id_mxfp4_f32_flat - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "mul_mv_id_mxfp4_f32_flat.cl.h" - }; -#else - const std::string kernel_src = read_file("mul_mv_id_mxfp4_f32_flat.cl"); -#endif - backend_ctx->program_mul_mv_id_mxfp4_f32_flat = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_mul_mv_id_mxfp4_f32_flat = clCreateKernel(backend_ctx->program_mul_mv_id_mxfp4_f32_flat, "kernel_mul_mv_id_mxfp4_f32_flat", &err), err)); - GGML_LOG_CONT("."); - } - - // Adreno kernels -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // transpose - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "transpose.cl.h" - }; -#else - const std::string kernel_src = read_file("transpose.cl"); -#endif - backend_ctx->program_transpose = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->kernel_transpose_32_16 = clCreateKernel(backend_ctx->program_transpose, "kernel_transpose_32_16", &err), err)); - CL_CHECK((backend_ctx->kernel_transpose_32 = clCreateKernel(backend_ctx->program_transpose, "kernel_transpose_32", &err), err)); - CL_CHECK((backend_ctx->kernel_transpose_16 = clCreateKernel(backend_ctx->program_transpose, "kernel_transpose_16", &err), err)); - CL_CHECK((backend_ctx->kernel_transpose_8_buf = clCreateKernel(backend_ctx->program_transpose, "kernel_transpose_8_buf", &err), err)); - CL_CHECK((backend_ctx->kernel_transpose_16_buf = clCreateKernel(backend_ctx->program_transpose, "kernel_transpose_16_buf", &err), err)); - CL_CHECK((backend_ctx->kernel_transpose_32_buf = clCreateKernel(backend_ctx->program_transpose, "kernel_transpose_32_buf", &err), err)); - CL_CHECK((backend_ctx->kernel_transpose_16_4x1 = clCreateKernel(backend_ctx->program_transpose, "kernel_transpose_16_4x1", &err), err)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q1_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q1_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q1_0_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q1_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q1_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q1_0_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src_CL_gemv_general { - #include "gemv_noshuffle_q1_0_f32.cl.h" - }; -#else - const std::string kernel_src_CL_gemv_general = read_file("gemv_noshuffle_q1_0_f32.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q1_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q1_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - - const char * nsg1_min_m_env = getenv("GGML_OPENCL_Q1_0_GEMV_NSG1_MIN_M"); - backend_ctx->min_m_gemv_nsg1_q1_0 = nsg1_min_m_env ? atoi(nsg1_min_m_env) : - (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 8192 : 0); - if (backend_ctx->min_m_gemv_nsg1_q1_0 > 0) { - const std::string nsg1_opts = CL_gemv_compile_opts + " -DN_SIMDGROUP=1"; - cl_program prog_nsg1 = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), nsg1_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q1_0_f32_nsg1 = clCreateKernel(prog_nsg1, "kernel_gemv_noshuffle_q1_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog_nsg1)); - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q3_k_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q3_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q3_k_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q3_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q3_k_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q3_k_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_q3_k_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q2_0_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q2_0_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q2_0_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q2_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_0_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q2_0_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_0_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq4_xs_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq4_xs_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq4_xs_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq4_xs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq4_xs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq4_xs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq4_xs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_xs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q2_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q2_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q2_0_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q2_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq4_xs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq4_xs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq4_xs_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ4_XS_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq4_xs_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ4_XS_MV_NSG=" + std::to_string(backend_ctx->iq4_xs_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq4_xs_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq4_xs_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq4_xs_f32 = kernel; - CL_CHECK(clReleaseProgram(prog)); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq4_xs_mv_nsg > 1); - backend_ctx->iq4_xs_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q2_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q2_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q2_0_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_Q2_0_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8 || nsg == 16 || nsg == 32) { - backend_ctx->q2_0_mv_nsg = nsg; - } - } - for (int wide = 0; wide < 2; ++wide) { - const std::string opts = compile_opts + " -DQ2_0_MV_WIDE=" + std::to_string(wide); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_q2_0_f32", &err); - CL_CHECK(err); - CL_CHECK(clReleaseProgram(prog)); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - size_t workgroup = 512; - while (workgroup > max_workgroup) { - workgroup /= 2; - } - GGML_ASSERT(workgroup >= 64); - if (wide) { - backend_ctx->kernel_gemv_noshuffle_q2_0_f32_wide = kernel; - backend_ctx->q2_0_mv_workgroup_size_wide = workgroup; - } else { - backend_ctx->kernel_gemv_noshuffle_q2_0_f32 = kernel; - backend_ctx->q2_0_mv_workgroup_size = workgroup; - } - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq1_s_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq1_s_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq1_s_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq1_s_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_s_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq1_s_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_s_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq1_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq1_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq1_s_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq1_s_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_s_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq1_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq1_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq1_s_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ1_S_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq1_s_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ1_S_MV_NSG=" + std::to_string(backend_ctx->iq1_s_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq1_s_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq1_s_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq1_s_f32 = kernel; - cl_kernel export_grid = clCreateKernel(prog, "kernel_iq1_s_grid_export", &err); - CL_CHECK(err); - backend_ctx->iq1_s_grid_buffer.allocate(backend_ctx->context, 2048*sizeof(cl_uint)); - CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq1_s_grid_buffer.buffer)); - size_t global[] = { 2048 }; - size_t local[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseKernel(export_grid)); - CL_CHECK(clReleaseProgram(prog)); - - cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = 2048; - desc.buffer = backend_ctx->iq1_s_grid_buffer.buffer; - backend_ctx->iq1_s_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); - CL_CHECK(err); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq1_s_mv_nsg > 1); - backend_ctx->iq1_s_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq1_m_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq1_m_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq1_m_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq1_m_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_m_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq1_m_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_m_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq1_m_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq1_m_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq1_m_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq1_m_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_m_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq1_m_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq1_m_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq1_m_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ1_M_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq1_m_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ1_M_MV_NSG=" + std::to_string(backend_ctx->iq1_m_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq1_m_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq1_m_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq1_m_f32 = kernel; - CL_CHECK(clReleaseProgram(prog)); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq1_m_mv_nsg > 1); - backend_ctx->iq1_m_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq3_s_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq3_s_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq3_s_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq3_s_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_s_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq3_s_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_s_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq3_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq3_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq3_s_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq3_s_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_s_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq3_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq3_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq3_s_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ3_S_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq3_s_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ3_S_MV_NSG=" + std::to_string(backend_ctx->iq3_s_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq3_s_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq3_s_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq3_s_f32 = kernel; - cl_kernel export_grid = clCreateKernel(prog, "kernel_iq3_s_grid_export", &err); - CL_CHECK(err); - backend_ctx->iq3_s_grid_buffer.allocate(backend_ctx->context, 512*sizeof(cl_uint)); - CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq3_s_grid_buffer.buffer)); - size_t global[] = { 512 }; - size_t local[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseKernel(export_grid)); - CL_CHECK(clReleaseProgram(prog)); - - cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = 512; - desc.buffer = backend_ctx->iq3_s_grid_buffer.buffer; - backend_ctx->iq3_s_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); - CL_CHECK(err); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq3_s_mv_nsg > 1); - backend_ctx->iq3_s_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq3_xxs_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq3_xxs_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq3_xxs_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq3_xxs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq3_xxs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq3_xxs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq3_xxs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_xxs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq3_xxs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq3_xxs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq3_xxs_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ3_XXS_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq3_xxs_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ3_XXS_MV_NSG=" + std::to_string(backend_ctx->iq3_xxs_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq3_xxs_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq3_xxs_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq3_xxs_f32 = kernel; - cl_kernel export_grid = clCreateKernel(prog, "kernel_iq3_xxs_grid_export", &err); - CL_CHECK(err); - backend_ctx->iq3_xxs_grid_buffer.allocate(backend_ctx->context, 256*sizeof(cl_uint)); - CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq3_xxs_grid_buffer.buffer)); - size_t global[] = { 256 }; - size_t local[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseKernel(export_grid)); - CL_CHECK(clReleaseProgram(prog)); - - cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = 256; - desc.buffer = backend_ctx->iq3_xxs_grid_buffer.buffer; - backend_ctx->iq3_xxs_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); - CL_CHECK(err); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq3_xxs_mv_nsg > 1); - backend_ctx->iq3_xxs_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq2_s_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq2_s_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq2_s_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_s_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_s_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_s_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_s_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq2_xs_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq2_xs_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq2_xs_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq2_xxs_q8_1_dp4a - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq2_xxs_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq2_xxs_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq2_xxs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq2_xxs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq2_xxs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_xxs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xxs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq2_xxs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq2_xxs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq2_xxs_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ2_XXS_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq2_xxs_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ2_XXS_MV_NSG=" + std::to_string(backend_ctx->iq2_xxs_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq2_xxs_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq2_xxs_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq2_xxs_f32 = kernel; - cl_kernel export_grid = clCreateKernel(prog, "kernel_iq2_xxs_grid_export", &err); - CL_CHECK(err); - backend_ctx->iq2_xxs_grid_buffer.allocate(backend_ctx->context, 512*sizeof(cl_uint)); - CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq2_xxs_grid_buffer.buffer)); - size_t global[] = { 512 }; - size_t local[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseKernel(export_grid)); - CL_CHECK(clReleaseProgram(prog)); - - cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = 512; - desc.buffer = backend_ctx->iq2_xxs_grid_buffer.buffer; - backend_ctx->iq2_xxs_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); - CL_CHECK(err); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq2_xxs_mv_nsg > 1); - backend_ctx->iq2_xxs_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq2_xs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq2_xs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq2_xs_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_xs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xs_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq2_xs_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq2_xs_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq2_xs_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ2_XS_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq2_xs_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ2_XS_MV_NSG=" + std::to_string(backend_ctx->iq2_xs_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq2_xs_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq2_xs_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq2_xs_f32 = kernel; - cl_kernel export_grid = clCreateKernel(prog, "kernel_iq2_xs_grid_export", &err); - CL_CHECK(err); - backend_ctx->iq2_xs_grid_buffer.allocate(backend_ctx->context, 1024*sizeof(cl_uint)); - CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq2_xs_grid_buffer.buffer)); - size_t global[] = { 1024 }; - size_t local[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseKernel(export_grid)); - CL_CHECK(clReleaseProgram(prog)); - - cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = 1024; - desc.buffer = backend_ctx->iq2_xs_grid_buffer.buffer; - backend_ctx->iq2_xs_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); - CL_CHECK(err); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq2_xs_mv_nsg > 1); - backend_ctx->iq2_xs_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq2_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq2_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq2_s_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq2_s_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_s_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq2_s_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq2_s_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq2_s_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_IQ2_S_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->iq2_s_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DIQ2_S_MV_NSG=" + std::to_string(backend_ctx->iq2_s_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq2_s_f32", &err); - CL_CHECK(err); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->iq2_s_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_iq2_s_f32 = kernel; - cl_kernel export_grid = clCreateKernel(prog, "kernel_iq2_s_grid_export", &err); - CL_CHECK(err); - backend_ctx->iq2_s_grid_buffer.allocate(backend_ctx->context, 2048*sizeof(cl_uint)); - CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq2_s_grid_buffer.buffer)); - size_t global[] = { 2048 }; - size_t local[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseKernel(export_grid)); - CL_CHECK(clReleaseProgram(prog)); - - cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = 2048; - desc.buffer = backend_ctx->iq2_s_grid_buffer.buffer; - backend_ctx->iq2_s_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); - CL_CHECK(err); - break; - } - CL_CHECK(clReleaseKernel(kernel)); - CL_CHECK(clReleaseProgram(prog)); - GGML_ASSERT(backend_ctx->iq2_s_mv_nsg > 1); - backend_ctx->iq2_s_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q3_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q3_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q3_k_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q3_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q3_k_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q3_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q3_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q3_k_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_Q3_K_MV_R")) { - const int rows = atoi(env); - if (rows == 1 || rows == 2 || rows == 4) { - backend_ctx->q3_k_mv_rows = rows; - } - } - if (const char * env = getenv("GGML_OPENCL_Q3_K_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->q3_k_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DQ3_K_MV_R=" + std::to_string(backend_ctx->q3_k_mv_rows) + - " -DQ3_K_MV_NSG=" + std::to_string(backend_ctx->q3_k_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_q3_k_f32", &err); - CL_CHECK(err); - CL_CHECK(clReleaseProgram(prog)); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->q3_k_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_q3_k_f32 = kernel; - break; - } - CL_CHECK(clReleaseKernel(kernel)); - GGML_ASSERT(backend_ctx->q3_k_mv_nsg > 1); - backend_ctx->q3_k_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q2_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q2_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q2_k_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q2_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_k_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q2_k_q8_1_dp4a - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q2_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q2_k_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q2_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_k_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + " -DTILESIZE_N=8"); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q2_k_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_k_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q2_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q2_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q2_k_f32.cl"); -#endif - if (const char * env = getenv("GGML_OPENCL_Q2_K_MV_R")) { - const int rows = atoi(env); - if (rows == 1 || rows == 2 || rows == 4) { - backend_ctx->q2_k_mv_rows = rows; - } - } - if (const char * env = getenv("GGML_OPENCL_Q2_K_MV_NSG")) { - const int nsg = atoi(env); - if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { - backend_ctx->q2_k_mv_nsg = nsg; - } - } - for (;;) { - const std::string opts = compile_opts + " -DQ2_K_MV_R=" + std::to_string(backend_ctx->q2_k_mv_rows) + - " -DQ2_K_MV_NSG=" + std::to_string(backend_ctx->q2_k_mv_nsg); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_q2_k_f32", &err); - CL_CHECK(err); - CL_CHECK(clReleaseProgram(prog)); - size_t max_workgroup; - CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); - if (64*(size_t)backend_ctx->q2_k_mv_nsg <= max_workgroup) { - backend_ctx->kernel_gemv_noshuffle_q2_k_f32 = kernel; - break; - } - CL_CHECK(clReleaseKernel(kernel)); - GGML_ASSERT(backend_ctx->q2_k_mv_nsg > 1); - backend_ctx->q2_k_mv_nsg /= 2; - } - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_general - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X) { - CL_gemv_compile_opts += " -DGGML_CL_A6X_CONSTFOLD_FIX"; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src_CL_gemv_general { - #include "gemv_noshuffle_q4_0_f32.cl.h" - }; -#else - const std::string kernel_src_CL_gemv_general = read_file("gemv_noshuffle_q4_0_f32.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_0_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32_mc3", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle - { - // Gemv 2048, 16384 - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DLINE_STRIDE_A=2048 " - " -DBLOCK_STRIDE_A=16384 " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src_CL_gemv { - #include "gemv_noshuffle_q4_0_f32_spec.cl.h" - }; -#else - const std::string kernel_src_CL_gemv = read_file("gemv_noshuffle_q4_0_f32_spec.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_0_f32_4096_1_4096 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - - // Gemv 2048, 16384 - CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DLINE_STRIDE_A=2048 " - " -DBLOCK_STRIDE_A=16384 " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - - prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_0_f32_4096_1_11008 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - - // Gemv 5504, 44032 - CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DLINE_STRIDE_A=5504 " - " -DBLOCK_STRIDE_A=44032 " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - - prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_0_f32_11008_1_4096 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - - // Gemv 16000, 128000 - CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DLINE_STRIDE_A=16000 " - " -DBLOCK_STRIDE_A=128000 " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); - - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - - prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32000_1_4096 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mat_Ab_Bi_8x4 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src_CL_gemm { - #include "gemm_noshuffle_q4_0_f32.cl.h" - }; -#else - const std::string kernel_src_CL_gemm = read_file("gemm_noshuffle_q4_0_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemm.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans = nullptr; - backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin = nullptr; - { - { - std::string opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q4_0_f32_32b_trans.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q4_0_f32_32b_trans.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans = - clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32_32b_trans", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - if (use_adreno_bin_kernels(backend_ctx)) { - size_t bin_size = 0; - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_0_f32_32b_trans_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_0_f32_32b_trans_ila_a7", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_noshuffle_q4_1_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q4_1_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q4_1_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_1_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_1_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q4_1_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q4_1_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q4_1_f32.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_1_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_1_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_1_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_1_f32_mc3", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q5_0_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q5_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q5_0_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q5_0_q8_1_dp4a (dp4a dense q5_0 prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q5_0_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q5_0_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_q8_1_dp4a", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q5_0_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q5_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q5_0_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q5_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q5_1_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q5_1_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q5_1_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_1_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_1_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q5_1_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q5_1_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q5_1_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q5_1_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_1_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq4_nl_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq4_nl_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq4_nl_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq4_nl_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_nl_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_iq4_nl_q8_1_dp4a (dp4a dense IQ4_NL prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_iq4_nl_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_iq4_nl_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q4_0_q8_1_dp4a (dp4a dense q4_0 prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q4_0_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q4_0_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_q8_1_dp4a", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_iq4_nl_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_iq4_nl_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_iq4_nl_f32.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_iq4_nl_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_iq4_nl_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // mul_mm_q8_0_f32_8x4 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q8_0_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q8_0_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q8_0_f32_bin - { - size_t bin_size = 0; - backend_ctx->kernel_gemm_noshuffle_q8_0_f32_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q8_0_f32_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_f32_bin = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q8_0_f32_32b_trans_ila_a7", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - } - } - - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemv_noshuffle_general_q8_0_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src_CL_gemv_general { - #include "gemv_noshuffle_q8_0_f32.cl.h" - }; -#else - const std::string kernel_src_CL_gemv_general = read_file("gemv_noshuffle_q8_0_f32.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q8_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q8_0_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q8_0_f32_splitk = clCreateKernel(prog, "kernel_gemv_noshuffle_q8_0_f32_splitk", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q8_0_f32_mc = clCreateKernel(prog, "kernel_gemv_noshuffle_q8_0_f32_mc", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q4_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q4_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q4_k_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_r1 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_r1", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_kimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_kimg", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_cok = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_cok", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q4_k_q8_1_dp4a (dp4a dense prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q4_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q4_k_q8_1_dp4a.cl"); -#endif - // X1 uses a smaller N tile to reduce local memory and register use. - int tile_n = (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E) ? 8 : 32; - if (const char * e = getenv("GGML_OPENCL_Q4K_DP4A_TS")) { tile_n = atoi(e); } - GGML_ASSERT(tile_n >= 4 && tile_n <= 64 && tile_n % 4 == 0); - backend_ctx->tile_n_dp4a_q4_k = tile_n; - std::string dp4a_opts = compile_opts + " -DTILESIZE_N=" + std::to_string(tile_n); - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), dp4a_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - - // Compile a smaller N tile to avoid unused columns in small batches. - int tile_n_narrow = MIN(tile_n, 16); - if (const char * e = getenv("GGML_OPENCL_Q4_K_DP4A_TS_NARROW")) { tile_n_narrow = atoi(e); } - GGML_ASSERT(tile_n_narrow >= 4 && tile_n_narrow <= 64 && tile_n_narrow % 4 == 0); - if (const char * e = getenv("GGML_OPENCL_Q4_K_DP4A_NARROW_MAX")) { - backend_ctx->max_n_dp4a_narrow_q4_k = atoi(e); - } - backend_ctx->tile_n_dp4a_narrow_q4_k = tile_n_narrow; - if (tile_n_narrow != tile_n) { - std::string narrow_opts = compile_opts + " -DTILESIZE_N=" + std::to_string(tile_n_narrow); - cl_program narrow_prog = build_program_from_source(backend_ctx, kernel_src.c_str(), narrow_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow = clCreateKernel(narrow_prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow_wimg = clCreateKernel(narrow_prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg", &err), err)); - CL_CHECK(clReleaseProgram(narrow_prog)); - } - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q8_0_q8_1_dp4a (dp4a dense q8_0 prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q8_0_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q8_0_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q5_k_q8_1_dp4a (dp4a dense prefill GEMM for q5_K) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q5_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q5_k_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_q8_1_dp4a", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q6_k_q8_1_dp4a (dp4a dense prefill GEMM for q6_K ffn_down/output) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q6_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q6_k_q8_1_dp4a.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_q8_1_dp4a", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // quant_a_q8_1 (plain activation q8_1 pre-pass for the dense dp4a GEMM) - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "quant_a_q8_1.cl.h" - }; -#else - const std::string kernel_src = read_file("quant_a_q8_1.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_quant_a_q8_1 = clCreateKernel(prog, "kernel_quant_a_q8_1", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q4_k_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X) { - CL_gemv_compile_opts += " -DGGML_CL_A6X_CONSTFOLD_FIX"; - } - // dequant-once-per-block mc3 verify GEMV - if (getenv("GGML_OPENCL_Q4_K_MC3_DQ")) { - CL_gemv_compile_opts += " -DQ4K_MC3_DEQUANT_ONCE "; - } - // LM-staged dequant mc3 verify GEMV, stages the dequantized - // q4_K weights in __local instead of regs - if (getenv("GGML_OPENCL_Q4_K_MC3_LDS")) { - CL_gemv_compile_opts += " -DQ4K_MC3_DEQUANT_LDS "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q4_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_k_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_k_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_mc3", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_k_f32_splitk = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_splitk", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_splitk_reduce_f32 = clCreateKernel(prog, "kernel_gemv_splitk_reduce_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_k_f32_glu = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_glu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q4_k_f32_o4 — 4-output-per-WI variant for the long-vocab - // q4_K lm_head/embed GEMV (shares one activation read across 4 output rows). - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q4_k_f32_o4.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32_o4.cl"); -#endif - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - cl_program prog = build_program_from_source( - backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_k_f32_o4 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_o4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q4_k_f32_tiled — tiled-wide canonical layout, default ON - // (opt out: GGML_OPENCL_Q4K_GEMV_TILED=0; separate convert + GEMV; weights via __global). - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q4_k_f32_tiled.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32_tiled.cl"); -#endif - std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_k_f32_tiled = - clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_tiled", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q4_K_f32_tiled_dp4a - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q4_K_f32_tiled_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q4_K_f32_tiled_dp4a.cl"); -#endif - std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a = - clCreateKernel(prog, "kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - backend_ctx->kernel_gemv_noshuffle_q4_k_f32_32b_trans = nullptr; - backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin = nullptr; - { - if (backend_ctx->has_vector_subgroup_broadcast) { - std::string opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q4_k_f32_32b_trans.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32_32b_trans.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q4_k_f32_32b_trans = - clCreateKernel(prog, "gemv_noshuffle_q4_k_f32_32b_trans", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - if (use_adreno_bin_kernels(backend_ctx)) { - size_t bin_size = 0; - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_k_f32_32b_trans_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_k_f32_32b_trans_ila_a7", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - } - } - - backend_ctx->kernel_gemv_noshuffle_q6_k_f32_32b_trans = nullptr; - backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin = nullptr; - { - if (backend_ctx->has_vector_subgroup_broadcast) { - std::string opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q6_k_f32_32b_trans.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32_32b_trans.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q6_k_f32_32b_trans = - clCreateKernel(prog, "kernel_gemv_noshuffle_q6_k_f32_32b_trans", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - if (use_adreno_bin_kernels(backend_ctx)) { - size_t bin_size = 0; - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q6_k_f32_32b_trans_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q6_k_f32_32b_trans_ila_a7", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - } - } - - backend_ctx->kernel_gemv_noshuffle_q5_k_f32_32b_trans = nullptr; - backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin = nullptr; - backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin = nullptr; - { - if (backend_ctx->has_vector_subgroup_broadcast) { - std::string opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -DSIMDGROUP_WIDTH=" + - std::to_string(backend_ctx->adreno_wave_size); -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q5_k_f32_32b_trans.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q5_k_f32_32b_trans.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q5_k_f32_32b_trans = - clCreateKernel(prog, "gemv_noshuffle_q5_k_f32_32b_trans", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - if (use_adreno_bin_kernels(backend_ctx)) { - size_t bin_size = 0; - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q5_k_f32_32b_trans_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q5_k_f32_32b_trans_ila_a7", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - - kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program bin_prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin = - clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8", &err), err)); - CL_CHECK(clReleaseProgram(bin_prog)); - GGML_LOG_CONT("."); - } - } - } - - std::string CL_moe_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable " - " -cl-fast-relaxed-math"; - - // gemv_moe_q4_1_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_q4_1_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_q4_1_f32_ns.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_q4_1_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q4_1_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_1_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_1_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_1_f32_ns.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_1_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q4_1_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_1_f32_ns_bin - { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_1_f32_ns_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_1_f32_ns_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_1_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_1_f32_ns_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemv_moe_mxfp4_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_mxfp4_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_mxfp4_f32.cl"); -#endif - backend_ctx->program_gemv_moe_mxfp4_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_mxfp4_f32 = clCreateKernel(backend_ctx->program_gemv_moe_mxfp4_f32, "kernel_gemv_moe_mxfp4_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // gemm_moe_mxfp4_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_mxfp4_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_mxfp4_f32.cl"); -#endif - backend_ctx->program_gemm_moe_mxfp4_f32 = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_f32 = clCreateKernel(backend_ctx->program_gemm_moe_mxfp4_f32, "kernel_gemm_moe_mxfp4_f32", &err), err)); - GGML_LOG_CONT("."); - } - - // gemv_moe_q4_0_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_q4_0_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_q4_0_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_q4_0_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q4_0_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_0_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_0_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_0_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q4_0_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_0_f32_ns_bin - { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_0_f32_ns_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_f32_ns_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_f32_ns_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q8_0_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q8_0_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q8_0_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q8_0_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q8_0_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_moe_q5_0_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_q5_0_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_q5_0_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_q5_0_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q5_0_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q5_0_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q5_0_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q5_0_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_0_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q5_0_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_moe_q5_1_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_q5_1_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_q5_1_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_q5_1_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q5_1_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q5_1_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q5_1_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q5_1_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_1_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q5_1_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_moe_q4_k_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_q4_k_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_q4_k_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_q4_k_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q4_k_f32_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_moe_q4_k_f32_ns_wimg = clCreateKernel(prog, "kernel_gemv_moe_q4_k_f32_ns_wimg", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_k_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_k_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_k_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q4_k_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_k_f32_ns_bin - { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_k_f32_ns_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_f32_ns_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_f32_ns_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q4_k_q8_1_dp4a (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_k_q8_1_dp4a.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_k_q8_1_dp4a_bin (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_q8_1_dp4a_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_mxfp4_q8_1_dp4a (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_mxfp4_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_mxfp4_q8_1_dp4a.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_mxfp4_q8_1_dp4a_bin (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_mxfp4_q8_1_dp4a_ldck_bin (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila_ldck", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila_ldck", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_mxfp4_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q4_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q4_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_1_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_1_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q5_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_0_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_0_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q5_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_1_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_1_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q4_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q5_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_k_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_k_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q6_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_q8_1_dp4a_ila_malu", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a_ila_malu", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q4_0_q8_1_dp4a (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q4_0_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q4_0_q8_1_dp4a.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q4_0_q8_1_dp4a_bin (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_q8_1_dp4a_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q8_1_dp4a (generic dp4a MoE GEMM; MOE_QT=80 -> q8_0 expert variant) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q8_1_dp4a.cl"); -#endif - const std::string opts80 = CL_moe_compile_opts + " -DMOE_QT=80"; - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), opts80.c_str()); - CL_CHECK((backend_ctx->kernel_gemm_moe_q8_1_dp4a_q80 = clCreateKernel(prog, "kernel_gemm_moe_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - - const std::string opts50 = CL_moe_compile_opts + " -DMOE_QT=50"; - cl_program prog50 = - build_program_from_source(backend_ctx, kernel_src.c_str(), opts50.c_str()); - CL_CHECK((backend_ctx->kernel_gemm_moe_q8_1_dp4a_q50 = clCreateKernel(prog50, "kernel_gemm_moe_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog50)); - - const std::string opts5 = CL_moe_compile_opts + " -DMOE_QT=5"; - cl_program prog5 = - build_program_from_source(backend_ctx, kernel_src.c_str(), opts5.c_str()); - CL_CHECK((backend_ctx->kernel_gemm_moe_q8_1_dp4a_q5k = clCreateKernel(prog5, "kernel_gemm_moe_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog5)); - GGML_LOG_CONT("."); - } - - // moe_reorder_quant_a_q8_1 (fused reorder + q8_1 quant) - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "moe_reorder_quant_a_q8_1.cl.h" - }; -#else - const std::string kernel_src = read_file("moe_reorder_quant_a_q8_1.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_moe_reorder_quant_a_q8_1 = clCreateKernel(prog, "kernel_moe_reorder_quant_a_q8_1", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // transpose_activation_q8 (per-tile transpose of q8_1 activations for the ldck dp4a GEMM) - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "transpose_activation_q8.cl.h" - }; -#else - const std::string kernel_src = read_file("transpose_activation_q8.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_transpose_activation_q8 = clCreateKernel(prog, "kernel_transpose_activation_q8", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_moe_q5_k_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_q5_k_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_q5_k_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_q5_k_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q5_k_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q5_k_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q5_k_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q5_k_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q5_k_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q5_k_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_moe_q6_k_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_q6_k_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_q6_k_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_q6_k_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q6_k_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q6_k_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q6_k_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q6_k_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q6_k_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q6_k_f32_ns_bin - { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q6_k_f32_ns_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_f32_ns_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_f32_ns_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemm_moe_q6_k_q8_1_dp4a (dp4a q6_K MoE prefill GEMM) - if (backend_ctx->has_integer_dot) { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_q6_k_q8_1_dp4a.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_q6_k_q8_1_dp4a.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_q6_k_q8_1_dp4a_bin (dp4a prefill GEMM) - if (backend_ctx->has_integer_dot) { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_q8_1_dp4a_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // gemv_moe_mxfp4_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_moe_mxfp4_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_moe_mxfp4_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_moe_mxfp4_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_mxfp4_f32_ns", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_moe_mxfp4_f32_ns_wimg = clCreateKernel(prog, "kernel_gemv_moe_mxfp4_f32_ns_wimg", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_mxfp4_f32_ns - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_moe_mxfp4_f32_ns.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_moe_mxfp4_f32_ns.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_f32_ns", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_moe_mxfp4_f32_ns_bin - { - size_t bin_size = 0; - backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_f32_ns_ila", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_f32_ns_ila", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - - // moe_reorder_b - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "moe_reorder_b.cl.h" - }; -#else - const std::string kernel_src = read_file("moe_reorder_b.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_moe_reorder_b = clCreateKernel(prog, "kernel_moe_reorder_b", &err), err)); - CL_CHECK((backend_ctx->kernel_moe_reorder_b_f16 = clCreateKernel(prog, "kernel_moe_reorder_b_f16", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q6_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q6_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32.cl"); -#endif - - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; - } - - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q6_K_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q6_K_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_mc3", &err), err)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q6_k_f32_o4 — 4-output-per-WI variant, opt-in via - // GGML_OPENCL_Q6K_GEMV_O4=1 (~3x fewer dispatches on long-vocab lm_head). - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q6_k_f32_o4.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32_o4.cl"); -#endif - - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; - } - - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q6_K_f32_o4 = clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_o4", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - - // Global-read variant: weights read from __global coalesced instead of - // image1d_buffer (the texture cache caps the streaming lm_head read - // bandwidth). Opt-in via GGML_OPENCL_Q6K_GEMV_O4_GLOBAL. - cl_program prog_g = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts + " -DQ6K_O4_GLOBAL"); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q6_K_f32_o4_global = - clCreateKernel(prog_g, "kernel_gemv_noshuffle_q6_K_f32_o4_global", &err), err)); - CL_CHECK(clReleaseProgram(prog_g)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q6_k_f32_tiled — tiled-wide canonical layout, default ON - // (opt out: GGML_OPENCL_Q6K_GEMV_TILED=0; separate convert + GEMV; weights via __global). - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q6_k_f32_tiled.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32_tiled.cl"); -#endif - std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q6_K_f32_tiled = - clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_tiled", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q6_K_f32_tiled_mc3 = - clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_tiled_mc3", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q6_k_f32_tiled — batched (N>1) GEMM over the same tiled-wide - // canonical layout, so batched lm_head/embed stays correct + on GPU. - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q6_k_f32_tiled.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32_tiled.cl"); -#endif - std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_K_f32_tiled = - clCreateKernel(prog, "kernel_gemm_noshuffle_q6_K_f32_tiled", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q6_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q6_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_K_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_K_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q6_K_f32_cok = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_K_f32_cok", &err), err)); - GGML_LOG_CONT("."); - } - - // gemv_noshuffle_q5_k_f32 - { - std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + - " -cl-mad-enable "; - if (backend_ctx->has_vector_subgroup_broadcast) { - CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; - } - -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemv_noshuffle_q5_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemv_noshuffle_q5_k_f32.cl"); -#endif - - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); - - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q5_k_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_k_f32", &err), err)); - CL_CHECK((backend_ctx->kernel_gemv_noshuffle_q5_k_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_k_f32_mc3", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // gemm_noshuffle_q5_k_f32 - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "gemm_noshuffle_q5_k_f32.cl.h" - }; -#else - const std::string kernel_src = read_file("gemm_noshuffle_q5_k_f32.cl"); -#endif - cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - CL_CHECK((backend_ctx->kernel_gemm_noshuffle_q5_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_f32", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - - // repack - { -#ifdef GGML_OPENCL_EMBED_KERNELS - const std::string kernel_src { - #include "flash_attn_repack.cl.h" - }; -#else - const std::string kernel_src = read_file("flash_attn_repack.cl"); -#endif - cl_program prog = - build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); - - CL_CHECK((backend_ctx->fa.kernel_repack_q_for_wmm = clCreateKernel(prog, "kernel_repack_q_for_wmm", &err), err)); - CL_CHECK((backend_ctx->fa.kernel_repack_k_for_wmm = clCreateKernel(prog, "kernel_repack_k_for_wmm", &err), err)); - CL_CHECK((backend_ctx->fa.kernel_repack_v_for_wmm = clCreateKernel(prog, "kernel_repack_v_for_wmm", &err), err)); - CL_CHECK((backend_ctx->fa.kernel_repack_mask_for_wmm = clCreateKernel(prog, "kernel_repack_mask_for_wmm", &err), err)); - GGML_LOG_CONT("."); - } - - // kernel_flash_attn_f32_f16_bin - { - size_t bin_size = 0; - backend_ctx->fa.kernel_flash_attn_f32_f16_bin = nullptr; - - if (use_adreno_bin_kernels(backend_ctx)) { - const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("flash_attn_f32_f16_wmm", &bin_size); - if (kernel_bin && bin_size > 0) { - cl_program prog = - build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); - - CL_CHECK((backend_ctx->fa.kernel_flash_attn_f32_f16_bin = clCreateKernel(prog, "flash_attn_f32_f16", &err), err)); - CL_CHECK(clReleaseProgram(prog)); - GGML_LOG_CONT("."); - } - } - } - load_cl_kernels_gemm_coopk(backend_ctx); - load_cl_kernels_coopmat(backend_ctx); -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - GGML_LOG_CONT("\n"); - backend_ctx->kernels_loaded = true; -} - -static ggml_backend_opencl_context * ggml_cl_init(ggml_backend_dev_t dev); -static bool ggml_opencl_is_device_supported(ggml_backend_dev_t dev); - -// FA per-(dk,dv) tile tuning table + GGML_OPENCL_FA_TUNE override parsing. -#include "fa_tune.h" - -// FA variant key for the per-(dk,dv,variant) lazy compile cache. -// Kernel built on first dispatch to reduce kernel loading time. -// NB - a warmup run is recommended to get all necessary FA variants compiled -// before actual runs. -enum ggml_opencl_fa_variant { - FA_VARIANT_PRE = 0, // prepass kernels (kv_pad, mask_pad, blk) - FA_VARIANT_F16 = 1, - FA_VARIANT_F32 = 2, - FA_VARIANT_F32_F16 = 3, - FA_VARIANT_Q8_0 = 4, - FA_VARIANT_Q4_0 = 5, - FA_VARIANT_F32_F16_SPLIT = 6, - FA_VARIANT_Q8_0_SPLIT = 7, - FA_VARIANT_Q4_0_SPLIT = 8, -}; - -static std::string ggml_opencl_fa_kernel_src(ggml_opencl_fa_variant v) { -#ifdef GGML_OPENCL_EMBED_KERNELS - switch (v) { - case FA_VARIANT_F16: - return std::string{ - #include "flash_attn_f16.cl.h" - }; - case FA_VARIANT_F32: - return std::string{ - #include "flash_attn_f32.cl.h" - }; - case FA_VARIANT_F32_F16: - case FA_VARIANT_F32_F16_SPLIT: - return std::string{ - #include "flash_attn_f32_f16.cl.h" - }; - case FA_VARIANT_PRE: - return std::string{ - #include "flash_attn_pre_f16.cl.h" - }; - case FA_VARIANT_Q8_0: - case FA_VARIANT_Q8_0_SPLIT: - return std::string{ - #include "flash_attn_f32_q8_0.cl.h" - }; - case FA_VARIANT_Q4_0: - case FA_VARIANT_Q4_0_SPLIT: - return std::string{ - #include "flash_attn_f32_q4_0.cl.h" - }; - } - return {}; -#else - switch (v) { - case FA_VARIANT_F16: return read_file("flash_attn_f16.cl"); - case FA_VARIANT_F32: return read_file("flash_attn_f32.cl"); - case FA_VARIANT_F32_F16: - case FA_VARIANT_F32_F16_SPLIT: return read_file("flash_attn_f32_f16.cl"); - case FA_VARIANT_PRE: return read_file("flash_attn_pre_f16.cl"); - case FA_VARIANT_Q8_0: - case FA_VARIANT_Q8_0_SPLIT: return read_file("flash_attn_f32_q8_0.cl"); - case FA_VARIANT_Q4_0: - case FA_VARIANT_Q4_0_SPLIT: return read_file("flash_attn_f32_q4_0.cl"); - } - return {}; -#endif -} - -static std::string ggml_opencl_fa_compile_opts(ggml_backend_opencl_context * backend_ctx, - const ggml_opencl_fa_dim * cfg, - ggml_opencl_fa_variant variant) { - std::string opts = backend_ctx->kernel_compile_opts + - " -D DK=" + std::to_string(cfg->dk) + - " -D DV=" + std::to_string(cfg->dv) + - " -D BLOCK_M=" + std::to_string(cfg->bm) + - " -D BLOCK_N=" + std::to_string(cfg->bn); - - if (backend_ctx->gpu_family == INTEL) { - opts += " -D FA_SG=32"; - } - - const bool is_split = variant == FA_VARIANT_F32_F16_SPLIT || - variant == FA_VARIANT_Q8_0_SPLIT || - variant == FA_VARIANT_Q4_0_SPLIT; - if (is_split) { - opts += " -D N_SPLIT=" + std::to_string(cfg->n_split); - } - // Shuffle define for the split tile paths AND the cluster-parallel decode - // kernel (q1_vec_mq_split_c8) in the plain F32_F16 program. Without it the - // c8 kernel is compiled out (HAS_SUBGROUP_SHUFFLE guard) and dispatch - // falls back to the baseline mq_split. - if ((is_split || variant == FA_VARIANT_F32_F16) && backend_ctx->has_subgroup_shuffle) { - opts += backend_ctx->has_qcom_subgroup_shuffle - ? " -D cl_qcom_subgroup_shuffle=1" - : " -D cl_khr_subgroup_shuffle=1"; - } - // X1E drops the explicit sub-group size pin on the c8 kernels, compiler - // routes the fp16-heavy kernel to a slow variant with explicit subgroup size - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E) { - opts += " -D FA_C8_NO_SG_PIN"; - } - // Transposed K tile in local memory: the KV rows the QK loop walks together become - // adjacent, so a group of them is ONE 128-bit local read instead of several narrow - // ones. The QK loop is LDS-read-issue-bound (a wrong-math probe that kept every FMA/dp4a - // but removed the LDS reads ran the kernel ~40% faster), so this is worth up to +26% on - // fa=1 prefill. Output is bit-identical -- only the layout moves. - // - // DK <= 128 only. At DK=256 (gemma-3-4b) it measures 1-2% NEGATIVE and reproduces across - // rounds; padding the row stride does not recover it, so the cause is not a simple bank - // conflict and the wider tile does not want this layout. - // - // Default on within that gate; GGML_OPENCL_FA_K_LDS_T=0 restores the row-major tile. - { - const char * e = getenv("GGML_OPENCL_FA_K_LDS_T"); - if ((e == nullptr || e[0] != '0') && cfg->dk <= 128) { - opts += " -D FA_K_LDS_T"; - } - } - return opts; -} - -// only register when the kernel's required dispatch workgroup size is within -// the limit of the device's maximum workgroup size -static bool ggml_opencl_fa_kernel_fits_wg(ggml_backend_opencl_context * backend_ctx, - cl_kernel kernel, size_t required_wg, - const char * name, int dk, int dv) { - if (kernel == NULL) { return false; } - const size_t dev_max = backend_ctx->max_workgroup_size; - if (dev_max < required_wg) { - GGML_LOG_INFO("ggml_opencl: %s DK=%d DV=%d requires WG %zu > device max %zu; skipping registration (will fall back)\n", - name, dk, dv, required_wg, dev_max); - return false; - } - size_t kwg = 0; - cl_int err = clGetKernelWorkGroupInfo(kernel, backend_ctx->device, - CL_KERNEL_WORK_GROUP_SIZE, - sizeof(kwg), &kwg, NULL); - if (err != CL_SUCCESS) { - GGML_LOG_INFO("ggml_opencl: clGetKernelWorkGroupInfo failed for %s DK=%d DV=%d (err=%d); skipping registration\n", - name, dk, dv, err); - return false; - } - if (kwg < required_wg) { - GGML_LOG_INFO("ggml_opencl: %s DK=%d DV=%d per-kernel max %zu < required %zu; skipping registration (will fall back)\n", - name, dk, dv, kwg, required_wg); - return false; - } - return true; -} - -// Log private memory for an FA kernel. Enable via `GGML_OPENCL_FA_LOG_SPILL=1`. -// On Adreno non-zero private_mem means spilling to global memory due to resource -// constraint and usually causes performance degradation. -// (per-work-item, no cache locality) — a strong signal to pick a config -// with smaller per-thread state (e.g. larger N_SPLIT). -static void ggml_opencl_log_fa_kernel_spill(ggml_backend_opencl_context * backend_ctx, - cl_kernel kernel, const char * name, int dk, int dv) { - static const bool enabled = []{ - const char * e = std::getenv("GGML_OPENCL_FA_LOG_SPILL"); - return e && e[0] && e[0] != '0'; - }(); - - if (!enabled || kernel == nullptr) { - return; - } - - cl_ulong priv_mem = 0; - if (clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_PRIVATE_MEM_SIZE, - sizeof(priv_mem), &priv_mem, NULL) == CL_SUCCESS) { - const char * tag = priv_mem > 0 ? "SPILL" : "ok"; - GGML_LOG_INFO("ggml_opencl: [%s] %s DK=%d DV=%d private_mem=%llu bytes\n", - tag, name, dk, dv, (unsigned long long) priv_mem); - } -} - -static void ggml_opencl_ensure_fa_pre_kernels(ggml_backend_opencl_context * backend_ctx, int dk, int dv) { - const std::pair dk_dv = {dk, dv}; - - const ggml_opencl_fa_dim * cfg = nullptr; - for (const auto & d : g_opencl_fa_dims) { - if (d.dk == dk && d.dv == dv) { - cfg = &d; break; - } - } - - if (cfg == nullptr) { - GGML_ABORT("ggml_opencl: no flash_attn config for DK=%d DV=%d", dk, dv); - } - - // BM-tile metadata is consumed by the prefill dispatch (n_q_blocks / wg - // sizing) regardless of whether the prepass kernels are needed for this - // n_kv — set it unconditionally - backend_ctx->fa.f32_f16_bm[{dk, dv}] = cfg->bm; - backend_ctx->fa.f32_f16_bn[{dk, dv}] = cfg->bn; - backend_ctx->fa.f32_f16_wg_size[{dk, dv}] = cfg->bm; - backend_ctx->fa.bm[{dk, dv}] = cfg->bm; - backend_ctx->fa.bn[{dk, dv}] = cfg->bn; - - if (backend_ctx->fa.kv_pad_f16.count(dk_dv) > 0) { return; } - - GGML_LOG_INFO("ggml_opencl: lazy-compiling flash_attn prepass for DK=%d DV=%d\n", dk, dv); - cl_int err; - const std::string src = ggml_opencl_fa_kernel_src(FA_VARIANT_PRE); - const std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, FA_VARIANT_PRE); - // retry when kernel compile fails - cl_program prog_pre_f16 = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts, - /*fatal=*/false, "fa prepass f16", backend_ctx->queue); - if (!prog_pre_f16) { return; } - cl_kernel k_kv_pad_f16 = clCreateKernel(prog_pre_f16, "flash_attn_kv_pad_f16", &err); - if (err != CL_SUCCESS) { clReleaseProgram(prog_pre_f16); return; } - cl_kernel k_mask_pad_f16 = clCreateKernel(prog_pre_f16, "flash_attn_mask_pad_f16", &err); - if (err != CL_SUCCESS) { clReleaseKernel(k_kv_pad_f16); clReleaseProgram(prog_pre_f16); return; } - cl_kernel k_blk_f16 = clCreateKernel(prog_pre_f16, "flash_attn_blk_f16", &err); - if (err != CL_SUCCESS) { clReleaseKernel(k_kv_pad_f16); clReleaseKernel(k_mask_pad_f16); clReleaseProgram(prog_pre_f16); return; } - backend_ctx->fa.kv_pad_f16[{dk, dv}] = k_kv_pad_f16; - backend_ctx->fa.mask_pad_f16[{dk, dv}] = k_mask_pad_f16; - backend_ctx->fa.blk_f16[{dk, dv}] = k_blk_f16; - // optional, the decomposed prefill checks for it and falls back to the fused tile - cl_kernel k_v_transpose_f16 = clCreateKernel(prog_pre_f16, "flash_attn_v_transpose_f16", &err); - if (err == CL_SUCCESS) { - backend_ctx->fa.v_transpose_f16[{dk, dv}] = k_v_transpose_f16; - } - if (backend_ctx->kernel_fa_v_transpose_q8 == nullptr && backend_ctx->has_integer_dot) { - backend_ctx->kernel_fa_v_transpose_q8 = clCreateKernel(prog_pre_f16, "flash_attn_v_transpose_q8", &err); - if (err != CL_SUCCESS) { - backend_ctx->kernel_fa_v_transpose_q8 = nullptr; - } - } - clReleaseProgram(prog_pre_f16); -} - -static bool ggml_opencl_ensure_fa_f32_f16_vec_512(ggml_backend_opencl_context * backend_ctx) { - const std::pair key = {512, 512}; - auto & fa = backend_ctx->fa; - if (fa.f32_f16_q1_vec.count(key) > 0) { - return true; - } - if (fa.f32_f16_vec_512_attempted || backend_ctx->kernel_compile_opts.empty()) { - return false; - } - fa.f32_f16_vec_512_attempted = true; - - const ggml_opencl_fa_dim * cfg = nullptr; - for (const auto & d : g_opencl_fa_dims) { - if (d.dk == 512 && d.dv == 512) { - cfg = &d; - break; - } - } - if (cfg == nullptr) { - return false; - } - - // Compile only vec decode and merge to stay within the Adreno compiler's memory limit. - const std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, FA_VARIANT_F32_F16) + - " -D FA_DECODE_ONLY -D FA_VEC_ONLY"; - cl_program prog = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, - ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16).c_str(), opts, - /*fatal=*/false, "fa f32_f16 decode512 vec", backend_ctx->queue); - if (!prog) { - return false; - } - cl_int err; - cl_kernel vec = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec", &err); - if (err != CL_SUCCESS) { - clReleaseProgram(prog); - return false; - } - cl_kernel merge = clCreateKernel(prog, "flash_attn_f32_merge", &err); - clReleaseProgram(prog); - if (err != CL_SUCCESS) { - clReleaseKernel(vec); - return false; - } - if (!ggml_opencl_fa_kernel_fits_wg(backend_ctx, vec, 256, "flash_attn_f32_f16_q1_vec", 512, 512) || - !ggml_opencl_fa_kernel_fits_wg(backend_ctx, merge, 128, "flash_attn_f32_merge", 512, 512)) { - clReleaseKernel(vec); - clReleaseKernel(merge); - return false; - } - fa.f32_f16_q1_vec[key] = vec; - if (fa.f32_merge.count(key) > 0) { - clReleaseKernel(merge); - } else { - fa.f32_merge[key] = merge; - } - return true; -} - -static void ggml_opencl_ensure_fa_f32_f16_mq_decode(ggml_backend_opencl_context * backend_ctx, int dk, int dv, int gqa) { - const std::tuple key = {dk, dv, gqa}; - auto & fa = backend_ctx->fa; - if (fa.f32_f16_mq_decode.count(key) > 0 || fa.f32_f16_mq_decode_attempted.count(key) > 0 || - backend_ctx->kernel_compile_opts.empty()) { - return; - } - if (gqa == 4 && dk != 128 && fa.f32_f16_q1_vec_mq_split.count({dk, dv}) > 0) { - fa.f32_f16_mq_decode[key] = fa.f32_f16_q1_vec_mq_split.at({dk, dv}); - fa.f32_f16_mq_decode_wg[key] = 256; - fa.f32_f16_mq_decode_hs[key] = 1; - return; - } - fa.f32_f16_mq_decode_attempted.insert(key); - const ggml_opencl_fa_dim * cfg = nullptr; - for (const auto & d : g_opencl_fa_dims) { - if (d.dk == dk && d.dv == dv) { - cfg = &d; - break; - } - } - if (cfg == nullptr) { - return; - } - - const bool cluster = dk == 64 || dk == 128; - const int head_sub = gqa == 16 ? (cluster ? 4 : 8) : - cluster ? 2 : (gqa == 8 ? (dk == 512 ? 4 : 2) : 1); - const int nsg_max = dk == 64 ? 1 : (dk == 128 || (gqa == 8 && dk == 256) ? 2 : 4); - const char * kernel_name = cluster ? "flash_attn_f32_f16_q1_vec_mq_split_c8" : "flash_attn_f32_f16_q1_vec_mq_split"; - const std::string src = ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16); - const std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, FA_VARIANT_F32_F16) + - " -D FA_MQ_ONLY -D MQ_GQA=" + std::to_string(gqa / head_sub) + - " -D FA_HEAD_SUB=" + std::to_string(head_sub) + - (cluster ? " -D MQ_NSG=" + std::to_string(nsg_max) + " -D FA_CL_C=16" : " -D FA_MQ_SPLIT_ONLY") + - (dk == 64 ? " -D FA_CL_MHRED -D FA_CL_MASK_BCAST" : (cluster && gqa == 16 ? " -D FA_CL_MHRED" : "")) + - (gqa == 8 && dk == 256 ? " -D FA_Q1_Q_REG" : ""); - for (int nsg = nsg_max; nsg >= 1; nsg /= 2) { - const size_t wg = 64 * nsg; - cl_program prog = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), - opts + " -D MQ_NSG_SPLIT=" + std::to_string(nsg), - /*fatal=*/false, "fa f32_f16 mq decode", backend_ctx->queue); - if (!prog) { - continue; - } - cl_int err; - cl_kernel kernel = clCreateKernel(prog, kernel_name, &err); - clReleaseProgram(prog); - if (err != CL_SUCCESS) { - continue; - } - if (!ggml_opencl_fa_kernel_fits_wg(backend_ctx, kernel, wg, kernel_name, dk, dv)) { - clReleaseKernel(kernel); - continue; - } - fa.f32_f16_mq_decode[key] = kernel; - fa.f32_f16_mq_decode_wg[key] = wg; - fa.f32_f16_mq_decode_hs[key] = head_sub; - return; - } -} - -// DK=512 prefill BM-tile -static bool ggml_opencl_ensure_fa_f32_f16_prefill_512(ggml_backend_opencl_context * backend_ctx, bool split) { - const int dk = 512, dv = 512; - const std::pair dk_dv = {dk, dv}; - auto & target = split ? backend_ctx->fa.f32_f16_split : backend_ctx->fa.f32_f16; - if (target.count(dk_dv) > 0) { return true; } - - static bool failed[2] = { false, false }; - if (failed[split ? 1 : 0]) { return false; } - - const ggml_opencl_fa_dim * cfg = nullptr; - for (const auto & d : g_opencl_fa_dims) { - if (d.dk == dk && d.dv == dv) { cfg = &d; break; } - } - if (cfg == nullptr) { failed[split ? 1 : 0] = true; return false; } - if (split && cfg->n_split <= 1) { failed[1] = true; return false; } - - const ggml_opencl_fa_variant variant = split ? FA_VARIANT_F32_F16_SPLIT : FA_VARIANT_F32_F16; - std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, variant) + " -D FA_PREFILL_ONLY"; - cl_program prog = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, - ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16).c_str(), opts, - /*fatal=*/false, split ? "fa f32_f16 prefill512 split" : "fa f32_f16 prefill512", - backend_ctx->queue); - if (!prog) { failed[split ? 1 : 0] = true; return false; } - - cl_int err; - cl_kernel k = clCreateKernel(prog, "flash_attn_f32_f16", &err); - if (err != CL_SUCCESS) { clReleaseProgram(prog); failed[split ? 1 : 0] = true; return false; } - target[dk_dv] = k; - if (split) { - backend_ctx->fa.f32_f16_split_wg_size[dk_dv] = cfg->bm * cfg->n_split; - backend_ctx->fa.f32_f16_split_nkv_threshold[dk_dv] = cfg->nkv_split_threshold; - } - ggml_opencl_log_fa_kernel_spill(backend_ctx, k, - split ? "flash_attn_f32_f16 (prefill512 split)" : "flash_attn_f32_f16 (prefill512)", dk, dv); - clReleaseProgram(prog); - - // determine whether to use the K-image variant of the split tile - static const char * pkimg_build_env = getenv("GGML_OPENCL_FA_PREFILL_K_IMG"); - const bool pkimg_build = (pkimg_build_env != NULL) && (pkimg_build_env[0] != '0'); - if (split && pkimg_build && backend_ctx->fa.f32_f16_split_k_img.count(dk_dv) == 0) { - std::string opts_img = ggml_opencl_fa_compile_opts(backend_ctx, cfg, variant) + - " -D FA_PREFILL_ONLY -D FA_K_IMG -D FA_TILE_NAME=flash_attn_f32_f16_k_img"; - cl_program prog_img = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, - ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16).c_str(), opts_img, - /*fatal=*/false, "fa f32_f16 prefill512 split k_img", backend_ctx->queue); - if (prog_img) { - cl_int err_img; - cl_kernel k_img = clCreateKernel(prog_img, "flash_attn_f32_f16_k_img", &err_img); - if (err_img == CL_SUCCESS) { - backend_ctx->fa.f32_f16_split_k_img[dk_dv] = k_img; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_img, - "flash_attn_f32_f16 (prefill512 split k_img)", dk, dv); - } - clReleaseProgram(prog_img); - } - } - return true; -} - -// Compile one (variant, dk, dv); memoised. false = compiler rejected. -static bool ggml_opencl_ensure_fa_variant(ggml_backend_opencl_context * backend_ctx, int dk, int dv, ggml_opencl_fa_variant variant) { - const std::pair dk_dv = {dk, dv}; - - const ggml_opencl_fa_dim * cfg = nullptr; - for (const auto & d : g_opencl_fa_dims) { - if (d.dk == dk && d.dv == dv) { - cfg = &d; break; - } - } - if (cfg == nullptr) { - return false; - } - - // if a variant has already been compiled - switch (variant) { - case FA_VARIANT_F16: { - if (backend_ctx->fa.f16.count(dk_dv)) { - return true; - } - break; - } - case FA_VARIANT_F32: { - if (backend_ctx->fa.f32.count(dk_dv)) { - return true; - } - break; - } - case FA_VARIANT_F32_F16: { - // The DK=512 decode-only program does not create the f32_f16 - // prefill kernel; check the q1 kernel instead so that repeated - // calls return a consistent result. - const bool decode_only = (dk == 512); - if (decode_only ? (backend_ctx->fa.f32_f16_q1.count(dk_dv) > 0) - : (backend_ctx->fa.f32_f16.count(dk_dv) > 0)) { - return true; - } - break; - } - case FA_VARIANT_Q8_0: { - if (backend_ctx->fa.f32_q8_0.count(dk_dv)) { - return true; - } - break; - } - case FA_VARIANT_Q4_0: { - if (backend_ctx->fa.f32_q4_0.count(dk_dv)) { - return true; - } - break; - } - case FA_VARIANT_F32_F16_SPLIT: { - if (backend_ctx->fa.f32_f16_split.count(dk_dv)) { - return true; - } - break; - } - case FA_VARIANT_Q8_0_SPLIT: { - if (backend_ctx->fa.f32_q8_0_split.count(dk_dv)) { - return true; - } - break; - } - case FA_VARIANT_Q4_0_SPLIT: { - if (backend_ctx->fa.f32_q4_0_split.count(dk_dv)) { - return true; - } - break; - } - case FA_VARIANT_PRE: { - ggml_opencl_ensure_fa_pre_kernels(backend_ctx, dk, dv); - return true; - } - } - - // not registered but attempted - meaning these kernels failed to compile - const auto attempt_key = std::make_pair(variant, dk_dv); - if (backend_ctx->fa.variant_attempted.count(attempt_key)) { - return false; - } - backend_ctx->fa.variant_attempted.insert(attempt_key); - - const bool is_split = variant == FA_VARIANT_F32_F16_SPLIT || - variant == FA_VARIANT_Q8_0_SPLIT || - variant == FA_VARIANT_Q4_0_SPLIT; - const bool is_quant = variant == FA_VARIANT_Q8_0 || variant == FA_VARIANT_Q8_0_SPLIT || - variant == FA_VARIANT_Q4_0 || variant == FA_VARIANT_Q4_0_SPLIT; - if (is_quant && (dk % 32 != 0 || dv % 32 != 0)) { - return false; - } - if (is_split && cfg->n_split <= 1) { - return false; - } - if ((variant == FA_VARIANT_Q8_0_SPLIT || variant == FA_VARIANT_Q4_0_SPLIT) && - ((dk / 32) % cfg->n_split != 0 || (dv / 4) % cfg->n_split != 0)) { - return false; - } - - const std::string src = ggml_opencl_fa_kernel_src(variant); - if (src.empty()) { return false; } - std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, variant); - - // bypass kernels for DK=512 - const bool fa_decode_only = (variant == FA_VARIANT_F32_F16 && dk == 512); - if (fa_decode_only) { - opts += " -D FA_DECODE_ONLY -D FA_DECODE_MINIMAL"; - } - - // c8 cluster width (GGML_OPENCL_FA_CL_C overrides): value = GQA4 cluster - // width (kernel default 8); the g8 programs use 2x the value (default 16). - // Wider clusters halve per-lane o_acc at the cost of position streams per - // subgroup - static const int fa_cl_c_env = []{ - const char * e = std::getenv("GGML_OPENCL_FA_CL_C"); - const int x = (e && e[0]) ? atoi(e) : 0; - return (x == 8 || x == 16 || x == 32) ? x : 0; // 0 = per-gen default - }(); - // X2E needs 16 to keep per-lane o_acc at 128B (the compiler spills the - // kernel-default width); X1E does not spill, but C=16 is still a measured - // +28-30% DK128-GQA4 decode win there (X1-85, kv 4096/8192), neutral on - // DK64 / GQA1 / quant-KV. - const int fa_cl_c_gqa4 = fa_cl_c_env ? fa_cl_c_env - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E ? 16 : 0); - const std::string opts_cl_c_gqa4 = fa_cl_c_gqa4 - ? " -D FA_CL_C=" + std::to_string(fa_cl_c_gqa4) : std::string(); - const std::string fa_cl_c_g8_val = std::to_string(fa_cl_c_gqa4 ? fa_cl_c_gqa4 * 2 : 16); - - const char * tag = nullptr; - switch (variant) { - case FA_VARIANT_F16: tag = "fa f16"; break; - case FA_VARIANT_F32: tag = "fa f32"; break; - case FA_VARIANT_F32_F16: tag = "fa f32_f16"; break; - case FA_VARIANT_Q8_0: tag = "fa q8_0"; break; - case FA_VARIANT_Q4_0: tag = "fa q4_0"; break; - case FA_VARIANT_F32_F16_SPLIT: tag = "fa f32_f16 split"; break; - case FA_VARIANT_Q8_0_SPLIT: tag = "fa q8_0 split"; break; - case FA_VARIANT_Q4_0_SPLIT: tag = "fa q4_0 split"; break; - default: break; - } - cl_program prog = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts + opts_cl_c_gqa4, - /*fatal=*/false, tag, backend_ctx->queue); - if (!prog) { return false; } - - cl_int err; - switch (variant) { - case FA_VARIANT_F16: { - cl_kernel k, kq1; - CL_CHECK((k = clCreateKernel(prog, "flash_attn_f16", &err), err)); - CL_CHECK((kq1 = clCreateKernel(prog, "flash_attn_f16_q1", &err), err)); - backend_ctx->fa.f16[{dk, dv}] = k; - backend_ctx->fa.f16_q1[{dk, dv}] = kq1; - break; - } - case FA_VARIANT_F32: { - cl_kernel k, kq1; - CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32", &err), err)); - CL_CHECK((kq1 = clCreateKernel(prog, "flash_attn_f32_q1", &err), err)); - backend_ctx->fa.f32[{dk, dv}] = k; - backend_ctx->fa.f32_q1[{dk, dv}] = kq1; - break; - } - case FA_VARIANT_F32_F16: { - cl_kernel kq1; - // BM-tile prefill kernel is excluded from the decode-only (DK=512) - if (!fa_decode_only) { - cl_kernel k; - CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_f16", &err), err)); - backend_ctx->fa.f32_f16[{dk, dv}] = k; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k, "flash_attn_f32_f16", dk, dv); - } - CL_CHECK((kq1 = clCreateKernel(prog, "flash_attn_f32_f16_q1", &err), err)); - backend_ctx->fa.f32_f16_q1[{dk, dv}] = kq1; - ggml_opencl_log_fa_kernel_spill(backend_ctx, kq1, "flash_attn_f32_f16_q1", dk, dv); - cl_kernel k_split = clCreateKernel(prog, "flash_attn_f32_f16_q1_split", &err); - if (err == CL_SUCCESS) { - backend_ctx->fa.f32_f16_q1_split[{dk, dv}] = k_split; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_split, "flash_attn_f32_f16_q1_split", dk, dv); - } - // q1_vec decode kernel (DV-split + subgroup reduce) - cl_kernel k_q1_vec = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec, 256, - "flash_attn_f32_f16_q1_vec", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec[{dk, dv}] = k_q1_vec; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec, "flash_attn_f32_f16_q1_vec", dk, dv); - } else { - clReleaseKernel(k_q1_vec); - } - } - // KV-head-coalesced vec for high-GQA small models - cl_kernel k_q1_vec_mq = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq, 256, - "flash_attn_f32_f16_q1_vec_mq", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq[{dk, dv}] = k_q1_vec_mq; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq, "flash_attn_f32_f16_q1_vec_mq", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq); - } - } - // KV-head-coalesced + flash-decoding split, reuses merge kernel - cl_kernel k_q1_vec_mq_split = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq_split", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split, 256, - "flash_attn_f32_f16_q1_vec_mq_split", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split[{dk, dv}] = k_q1_vec_mq_split; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split, "flash_attn_f32_f16_q1_vec_mq_split", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_split); - } - } - // K-image variant of MQ_GQA=4 split - cl_kernel k_q1_vec_mq_split_k_img = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq_split_k_img", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_k_img, 256, - "flash_attn_f32_f16_q1_vec_mq_split_k_img", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_k_img[{dk, dv}] = k_q1_vec_mq_split_k_img; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_k_img, "flash_attn_f32_f16_q1_vec_mq_split_k_img", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_split_k_img); - } - } - // Cluster-parallel decode variant - cl_kernel k_q1_vec_mq_split_c8 = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_c8, 256, - "flash_attn_f32_f16_q1_vec_mq_split_c8", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_c8[{dk, dv}] = k_q1_vec_mq_split_c8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_split_c8); - } - } - cl_kernel k_merge = clCreateKernel(prog, "flash_attn_f32_merge", &err); - if (err == CL_SUCCESS) { - backend_ctx->fa.f32_merge[{dk, dv}] = k_merge; - } - // local-tile decode variant - if (dk == 128 && dv == 128) { - cl_kernel k_lt = clCreateKernel(prog, "flash_attn_f32_f16_q1_local_tile", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_lt, 128, - "flash_attn_f32_f16_q1_local_tile", dk, dv)) { - backend_ctx->fa.f32_f16_q1_local_tile[{dk, dv}] = k_lt; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_lt, "flash_attn_f32_f16_q1_local_tile", dk, dv); - } else { - clReleaseKernel(k_lt); - } - } - // hybrid local-tile + MQ + FD-split - cl_kernel k_lmq = clCreateKernel(prog, "flash_attn_f32_f16_q1_local_mq_split", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_lmq, 64, - "flash_attn_f32_f16_q1_local_mq_split", dk, dv)) { - backend_ctx->fa.f32_f16_q1_local_mq_split[{dk, dv}] = k_lmq; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_lmq, "flash_attn_f32_f16_q1_local_mq_split", dk, dv); - } else { - clReleaseKernel(k_lmq); - } - } - } - - // second compile of the same source with -DMQ_GQA=8. - // FA_MQ_ONLY keeps only the vec_mq kernels so that the program - // compiles within the Adreno compiler's memory budget at DK>=256. - // FA_CL_C for the g8 program: MQ_GQA=8 doubles the c8 kernel's - // per-lane o_acc, so widen the cluster to keep the register - // footprint inside the 192-thread WG cap (see fa_cl_c_gqa4 above - // for the per-gen default). - const std::string opts_g8 = opts + " -D MQ_GQA=8 -D MQ_NSG=3 -D MQ_NSG_SPLIT=3 -D FA_MQ_ONLY -D FA_CL_C=" + fa_cl_c_g8_val; - cl_program prog_g8 = fa_decode_only ? nullptr : build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts_g8, - /*fatal=*/false, "fa f32_f16 MQ_GQA=8", backend_ctx->queue); - if (prog_g8) { - const size_t mq_g8_required_wg = 192; // Q1_WG_SIZE(64) * MQ_NSG_SPLIT(3) - cl_kernel k_q1_vec_mq_g8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_g8, mq_g8_required_wg, - "flash_attn_f32_f16_q1_vec_mq (g8)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_g8[{dk, dv}] = k_q1_vec_mq_g8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_g8, "flash_attn_f32_f16_q1_vec_mq_g8", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_g8); - } - } - cl_kernel k_q1_vec_mq_split_g8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq_split", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_g8, mq_g8_required_wg, - "flash_attn_f32_f16_q1_vec_mq_split (g8)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8[{dk, dv}] = k_q1_vec_mq_split_g8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_g8, "flash_attn_f32_f16_q1_vec_mq_split_g8", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_split_g8); - } - } - // K-image variant - cl_kernel k_q1_vec_mq_split_g8_k_img = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq_split_k_img", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_g8_k_img, mq_g8_required_wg, - "flash_attn_f32_f16_q1_vec_mq_split_k_img (g8)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_k_img[{dk, dv}] = k_q1_vec_mq_split_g8_k_img; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_g8_k_img, "flash_attn_f32_f16_q1_vec_mq_split_g8_k_img", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_split_g8_k_img); - } - } - // Cluster-parallel decode, MQ_GQA=8 / FA_CL_C=16 specialization - cl_kernel k_q1_vec_mq_split_g8_c8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_g8_c8, mq_g8_required_wg, - "flash_attn_f32_f16_q1_vec_mq_split_c8 (g8)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8[{dk, dv}] = k_q1_vec_mq_split_g8_c8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_g8_c8, "flash_attn_f32_f16_q1_vec_mq_split_g8_c8", dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_split_g8_c8); - } - } - // hybrid local-tile + MQ_GQA=8 - if (dk == 128 && dv == 128) { - cl_kernel k_lmq_g8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_local_mq_split", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_lmq_g8, 64, - "flash_attn_f32_f16_q1_local_mq_split (g8)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_local_mq_split_g8[{dk, dv}] = k_lmq_g8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_lmq_g8, "flash_attn_f32_f16_q1_local_mq_split_g8", dk, dv); - } else { - clReleaseKernel(k_lmq_g8); - } - } - } - clReleaseProgram(prog_g8); - } - // NSG_SPLIT=2 programs for the cluster-parallel kernel: its register - // footprint caps the per-kernel WG at 128 on X2 (< the stock 256/192 - // requirement), so it can never register from the stock programs. - // With FA_CL_NCL position streams per subgroup, 2 subgroups still - // carry 16 in-flight rows per WG (baseline WG has 4). FA_MQ_ONLY - // keeps these compiles minimal; skipped when the stock program c8 - // registered (some other device) or shuffles are absent. - if (!fa_decode_only && backend_ctx->has_subgroup_shuffle && - backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.count({dk, dv}) == 0) { - const std::string opts_c8_ns2 = opts + " -D FA_MQ_ONLY -D MQ_GQA=4 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2" + opts_cl_c_gqa4; - cl_program prog_c8 = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts_c8_ns2, - /*fatal=*/false, "fa f32_f16 c8 NSG2", backend_ctx->queue); - if (prog_c8) { - cl_kernel k_c8 = clCreateKernel(prog_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); - if (err == CL_SUCCESS) { - // WG = MQ_NSG(2) × Q1_WG_SIZE(=FA_SG): 128 Adreno (64), 64 Intel (32). - const size_t c8_ns2_wg = backend_ctx->gpu_family == INTEL ? 64 : 128; - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_c8, c8_ns2_wg, - "flash_attn_f32_f16_q1_vec_mq_split_c8 (ns2)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2[{dk, dv}] = k_c8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8_ns2", dk, dv); - } else { - clReleaseKernel(k_c8); - } - } - clReleaseProgram(prog_c8); - } - } - // FA_CL_C=32 g8 program for the DK=DV=256 GQA=8 - if (!fa_decode_only && backend_ctx->has_subgroup_shuffle && - dk == 256 && dv == 256) { - const std::string opts_g8_c32 = opts + " -D FA_MQ_ONLY -D MQ_GQA=8 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2 -D FA_CL_C=32"; - cl_program prog_g8_c32 = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts_g8_c32, - /*fatal=*/false, "fa f32_f16 c32 g8 d256 NSG2", backend_ctx->queue); - if (prog_g8_c32) { - cl_kernel k_g8_c32 = clCreateKernel(prog_g8_c32, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_g8_c32, 128, - "flash_attn_f32_f16_q1_vec_mq_split_c8 (g8 c32 d256)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c32[{dk, dv}] = k_g8_c32; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_g8_c32, "flash_attn_f32_f16_q1_vec_mq_split_g8_c32", dk, dv); - } else { - clReleaseKernel(k_g8_c32); - } - } - clReleaseProgram(prog_g8_c32); - } - } - if (!fa_decode_only && backend_ctx->has_subgroup_shuffle && - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.count({dk, dv}) == 0) { - const std::string opts_g8_c8_ns2 = opts + " -D FA_MQ_ONLY -D MQ_GQA=8 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2 -D FA_CL_C=" + fa_cl_c_g8_val; - cl_program prog_g8_c8 = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts_g8_c8_ns2, - /*fatal=*/false, "fa f32_f16 c8 g8 NSG2", backend_ctx->queue); - if (prog_g8_c8) { - cl_kernel k_g8_c8 = clCreateKernel(prog_g8_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_g8_c8, 128, - "flash_attn_f32_f16_q1_vec_mq_split_c8 (g8 ns2)", dk, dv)) { - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8_ns2[{dk, dv}] = k_g8_c8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_g8_c8, "flash_attn_f32_f16_q1_vec_mq_split_g8_c8_ns2", dk, dv); - } else { - clReleaseKernel(k_g8_c8); - } - } - clReleaseProgram(prog_g8_c8); - } - } - break; - } - case FA_VARIANT_Q8_0: - case FA_VARIANT_Q4_0: { - const bool is_q8 = variant == FA_VARIANT_Q8_0; - const std::string base = is_q8 ? "flash_attn_f32_q8_0" : "flash_attn_f32_q4_0"; - const std::string name_q1 = base + "_q1"; - const std::string name_q1_split = base + "_q1_split"; - auto & m_q1 = is_q8 ? backend_ctx->fa.f32_q8_0_q1 : backend_ctx->fa.f32_q4_0_q1; - auto & m_prefill = is_q8 ? backend_ctx->fa.f32_q8_0 : backend_ctx->fa.f32_q4_0; - auto & m_q1_split = is_q8 ? backend_ctx->fa.f32_q8_0_q1_split : backend_ctx->fa.f32_q4_0_q1_split; - - cl_kernel k, kq1; - CL_CHECK((kq1 = clCreateKernel(prog, name_q1.c_str(), &err), err)); - CL_CHECK((k = clCreateKernel(prog, base.c_str(), &err), err)); - m_q1[{dk, dv}] = kq1; - m_prefill[{dk, dv}] = k; - ggml_opencl_log_fa_kernel_spill(backend_ctx, kq1, name_q1.c_str(), dk, dv); - ggml_opencl_log_fa_kernel_spill(backend_ctx, k, base.c_str(), dk, dv); - cl_kernel k_split = clCreateKernel(prog, name_q1_split.c_str(), &err); - if (err == CL_SUCCESS) { - m_q1_split[{dk, dv}] = k_split; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_split, name_q1_split.c_str(), dk, dv); - } - - // DV-split decode variant (q1_vec) - auto & m_q1_vec = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec : backend_ctx->fa.f32_q4_0_q1_vec; - const std::string name_q1_vec = name_q1 + "_vec"; - cl_kernel k_q1_vec = clCreateKernel(prog, name_q1_vec.c_str(), &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec, 256, - name_q1_vec.c_str(), dk, dv)) { - m_q1_vec[{dk, dv}] = k_q1_vec; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec, name_q1_vec.c_str(), dk, dv); - } else { - clReleaseKernel(k_q1_vec); - } - } - - // KV-head-coalesced + flash-decoding split - auto & m_mq_split = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec_mq_split - : backend_ctx->fa.f32_q4_0_q1_vec_mq_split; - const std::string name_mq_split = name_q1 + "_vec_mq_split"; - cl_kernel k_q1_vec_mq_split = clCreateKernel(prog, name_mq_split.c_str(), &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split, 256, - name_mq_split.c_str(), dk, dv)) { - m_mq_split[{dk, dv}] = k_q1_vec_mq_split; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split, name_mq_split.c_str(), dk, dv); - } else { - clReleaseKernel(k_q1_vec_mq_split); - } - } - if (!backend_ctx->fa.f32_merge.count({dk, dv})) { - cl_kernel k_merge = clCreateKernel(prog, "flash_attn_f32_merge", &err); - if (err == CL_SUCCESS) { - backend_ctx->fa.f32_merge[{dk, dv}] = k_merge; - } - } - // Second compile with MQ_GQA=8, MQ_NSG=3, MQ_NSG_SPLIT=3 - auto & m_mq_split_g8 = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec_mq_split_g8 - : backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8; - const std::string opts_mq_g8 = opts + " -D MQ_GQA=8 -D MQ_NSG=3 -D MQ_NSG_SPLIT=3"; - cl_program prog_mq_g8 = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts_mq_g8, - /*fatal=*/false, is_q8 ? "fa q8_0 MQ_GQA=8" : "fa q4_0 MQ_GQA=8", - backend_ctx->queue); - if (prog_mq_g8) { - const size_t mq_g8_required_wg = 192; - cl_kernel k_g8 = clCreateKernel(prog_mq_g8, name_mq_split.c_str(), &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_g8, mq_g8_required_wg, - name_mq_split.c_str(), dk, dv)) { - m_mq_split_g8[{dk, dv}] = k_g8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_g8, name_mq_split.c_str(), dk, dv); - } else { - clReleaseKernel(k_g8); - } - } - clReleaseProgram(prog_mq_g8); - } - // GQA=4 cluster-parallel program (NSG_SPLIT=2 / WG=128) - if (backend_ctx->has_subgroup_shuffle) { - auto & m_c8_gqa4 = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec_mq_split_c8 - : backend_ctx->fa.f32_q4_0_q1_vec_mq_split_c8; - const std::string name_c8_gqa4 = name_q1 + "_vec_mq_split_c8"; - const std::string opts_c8_gqa4 = opts + " -D MQ_GQA=4 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2" + opts_cl_c_gqa4; - cl_program prog_c8_gqa4 = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts_c8_gqa4, - /*fatal=*/false, is_q8 ? "fa q8_0 c8 GQA4 NSG2" : "fa q4_0 c8 GQA4 NSG2", - backend_ctx->queue); - if (prog_c8_gqa4) { - cl_kernel k_c8_gqa4 = clCreateKernel(prog_c8_gqa4, name_c8_gqa4.c_str(), &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_c8_gqa4, 128, - name_c8_gqa4.c_str(), dk, dv)) { - m_c8_gqa4[{dk, dv}] = k_c8_gqa4; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_c8_gqa4, name_c8_gqa4.c_str(), dk, dv); - } else { - clReleaseKernel(k_c8_gqa4); - } - } - clReleaseProgram(prog_c8_gqa4); - } - } - // Cluster-parallel q4_0 decode kernel - if (!is_q8 && backend_ctx->has_subgroup_shuffle) { - const std::string opts_c8 = opts + " -D MQ_GQA=8 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2"; - cl_program prog_c8 = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts_c8, - /*fatal=*/false, "fa q4_0 c8 NSG2", backend_ctx->queue); - if (prog_c8) { - cl_kernel k_c8 = clCreateKernel(prog_c8, "flash_attn_f32_q4_0_q1_vec_mq_split_c8", &err); - if (err == CL_SUCCESS) { - if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_c8, 128, - "flash_attn_f32_q4_0_q1_vec_mq_split_c8 (g8 ns2)", dk, dv)) { - backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8_c8[{dk, dv}] = k_c8; - ggml_opencl_log_fa_kernel_spill(backend_ctx, k_c8, "flash_attn_f32_q4_0_q1_vec_mq_split_g8_c8", dk, dv); - } else { - clReleaseKernel(k_c8); - } - } - clReleaseProgram(prog_c8); - } - } - break; - } - case FA_VARIANT_F32_F16_SPLIT: { - cl_kernel k; - CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_f16", &err), err)); - backend_ctx->fa.f32_f16_split[{dk, dv}] = k; - backend_ctx->fa.f32_f16_split_wg_size[{dk, dv}] = cfg->bm * cfg->n_split; - backend_ctx->fa.f32_f16_split_nkv_threshold[{dk, dv}] = cfg->nkv_split_threshold; - break; - } - case FA_VARIANT_Q8_0_SPLIT: - case FA_VARIANT_Q4_0_SPLIT: { - const bool is_q8 = variant == FA_VARIANT_Q8_0_SPLIT; - cl_kernel k; - CL_CHECK((k = clCreateKernel(prog, is_q8 ? "flash_attn_f32_q8_0" : "flash_attn_f32_q4_0", &err), err)); - auto & split = is_q8 ? backend_ctx->fa.f32_q8_0_split : backend_ctx->fa.f32_q4_0_split; - auto & split_wg = is_q8 ? backend_ctx->fa.f32_q8_0_split_wg_size : backend_ctx->fa.f32_q4_0_split_wg_size; - auto & split_bm = is_q8 ? backend_ctx->fa.f32_q8_0_split_bm : backend_ctx->fa.f32_q4_0_split_bm; - auto & split_thresh = is_q8 ? backend_ctx->fa.f32_q8_0_split_nkv_threshold : backend_ctx->fa.f32_q4_0_split_nkv_threshold; - split[{dk, dv}] = k; - split_wg[{dk, dv}] = cfg->bm * cfg->n_split; - split_bm[{dk, dv}] = cfg->bm; - split_thresh[{dk, dv}] = 0; // quant prefill: always split - break; - } - default: - break; - } - CL_CHECK(clReleaseProgram(prog)); - return true; -} - -// Compile a quant FA split kernel with a hand-picked (BLOCK_M, N_SPLIT) that -// overrides the default fa_dims tuning, for the DK values where the default -// N_SPLIT is degenerate for quant prefill: -// DK=256: default N_SPLIT=16 leaves DK/32=8 blocks -> 0 blocks/split. -// Override N_SPLIT=8 (1 block/split), BLOCK_M=16. -// DK=96 : DK/32 = 3 blocks, not divisible by the default N_SPLIT=2 -> -// override N_SPLIT=3. BLOCK_M must be 16, not 32: the N_SPLIT=3 -// QK-partial reduction uses sub_group_shuffle, so all 3 split -// threads of a query must land in one subgroup — WG_SIZE = -// BLOCK_M*N_SPLIT must be <= the 64-lane Adreno subgroup (16*3=48). -static bool ggml_opencl_ensure_fa_quant_split_override( - ggml_backend_opencl_context * backend_ctx, - int dk, int dv, int quant_bm, int quant_n_split, bool is_q8_0 -) { - const std::pair dk_dv = {dk, dv}; - if (is_q8_0 && backend_ctx->fa.f32_q8_0_split.count(dk_dv)) { - return true; - } - if (!is_q8_0 && backend_ctx->fa.f32_q4_0_split.count(dk_dv)) { - return true; - } - - const ggml_opencl_fa_variant variant = is_q8_0 ? FA_VARIANT_Q8_0_SPLIT : FA_VARIANT_Q4_0_SPLIT; - const auto attempt_key = std::make_pair(variant, dk_dv); - if (backend_ctx->fa.variant_attempted.count(attempt_key)) { - return false; - } - - backend_ctx->fa.variant_attempted.insert(attempt_key); - - std::string shuffle_opts; - if (backend_ctx->has_subgroup_shuffle) { - shuffle_opts = backend_ctx->has_qcom_subgroup_shuffle - ? " -D cl_qcom_subgroup_shuffle=1" - : " -D cl_khr_subgroup_shuffle=1"; - } - const ggml_opencl_fa_dim * cfg = nullptr; - for (const auto & d : g_opencl_fa_dims) { - if (d.dk == dk && d.dv == dv) { - cfg = &d; break; - } - } - if (cfg == nullptr) { - return false; - } - - // BLK_PREPASS_BM is the prepass-kernel BLOCK_M, needed so the quant kernel - // indexes the blk[] classification buffer correctly. - std::string opts = backend_ctx->kernel_compile_opts + shuffle_opts + - " -D DK=" + std::to_string(dk) + - " -D DV=" + std::to_string(dv) + - " -D BLOCK_M=" + std::to_string(quant_bm) + - " -D BLOCK_N=" + std::to_string(cfg->bn) + - " -D N_SPLIT=" + std::to_string(quant_n_split) + - " -D BLK_PREPASS_BM=" + std::to_string(cfg->bm); - - const std::string src = ggml_opencl_fa_kernel_src(variant); - if (src.empty()) { - return false; - } - - const std::string tag = std::string("fa ") + (is_q8_0 ? "q8_0" : "q4_0") + - " split DK=" + std::to_string(dk); - cl_program prog = build_program_from_source_ex( - backend_ctx->context, backend_ctx->device, src.c_str(), opts, - /*fatal=*/false, tag.c_str(), backend_ctx->queue); - if (!prog) { return false; } - cl_int err; - cl_kernel k; - if (is_q8_0) { - CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_q8_0", &err), err)); - backend_ctx->fa.f32_q8_0_split[dk_dv] = k; - backend_ctx->fa.f32_q8_0_split_wg_size[dk_dv] = quant_bm * quant_n_split; - backend_ctx->fa.f32_q8_0_split_bm[dk_dv] = quant_bm; - backend_ctx->fa.f32_q8_0_split_nkv_threshold[dk_dv] = 0; - } else { - CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_q4_0", &err), err)); - backend_ctx->fa.f32_q4_0_split[dk_dv] = k; - backend_ctx->fa.f32_q4_0_split_wg_size[dk_dv] = quant_bm * quant_n_split; - backend_ctx->fa.f32_q4_0_split_bm[dk_dv] = quant_bm; - backend_ctx->fa.f32_q4_0_split_nkv_threshold[dk_dv] = 0; - } - CL_CHECK(clReleaseProgram(prog)); - return true; -} - -namespace /* anonymous */ { -extern struct ggml_backend_device_i ggml_backend_opencl_device_i; -} - -// Look for available and suitable devices. -static std::vector ggml_opencl_probe_devices(ggml_backend_reg * reg) { - std::vector found_devices; - -#ifdef GGML_OPENCL_PROFILING - GGML_LOG_INFO("ggml_opencl: OpenCL profiling enabled\n"); -#endif - - struct cl_device; - struct cl_platform { - cl_platform_id id; - unsigned number; - char name[128]; - char vendor[128]; - struct cl_device * devices; - unsigned n_devices; - struct cl_device * default_device; - }; - - struct cl_device { - struct cl_platform * platform; - cl_device_id id; - unsigned number; - cl_device_type type; - char name[128]; - char version[128]; - }; - - enum { NPLAT = 16, NDEV = 16 }; - - struct cl_platform platforms[NPLAT]; - unsigned n_platforms = 0; - struct cl_device devices[NDEV]; - unsigned n_devices = 0; - struct cl_device * default_device = NULL; - unsigned default_platform_number = 0; - - cl_platform_id platform_ids[NPLAT]; - if (clGetPlatformIDs(NPLAT, platform_ids, &n_platforms) != CL_SUCCESS) { - GGML_LOG_ERROR("ggml_opencl: platform IDs not available.\n"); - return found_devices; - } - - for (unsigned i = 0; i < n_platforms; i++) { - struct cl_platform * p = &platforms[i]; - p->number = i; - p->id = platform_ids[i]; - CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_NAME, sizeof(p->name), &p->name, NULL)); - CL_CHECK(clGetPlatformInfo(p->id, CL_PLATFORM_VENDOR, sizeof(p->vendor), &p->vendor, NULL)); - - cl_device_id device_ids[NDEV]; - cl_int clGetDeviceIDsError = clGetDeviceIDs(p->id, CL_DEVICE_TYPE_ALL, NDEV, device_ids, &p->n_devices); - if (clGetDeviceIDsError == CL_DEVICE_NOT_FOUND) { - p->n_devices = 0; - } else { - CL_CHECK(clGetDeviceIDsError); - } - p->devices = p->n_devices > 0 ? &devices[n_devices] : NULL; - p->default_device = NULL; - - for (unsigned j = 0; j < p->n_devices; j++) { - struct cl_device * d = &devices[n_devices]; - d->number = n_devices++; - d->id = device_ids[j]; - d->platform = p; - CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_NAME, sizeof(d->name), &d->name, NULL)); - CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_TYPE, sizeof(d->type), &d->type, NULL)); - CL_CHECK(clGetDeviceInfo(d->id, CL_DEVICE_VERSION, sizeof(d->version), &d->version, NULL)); - - if (p->default_device == NULL && d->type == CL_DEVICE_TYPE_GPU) { - p->default_device = d; - } - } - - if (default_device == NULL && p->default_device != NULL) { - default_device = p->default_device; - default_platform_number = i; - } - } - - if (n_devices == 0) { - GGML_LOG_ERROR("ggml_opencl: could find any OpenCL devices.\n"); - return found_devices; - } - - char * user_platform_string = getenv("GGML_OPENCL_PLATFORM"); - char * user_device_string = getenv("GGML_OPENCL_DEVICE"); - int user_platform_number = -1; - int user_device_number = -1; - cl_device * candidate_devices = nullptr; - unsigned n_candidate_devices = 0; - - unsigned n; - if (user_platform_string != NULL && sscanf(user_platform_string, " %u", &n) == 1 && n < n_platforms) { - user_platform_number = (int)n; - } - if (user_device_string != NULL && sscanf(user_device_string, " %u", &n) == 1 && n < n_devices) { - user_device_number = (int)n; - } - if (user_platform_number != -1 && user_device_number != -1) { - cl_platform* platform = &platforms[user_platform_number]; - if ((unsigned)user_device_number >= platform->n_devices) { - GGML_LOG_ERROR("ggml_opencl: invalid device number %d\n", user_device_number); - exit(1); - } - default_device = &platform->devices[user_device_number]; - candidate_devices = platform->devices; - n_candidate_devices = platform->n_devices; - } else { - // Choose a platform by matching a substring. - if (user_platform_number == -1 && user_platform_string != NULL && user_platform_string[0] != 0) { - for (unsigned i = 0; i < n_platforms; i++) { - struct cl_platform * p = &platforms[i]; - if (strstr(p->name, user_platform_string) != NULL || - strstr(p->vendor, user_platform_string) != NULL) { - user_platform_number = (int)i; - break; - } - } - if (user_platform_number == -1) { - GGML_LOG_ERROR("ggml_opencl: no platform matching '%s' was found.\n", user_platform_string); - exit(1); - } - } - - int platform_idx = user_platform_number != -1 ? user_platform_number : default_platform_number; - struct cl_platform * p = &platforms[platform_idx]; - candidate_devices = p->devices; - n_candidate_devices = p->n_devices; - default_device = p->default_device; - if (n_candidate_devices == 0) { - GGML_LOG_ERROR("ggml_opencl: selected platform '%s' does not have any devices.\n", p->name); - exit(1); - } - - if (user_device_number == -1 && user_device_string != NULL && user_device_string[0] != 0) { - for (unsigned i = 0; i < n_candidate_devices; i++) { - struct cl_device * d = &candidate_devices[i]; - if (strstr(d->name, user_device_string) != NULL) { - user_device_number = d->number; - break; - } - } - if (user_device_number == -1) { - GGML_LOG_ERROR("ggml_opencl: no device matching '%s' was found.\n", user_device_string); - exit(1); - } - } - if (user_device_number != -1) { - candidate_devices = &devices[user_device_number]; - n_candidate_devices = 1; - default_device = &candidate_devices[0]; - } - - GGML_ASSERT(n_candidate_devices > 0); - - if (default_device == NULL) { - default_device = &candidate_devices[0]; - } - } - - GGML_ASSERT(n_candidate_devices != 0 && candidate_devices); - - // Put the default device in front. - for (unsigned i = 1; i < n_candidate_devices; i++) { - if (&candidate_devices[i] == default_device) { - std::swap(candidate_devices[0], candidate_devices[i]); - default_device = &candidate_devices[0]; - break; - } - } - - GGML_LOG_INFO("ggml_opencl: selected platform: '%s'\n", default_device->platform->name); - - std::vector device_ids; - for (auto dev = candidate_devices, dev_end = candidate_devices + n_candidate_devices; dev != dev_end; dev++) { - device_ids.push_back(dev->id); - } - - cl_int err; - cl_context shared_context; - cl_context_properties properties[] = { (intptr_t) CL_CONTEXT_PLATFORM, (intptr_t) default_device->platform->id, 0 }; - - CL_CHECK( - (shared_context = clCreateContext(properties, device_ids.size(), device_ids.data(), NULL, NULL, &err), err)); - - for (auto dev = candidate_devices, dev_end = candidate_devices + n_candidate_devices; dev != dev_end; dev++) { - GGML_LOG_INFO("\nggml_opencl: device: '%s (%s)'\n", dev->name, dev->version); - - auto dev_ctx = std::unique_ptr(new ggml_backend_opencl_device_context{ - /*.platform =*/dev->platform->id, - /*.platform_nane =*/dev->platform->name, - /*.device =*/dev->id, - /*.device_name =*/dev->name, - /*.device_type =*/dev->type, - /*.device_version =*/dev->version, - /*.backend_ctx =*/nullptr, - /*.buffer_type =*/{}, - /*.context =*/shared_context, - }); - - found_devices.push_back(ggml_backend_device{ - /* .iface = */ ggml_backend_opencl_device_i, - /* .reg = */ reg, - /* .context = */ dev_ctx.get(), - }); - - if (!ggml_opencl_is_device_supported(&found_devices.back())) { - found_devices.pop_back(); - GGML_LOG_WARN("ggml_opencl: drop unsupported device '%s'.\n", dev->name); - continue; - } - - g_ggml_backend_opencl_dev_ctxs.push_back(std::move(dev_ctx)); - } - - if (found_devices.size()) { - auto * dev_ctx = static_cast(found_devices.front().context); - GGML_LOG_INFO("ggml_opencl: default device: '%s (%s)'\n", dev_ctx->device_name.c_str(), - dev_ctx->device_version.c_str()); - - if (dev_ctx->device_type != CL_DEVICE_TYPE_GPU) { - GGML_LOG_WARN("ggml_opencl: warning, the default device is not a GPU: '%s'.\n", - dev_ctx->device_name.c_str()); - } - } - - return found_devices; -} - -static void ggml_opencl_print_backend_info(ggml_backend_opencl_device_context * dev_ctx) { - GGML_ASSERT(dev_ctx); - GGML_ASSERT(dev_ctx->backend_ctx); - - auto * backend_ctx = dev_ctx->backend_ctx; - - GGML_LOG_INFO("ggml_opencl: OpenCL device: %s\n", - backend_ctx->device_name.c_str()); - GGML_LOG_INFO("ggml_opencl: OpenCL driver: %s\n", - backend_ctx->driver_version.c_str()); - GGML_LOG_INFO("ggml_opencl: vector subgroup broadcast support: %s\n", - backend_ctx->has_vector_subgroup_broadcast ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: subgroup shuffle support: %s\n", - backend_ctx->has_subgroup_shuffle ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: device FP16 support: %s\n", - backend_ctx->fp16_support ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: khr dot product support: %s\n", - backend_ctx->has_integer_dot ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: mem base addr align: %u\n", - backend_ctx->alignment); - GGML_LOG_INFO("ggml_opencl: global mem size: %zu MB\n", - backend_ctx->global_mem_size/1024/1024); - GGML_LOG_INFO("ggml_opencl: max mem alloc size: %zu MB\n", - backend_ctx->max_alloc_size/1024/1024); - GGML_LOG_INFO("ggml_opencl: device max image buffer size (pixels): %zu\n", - backend_ctx->image_max_buffer_size); - GGML_LOG_INFO("ggml_opencl: device max image2d size: %zu x %zu\n", - backend_ctx->image2d_max_width, backend_ctx->image2d_max_height); - GGML_LOG_INFO("ggml_opencl: device max workgroup size: %zu\n", - backend_ctx->max_workgroup_size); - GGML_LOG_INFO("ggml_opencl: SVM coarse grain buffer support: %s\n", - backend_ctx->svm_caps & CL_DEVICE_SVM_COARSE_GRAIN_BUFFER ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: SVM fine grain buffer support: %s\n", - backend_ctx->svm_caps & CL_DEVICE_SVM_FINE_GRAIN_BUFFER ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: SVM fine grain system support: %s\n", - backend_ctx->svm_caps & CL_DEVICE_SVM_FINE_GRAIN_SYSTEM ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: SVM atomics support: %s\n", - backend_ctx->svm_caps & CL_DEVICE_SVM_ATOMICS ? "true" : "false"); - GGML_LOG_INFO("ggml_opencl: cl_qcom_subgroup_shuffle support: %s\n", - backend_ctx->has_qcom_subgroup_shuffle ? "true" : "false"); - - // Print out configurations -#ifdef GGML_OPENCL_SOA_Q - GGML_LOG_INFO("ggml_opencl: flattening quantized weights representation as struct of arrays (GGML_OPENCL_SOA_Q)\n"); -#endif // GGML_OPENCL_SOA_Q - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_LOG_INFO("ggml_opencl: using kernels optimized for Adreno (GGML_OPENCL_USE_ADRENO_KERNELS)\n"); - if (backend_ctx->adreno_xmem_gemm_enabled) { - GGML_LOG_INFO("ggml_opencl: Adreno xmem F16xF32 GEMM enabled (temporary weight prepack)\n"); - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - if (backend_ctx->adreno_use_large_buffer) { - if (!backend_ctx->adreno_has_large_buffer) { - GGML_LOG_INFO("ggml_opencl: Adreno large buffer requested but not supported by driver, will use regular buffer\n"); - backend_ctx->adreno_use_large_buffer = false; - } else { - GGML_LOG_INFO("ggml_opencl: Adreno large buffer enabled\n"); - } - } - - if (dev_ctx->opfilter) { - // for information only, the actual regex object is created in ggml_opencl_is_device_supported - GGML_LOG_INFO("ggml_opencl: opfilter regex = \"%s\"\n", dev_ctx->opfilter_str.c_str()); - } -} - -// check if device should be accepted -static bool ggml_opencl_is_device_supported(ggml_backend_dev_t dev) { - GGML_ASSERT(dev); - GGML_ASSERT(dev->context); - - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; - GGML_ASSERT(dev_ctx->platform); - GGML_ASSERT(dev_ctx->device); - - if (strstr(dev_ctx->device_name.c_str(), "Adreno") || - strstr(dev_ctx->device_name.c_str(), "Qualcomm") || - strstr(dev_ctx->device_version.c_str(), "Adreno")) { - dev_ctx->gpu_family = GPU_FAMILY::ADRENO; - - // Usually device version contains the detailed device name - dev_ctx->adreno_gen = get_adreno_gpu_gen(dev_ctx->device_version.c_str()); - if (dev_ctx->adreno_gen == ADRENO_GPU_GEN::ADRENO_UNKNOWN) { - dev_ctx->adreno_gen = get_adreno_gpu_gen(dev_ctx->device_name.c_str()); - } - } else if (strstr(dev_ctx->device_name.c_str(), "Intel")) { - dev_ctx->gpu_family = GPU_FAMILY::INTEL; - } else { - GGML_LOG_WARN("ggml_opencl: unsupported GPU '%s'.\n", dev_ctx->device_name.c_str()); - dev_ctx->gpu_family = GPU_FAMILY::UNKNOWN; - return false; - } - - ggml_cl_version platform_version = get_opencl_platform_version(dev_ctx->platform); - - // Check device OpenCL version, OpenCL 2.0 or above is required - ggml_cl_version opencl_c_version = get_opencl_c_version(platform_version, dev_ctx->device); - if (opencl_c_version.major < 2) { - GGML_LOG_WARN("ggml_opencl: OpenCL 2.0 or above is required\n"); - return false; - } - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (dev_ctx->gpu_family != GPU_FAMILY::ADRENO) { - GGML_LOG_WARN("ggml_opencl: Adreno-specific kernels should not be enabled for non-Adreno GPUs; " - "run on an Adreno GPU or recompile with CMake option `-DGGML_OPENCL_USE_ADRENO_KERNELS=OFF`\n"); - return false; - } -#endif - - size_t ext_str_size; - CL_CHECK(clGetDeviceInfo(dev_ctx->device, CL_DEVICE_EXTENSIONS, 0, NULL, &ext_str_size)); - - std::vector ext_buffer(ext_str_size + 1); - CL_CHECK(clGetDeviceInfo(dev_ctx->device, CL_DEVICE_EXTENSIONS, ext_str_size, ext_buffer.data(), NULL)); - ext_buffer[ext_str_size] = '\0'; - - // Check if ext_buffer contains cl_khr_fp16 - bool fp16_support = strstr(ext_buffer.data(), "cl_khr_fp16") != NULL; - if (!fp16_support) { - GGML_LOG_WARN("ggml_opencl: device does not support FP16\n"); - return false; - } - - // If OpenCL 3.0 is supported, then check for cl_khr_subgroups, which becomes - // optional in OpenCL 3.0 (cl_khr_subgroup is mandatory in OpenCL 2.x) - if (opencl_c_version.major == 3 && strstr(ext_buffer.data(), "cl_khr_subgroups") == NULL && - strstr(ext_buffer.data(), "cl_intel_subgroups") == NULL) { - GGML_LOG_WARN("ggml_opencl: device does not support subgroups (cl_khr_subgroups or cl_intel_subgroups) " - "(note that subgroups is an optional feature in OpenCL 3.0)\n"); - return false; - } - - clGetDeviceInfo(dev_ctx->device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(size_t), &dev_ctx->global_mem_size, NULL); - - const char * str_opfilter = getenv("GGML_OPENCL_OPFILTER"); - if (str_opfilter) { - dev_ctx->opfilter_str = str_opfilter; - dev_ctx->opfilter = new std::regex(str_opfilter, std::regex_constants::icase); - } - - return true; -} - -// Initialize device if it is supported (returns nullptr if it is not). -static ggml_backend_opencl_context * ggml_cl_init(ggml_backend_dev_t dev) { - GGML_ASSERT(dev); - GGML_ASSERT(dev->context); - - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; - GGML_ASSERT(dev_ctx->platform); - GGML_ASSERT(dev_ctx->device); - - if (dev_ctx->backend_ctx) { - return dev_ctx->backend_ctx; - } - - auto backend_ctx = std::make_unique(); - backend_ctx->device = dev_ctx->device; - backend_ctx->gpu_family = GPU_FAMILY::UNKNOWN; - - // ref_count get increased in ggml_backend_opencl_device_init - // This function is also used to retrieve backend context, so we don't want - // to increase ref_count for each call. We only want to increase ref_count - // when the associated device is initialized - backend_ctx->ref_count = 0; - - backend_ctx->gpu_family = dev_ctx->gpu_family; - backend_ctx->adreno_gen = dev_ctx->adreno_gen; - if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO) { - ggml_cl_init_fa_dims_table(); - - // Use wave size of 64 for all Adreno GPUs. - backend_ctx->adreno_wave_size = 64; - } - - // Populate backend device name - backend_ctx->device_name = dev_ctx->device_name; - - // A local ref of cl_device_id for convenience - cl_device_id device = backend_ctx->device; - - ggml_cl_version platform_version = get_opencl_platform_version(dev_ctx->platform); - ggml_cl_version opencl_c_version = get_opencl_c_version(platform_version, device); - - backend_ctx->platform_version = platform_version; - backend_ctx->opencl_c_version = opencl_c_version; - - // Check driver version - size_t driver_version_str_size; - CL_CHECK(clGetDeviceInfo(device, CL_DRIVER_VERSION, 0, NULL, &driver_version_str_size)); - std::vector driver_version(driver_version_str_size + 1); - CL_CHECK(clGetDeviceInfo(device, CL_DRIVER_VERSION, driver_version_str_size, driver_version.data(), NULL)); - driver_version[driver_version_str_size] = '\0'; - backend_ctx->driver_version = driver_version.data(); - - backend_ctx->adreno_cl_compiler_version = get_adreno_cl_compiler_version(driver_version.data()); - backend_ctx->has_vector_subgroup_broadcast = - (backend_ctx->adreno_cl_compiler_version.type == E031 && backend_ctx->adreno_cl_compiler_version.major >= 47) || - (backend_ctx->adreno_cl_compiler_version.type == DX && backend_ctx->adreno_cl_compiler_version.major >= 17) || - (backend_ctx->adreno_cl_compiler_version.type == E17); - - // The q6_K flat mul_mat miscompile is a defect of the older E031 compilers, not a - // property of any GPU generation: it reproduces on E031.38 (Adreno 642L) and E031.41 - // (Adreno 740) and is fixed by E031.45 (Adreno 619). Gate on the compiler so parts - // that do not need the workarounds do not pay for them. The explicit type check is - // required: newer_than_or_same() is false for every non-E031 compiler, so negating it - // alone would enable the workarounds on E17/DX. - backend_ctx->q6_k_flat_old_compiler = - backend_ctx->adreno_cl_compiler_version.type == E031 && - !backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 45, 0, 0); - - size_t ext_str_size; - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, 0, NULL, &ext_str_size)); - std::vector ext_buffer(ext_str_size + 1); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_EXTENSIONS, ext_str_size, ext_buffer.data(), NULL)); - ext_buffer[ext_str_size] = '\0'; // ensure it is null terminated - - // check support for qcom_subgroup_shuffle - if (strstr(ext_buffer.data(), "cl_qcom_subgroup_shuffle") != NULL) { - backend_ctx->has_qcom_subgroup_shuffle = true; - } - - // Check if ext_buffer contains cl_khr_fp16 - backend_ctx->fp16_support = strstr(ext_buffer.data(), "cl_khr_fp16") != NULL; - - // check Adreno large buffer support - backend_ctx->adreno_has_large_buffer = strstr(ext_buffer.data(), "cl_qcom_large_buffer") != NULL; - - // subgroup shuffle support (N_SPLIT>1 FA kernel) - backend_ctx->has_qcom_subgroup_shuffle = strstr(ext_buffer.data(), "cl_qcom_subgroup_shuffle") != NULL; - backend_ctx->has_khr_subgroup_shuffle = strstr(ext_buffer.data(), "cl_khr_subgroup_shuffle") != NULL; - backend_ctx->has_subgroup_shuffle = backend_ctx->has_khr_subgroup_shuffle || backend_ctx->has_qcom_subgroup_shuffle; - - // check for cl_khr_integer_dot_product - // cl_qcom_dot_product8 uses signed * unsigned - // while cl_khr_integer_dot_product uses signed * signed -- we stick with khr for now - backend_ctx->has_integer_dot = - strstr(ext_buffer.data(), "cl_khr_integer_dot_product") != NULL; - - cl_uint base_align_in_bits; - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MEM_BASE_ADDR_ALIGN, sizeof(cl_uint), &base_align_in_bits, NULL)); - GGML_ASSERT(base_align_in_bits % 8u == 0); - backend_ctx->alignment = base_align_in_bits / 8u; - - backend_ctx->global_mem_size = dev_ctx->global_mem_size; - - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(size_t), &backend_ctx->max_alloc_size, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE_MAX_BUFFER_SIZE, sizeof(size_t), &backend_ctx->image_max_buffer_size, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(size_t), &backend_ctx->image2d_max_width, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(size_t), &backend_ctx->image2d_max_height, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof(size_t), &backend_ctx->image3d_max_width, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof(size_t), &backend_ctx->image3d_max_height, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof(size_t), &backend_ctx->image3d_max_depth, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &backend_ctx->max_workgroup_size, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(cl_ulong), &backend_ctx->local_mem_size, NULL)); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_SVM_CAPABILITIES, sizeof(cl_device_svm_capabilities), &backend_ctx->svm_caps, 0)); - - if (opencl_c_version.major >= 3) { - // Assume it is not available for 3.0, since it is optional in 3.0. - // If compiling against 3.0, then we can query. - backend_ctx->non_uniform_workgroups = false; -#if CL_TARGET_OPENCL_VERSION >= 300 - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_NON_UNIFORM_WORK_GROUP_SUPPORT, sizeof(cl_bool), - &backend_ctx->non_uniform_workgroups, 0)); -#endif - } else { - GGML_ASSERT(opencl_c_version.major == 2); - // Non-uniform workgroup sizes is mandatory feature in v2.x. - backend_ctx->non_uniform_workgroups = true; - } - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno xmem F16xF32 GEMM, default on adreno, opt out with GGML_OPENCL_ADRENO_XMEM_GEMM=0. - // This helps models with f16 attention weights, e.g., gpt-oss-20b-f16 - { - const char * xmem_env = getenv("GGML_OPENCL_ADRENO_XMEM_GEMM"); - backend_ctx->adreno_xmem_gemm_enabled = backend_ctx->gpu_family == GPU_FAMILY::ADRENO && - (xmem_env ? atoi(xmem_env) != 0 : true); - } -#endif - - // determine whether to use large buffer for Adreno - backend_ctx->adreno_use_large_buffer = getenv("GGML_OPENCL_ADRENO_USE_LARGE_BUFFER") != nullptr && - backend_ctx->gpu_family == GPU_FAMILY::ADRENO; - - backend_ctx->kernel_compile_opts = ggml_opencl_make_compile_opts(backend_ctx.get()); - CL_CHECK(clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, - sizeof(backend_ctx->fa.compute_units), &backend_ctx->fa.compute_units, NULL)); - - // ragged moe, unspecified or non-zero means enabled, set to 0 to disable - static const char * ragged_fp16_env = getenv("GGML_OPENCL_MOE_RAGGED_FP16"); - backend_ctx->adreno_use_moe_ragged = (ragged_fp16_env == NULL) ? 1 : (atoi(ragged_fp16_env) != 0); - - // ragged moe, tile-skip granularity (columns per skip-group): 8 = quarter (default), - // 16 = half (legacy), 32 = disabled. Override with GGML_OPENCL_MOE_RAGGED_GRAN={8,16,32} - static const char * ragged_gran_env = getenv("GGML_OPENCL_MOE_RAGGED_GRAN"); - backend_ctx->adreno_moe_ragged_skip_gran = (ragged_gran_env != NULL) ? atoi(ragged_gran_env) : 8; - - // whether fuse moe combine - static const char * fuse_moe_bias_glu_env = getenv("GGML_OPENCL_FUSE_MOE_BIAS_GLU"); - backend_ctx->fuse_moe_bias_glu = fuse_moe_bias_glu_env == NULL ? 1 : (atoi(fuse_moe_bias_glu_env) != 0); - - static const char * fuse_moe_bias_combine_env = getenv("GGML_OPENCL_FUSE_MOE_BIAS_COMBINE"); - backend_ctx->fuse_moe_bias_combine = fuse_moe_bias_combine_env == NULL ? 1 : (atoi(fuse_moe_bias_combine_env) != 0); - - static const char * fuse_moe_combine_env = getenv("GGML_OPENCL_FUSE_MOE_COMBINE"); - backend_ctx->fuse_moe_combine = fuse_moe_combine_env == NULL ? 1 : (atoi(fuse_moe_combine_env) != 0); - - // ragged moe dp4 variant - static const char * ragged_dp4_env = getenv("GGML_OPENCL_MOE_RAGGED"); - backend_ctx->adreno_use_moe_ragged_dp4 = ragged_dp4_env == NULL ? 1 : (atoi(ragged_dp4_env) != 0); - -#ifdef GGML_OPENCL_USE_ADRENO_BIN_KERNELS - // try loading adreno binary kernels if enabled - // if fails to load, builtin kernels will be used - { - dl_handle * kernel_lib_handle = dl_load_library(KERNEL_LIB_NAME); - backend_ctx->adreno_use_bin_kernels = false; - - if (kernel_lib_handle) { - backend_ctx->get_adreno_bin_kernel_func = (get_adreno_bin_kernel_func_t)dl_get_sym(kernel_lib_handle, "get_adreno_kernels"); - if (backend_ctx->get_adreno_bin_kernel_func) { - GGML_LOG_INFO("ggml_opencl: loaded bin kernel library %s\n", KERNEL_LIB_NAME); - backend_ctx->adreno_use_bin_kernels = true; - } else { - GGML_LOG_INFO("ggml_opencl: bin kernel library %s is invalid, will use builtin kernels\n", KERNEL_LIB_NAME); - } - } else { - GGML_LOG_INFO("ggml_opencl: failed to load %s, will use builtin kernels\n", KERNEL_LIB_NAME); - } - } -#endif // GGML_OPENCL_USE_ADRENO_BIN_KERNELS - - cl_int err; - - // A local ref of cl_context for convenience - cl_context context = backend_ctx->context = dev_ctx->context; - - //CL_CHECK((queue = clCreateCommandQueue(context, device, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, &err), - // (err != CL_INVALID_QUEUE_PROPERTIES && err != CL_INVALID_VALUE ? err : - // (queue = clCreateCommandQueue(context, device, 0, &err), err) - //))); - cl_command_queue_properties command_queue_props = 0; -#ifdef GGML_OPENCL_PROFILING - command_queue_props |= CL_QUEUE_PROFILING_ENABLE; -#endif - CL_CHECK((backend_ctx->queue = clCreateCommandQueue(context, device, command_queue_props, &err), err)); - - // delay kernel loading until the first buffer is created - // load_cl_kernels(backend_ctx.get()); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Allocate intermediate buffers and images - size_t required_A_q_d_bytes = 311164928; - size_t required_A_s_d_bytes = 38895616; - size_t required_B_d_bytes = 45088768; - - // Ensure buffer sizes do not exceed the maximum allocation size - size_t max_A_q_d_bytes = MIN(required_A_q_d_bytes, backend_ctx->max_alloc_size); - size_t max_A_s_d_bytes = MIN(required_A_s_d_bytes, backend_ctx->max_alloc_size); - size_t max_B_d_bytes = MIN(required_B_d_bytes, backend_ctx->max_alloc_size); - if (required_A_q_d_bytes > backend_ctx->max_alloc_size) { - GGML_LOG_WARN("ggml_opencl: A_q_d buffer size reduced from %zu to %zu due to device limitations.\n", - required_A_q_d_bytes, max_A_q_d_bytes); - } - if (required_A_s_d_bytes > backend_ctx->max_alloc_size) { - GGML_LOG_WARN("ggml_opencl: A_s_d buffer size reduced from %zu to %zu due to device limitations.\n", - required_A_s_d_bytes, max_A_s_d_bytes); - } - if (required_B_d_bytes > backend_ctx->max_alloc_size) { - GGML_LOG_WARN("ggml_opencl: B_d buffer size reduced from %zu to %zu due to device limitations.\n", - required_B_d_bytes, max_B_d_bytes); - } - - backend_ctx->prealloc_quant_trans.allocate(context, max_A_q_d_bytes); - backend_ctx->prealloc_scales_trans.allocate(context, max_A_s_d_bytes); - backend_ctx->prealloc_act_trans.allocate(context, max_B_d_bytes); -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - backend_ctx->disable_fusion = getenv("GGML_OPENCL_DISABLE_FUSION") != nullptr; - if (const char * env = getenv("GGML_OPENCL_FUSE_MM_GLU")) { - backend_ctx->fuse_mm_glu = atoi(env) != 0; - } - if (const char * env = getenv("GGML_OPENCL_FUSE_RMS_ADD")) { - backend_ctx->fuse_rms_add = atoi(env) != 0; - } - if (const char * env = getenv("GGML_OPENCL_F16_MROW")) { - backend_ctx->f16_mrow = atoi(env) != 0; - } - if (const char * env = getenv("GGML_OPENCL_F16_MROW_RPT")) { - const int v = atoi(env); - backend_ctx->f16_mrow_rpt = (v == 2 || v == 4 || v == 8 || v == 16) ? v : 1; - } - - dev_ctx->backend_ctx = backend_ctx.release(); - return dev_ctx->backend_ctx; -} - -static void ggml_cl_free(ggml_backend_t backend) { - ggml_backend_opencl_context * ctx = (ggml_backend_opencl_context *) backend->context; - ctx->free(); -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static void transpose_2d( - ggml_backend_opencl_context * backend_ctx, - cl_kernel kernel, - cl_mem src, cl_mem dst, size_t size, - cl_int stride, cl_int rows, - bool blocking = true, - bool auto_local = false // let driver pick local size for non-uniform workgroups -) { - static ggml_cl_buffer buf; - - cl_event evt; - cl_int err; - - buf.allocate(backend_ctx->context, size); - - cl_mem trans; - cl_buffer_region region; - - region.origin = 0; - region.size = size; - CL_CHECK((trans = clCreateSubBuffer( - buf.buffer, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &src)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_int), &stride)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &rows)); - - size_t local_size[3] = {64, 1, 1}; - size_t global_size[3] = {(size_t)stride, (size_t)rows, 1};; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, - global_size, auto_local ? NULL : local_size, 0, NULL, NULL)); - - if (blocking) { - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, trans, dst, 0, 0, size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - } else { - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, trans, dst, 0, 0, size, 0, NULL, NULL)); - } - - CL_CHECK(clReleaseMemObject(trans)); -} - -static void transpose_2d_as_8b( - ggml_backend_opencl_context * backend_ctx, - cl_mem src, cl_mem dst, size_t size, - cl_int stride, cl_int rows, - bool blocking = true, - bool auto_local = false -) { - transpose_2d(backend_ctx, backend_ctx->kernel_transpose_8_buf, - src, dst, size, stride, rows, blocking, auto_local); -} - -static void transpose_2d_as_16b( - ggml_backend_opencl_context * backend_ctx, - cl_mem src, cl_mem dst, size_t size, - cl_int stride, cl_int rows, - bool blocking = true, - bool auto_local = false -) { - transpose_2d(backend_ctx, backend_ctx->kernel_transpose_16_buf, - src, dst, size, stride, rows, blocking, auto_local); -} - -static void transpose_2d_as_32b( - ggml_backend_opencl_context * backend_ctx, - cl_mem src, cl_mem dst, size_t size, - cl_int stride, cl_int rows, - bool blocking = true, - bool auto_local = false -) { - transpose_2d(backend_ctx, backend_ctx->kernel_transpose_32_buf, - src, dst, size, stride, rows, blocking, auto_local); -} -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -//------------------------------------------------------------------------------ -// Tensor extra management -//------------------------------------------------------------------------------ -struct ggml_tensor_extra_cl { - // The buffer object that holds the data. - cl_mem data_device; - // The offset into the buffer object. This is primarily for scratch buffer - // and view operation. - // NB: this offset no longer includes view offset (view_offs). Whenever this - // offset is used, view_offs should be considered. - cl_ulong offset; - // The actual size of the cl_mem object. This is needed when returning the - // block to the pool. - size_t actual_size; - - void reset() { - data_device = nullptr; - offset = 0; - actual_size = 0; - } -}; - -struct ggml_tensor_extra_cl_q1_0 { - cl_mem q = nullptr; - cl_mem q_img = nullptr; - - cl_mem d = nullptr; - cl_mem d_img = nullptr; - - size_t size_q = 0; - size_t size_d = 0; - - ~ggml_tensor_extra_cl_q1_0() { - reset(); - } - - void reset() { - // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. - // They must be properly released so that the original buffer can be - // properly released to avoid memory leak. - if (q != nullptr) { - CL_CHECK(clReleaseMemObject(q)); - q = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - q_img = nullptr; - d_img = nullptr; - size_q = 0; - size_d = 0; - } -}; - -// Additional tensor extra structs for quantized tensors. -// These tensors are loaded from files and should not be allocated in scratch -- -// they should always be allocated from the pool. Hence, they do not have an -// `offset`, which indicate their locations in the scratch buffer. -struct ggml_tensor_extra_cl_q4_0 { - // Quantized values. - cl_mem q = nullptr; - // Quantized values in image1d_buffer_t. - cl_mem q_img = nullptr; - // Scales. - cl_mem d = nullptr; - // Scales in image1d_buffer_t. - cl_mem d_img = nullptr; - // Size of quantized values. - size_t size_q = 0; - // Size of scales. - size_t size_d = 0; - - ~ggml_tensor_extra_cl_q4_0() { - reset(); - } - - void reset() { - // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. - // They must be properly released so that the original buffer can be - // properly released to avoid memory leak. - if (q != nullptr) { - CL_CHECK(clReleaseMemObject(q)); - q = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (q_img != nullptr) { - CL_CHECK(clReleaseMemObject(q_img)); - q_img = nullptr; - } - if (d_img != nullptr) { - CL_CHECK(clReleaseMemObject(d_img)); - d_img = nullptr; - } - size_q = 0; - size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_q4_1 { - // Quantized values. - cl_mem q = nullptr; - // Quantized values in image1d_buffer_t. - cl_mem q_img = nullptr; - // Scales. - cl_mem d = nullptr; - // Scales in image1d_buffer_t. - cl_mem d_img = nullptr; - // Min - cl_mem m = nullptr; - // Min in image1d_buffer_t. - cl_mem m_img = nullptr; - // Size of quantized values. - size_t size_q = 0; - // Size of scales. - size_t size_d = 0; - // Size of min values. - size_t size_m = 0; - - ~ggml_tensor_extra_cl_q4_1() { - reset(); - } - - void reset() { - // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. - // They must be properly released so that the original buffer can be - // properly released to avoid memory leak. - if (q != nullptr) { - CL_CHECK(clReleaseMemObject(q)); - q = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (m != nullptr) { - CL_CHECK(clReleaseMemObject(m)); - m = nullptr; - } - if (q_img != nullptr) { - CL_CHECK(clReleaseMemObject(q_img)); - q_img = nullptr; - } - // Currently, q_img and d_img are only initialized when SMALL_ALLOC is - // enabled. They point to the images in ggml_backend_opencl_buffer_context. - // So, there is no need to release them here. - // TODO: initialize them for non SMALL_PATH path, or remove them. - d_img = nullptr; - m_img = nullptr; - size_q = 0; - size_d = 0; - size_m = 0; - } -}; - -struct ggml_tensor_extra_cl_q5_0 { - // Quantized values. - cl_mem qs = nullptr; - // Quantized values in image1d_buffer_t. - cl_mem qs_img = nullptr; - // 5-th bit values. - cl_mem qh = nullptr; - // 5-th bit values in image1d_buffer_t. - cl_mem qh_img = nullptr; - // Scales. - cl_mem d = nullptr; - // Scales in image1d_buffer_t. - cl_mem d_img = nullptr; - // Uniform per-32-block scale (2/block) + min (1/block, = d*16 for the -16 centering) - // for the generic dp4a MoE GEMM. Built from d. - cl_mem scale = nullptr; - cl_mem min = nullptr; - // Size of quantized values. - size_t size_qs = 0; - // Size of 5-th bit values. - size_t size_qh = 0; - // Size of scales. - size_t size_d = 0; - - ~ggml_tensor_extra_cl_q5_0() { - reset(); - } - - void reset() { - if (qs != nullptr) { - CL_CHECK(clReleaseMemObject(qs)); - qs = nullptr; - } - if (qh != nullptr) { - CL_CHECK(clReleaseMemObject(qh)); - qh = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (qs_img != nullptr) { - CL_CHECK(clReleaseMemObject(qs_img)); - qs_img = nullptr; - } - if (scale != nullptr) { - CL_CHECK(clReleaseMemObject(scale)); - scale = nullptr; - } - if (min != nullptr) { - CL_CHECK(clReleaseMemObject(min)); - min = nullptr; - } - - qh_img = nullptr; - d_img = nullptr; - size_qs = 0; - size_qh = 0; - size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_q5_1 { - // Quantized values. - cl_mem qs = nullptr; - // Quantized values in image1d_buffer_t. - cl_mem qs_img = nullptr; - // 5-th bit values. - cl_mem qh = nullptr; - // 5-th bit values in image1d_buffer_t. - cl_mem qh_img = nullptr; - // Scales. - cl_mem d = nullptr; - // Scales in image1d_buffer_t. - cl_mem d_img = nullptr; - // Min - cl_mem m = nullptr; - // Min in image1d_buffer_t. - cl_mem m_img = nullptr; - // Size of quantized values. - size_t size_qs = 0; - // Size of 5-th bit values. - size_t size_qh = 0; - // Size of scales. - size_t size_d = 0; - // Size of min values. - size_t size_m = 0; - - ~ggml_tensor_extra_cl_q5_1() { - reset(); - } - - void reset() { - // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. - // They must be properly released so that the original buffer can be - // properly released to avoid memory leak. - if (qs != nullptr) { - CL_CHECK(clReleaseMemObject(qs)); - qs = nullptr; - } - if (qh != nullptr) { - CL_CHECK(clReleaseMemObject(qh)); - qh = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (m != nullptr) { - CL_CHECK(clReleaseMemObject(m)); - m = nullptr; - } - if (qs_img != nullptr) { - CL_CHECK(clReleaseMemObject(qs_img)); - qs_img = nullptr; - } - // qh_img, d_img, and m_img are not currently allocated separately. - // TODO: initialize them for non SMALL_PATH path, or remove them. - qh_img = nullptr; - d_img = nullptr; - m_img = nullptr; - size_qs = 0; - size_qh = 0; - size_d = 0; - size_m = 0; - } -}; - -struct ggml_tensor_extra_cl_mxfp4 { - // Quantized values. - cl_mem q = nullptr; - // Quantized values in image1d_buffer_t. - cl_mem q_img = nullptr; - // Scales in E8M0. - cl_mem e = nullptr; - // Scales in image1d_buffer_t. - cl_mem e_img = nullptr; - // Size of quantized values. - size_t size_q = 0; - // Size of scales. - size_t size_e = 0; - - ~ggml_tensor_extra_cl_mxfp4() { - reset(); - } - - void reset() { - // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. - // They must be properly released so that the original buffer can be - // properly released to avoid memory leak. - if (q != nullptr) { - CL_CHECK(clReleaseMemObject(q)); - q = nullptr; - } - if (e != nullptr) { - CL_CHECK(clReleaseMemObject(e)); - e = nullptr; - } - if (q_img != nullptr) { - CL_CHECK(clReleaseMemObject(q_img)); - q_img = nullptr; - } - // Currently, e_img is not used. They can be image1d_buffer_t - // that wraps around q and d to utilize image access path. - e_img = nullptr; - size_q = 0; - size_e = 0; - } -}; - -struct ggml_tensor_extra_cl_q8_0 { - cl_mem q = nullptr; - cl_mem q_img = nullptr; - - cl_mem d = nullptr; - cl_mem d_img = nullptr; - - // Uniform per-16-segment scale (16/superblock) for the generic dp4a MoE GEMM. - // Expanded from d at set_tensor; the int8 codes are reused from q. - // q8_0 is symmetric so no min buffer (has_min=0). - cl_mem scale = nullptr; - - size_t size_q = 0; - size_t size_d = 0; - - ~ggml_tensor_extra_cl_q8_0() { - reset(); - } - - void reset() { - // q and d are subbuffers into the bigger buffer allocated in ggml_backend_buffer. - // They must be properly released so that the original buffer can be - // properly released to avoid memory leak. - if (q != nullptr) { - CL_CHECK(clReleaseMemObject(q)); - q = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (scale != nullptr) { - CL_CHECK(clReleaseMemObject(scale)); - scale = nullptr; - } - // Currently, q_img and d_img are not used. They can be image1d_buffer_t - // that wraps around q and d to utilize image access path. - q_img = nullptr; - d_img = nullptr; - size_q = 0; - size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_iq4_nl { - cl_mem q = nullptr; - cl_mem q_img = nullptr; - - cl_mem d = nullptr; - cl_mem d_img = nullptr; - - size_t size_q = 0; - size_t size_d = 0; - - ~ggml_tensor_extra_cl_iq4_nl() { - reset(); - } - - void reset() { - if (q != nullptr) { CL_CHECK(clReleaseMemObject(q)); q = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - q_img = nullptr; - d_img = nullptr; - size_q = 0; - size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_q4_K { - // Quantized values - cl_mem q = nullptr; - // Quantized values in image1d_buffer_t. - cl_mem q_img = nullptr; - // Scales for each super block. - cl_mem s = nullptr; - // Scales - cl_mem d = nullptr; - // Min - cl_mem dm = nullptr; - - ~ggml_tensor_extra_cl_q4_K() { - reset(); - } - - void reset() { - if (q != nullptr) { - CL_CHECK(clReleaseMemObject(q)); - q = nullptr; - } - if (s != nullptr) { - CL_CHECK(clReleaseMemObject(s)); - s = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (dm != nullptr) { - CL_CHECK(clReleaseMemObject(dm)); - dm = nullptr; - } - if (q_img != nullptr) { - CL_CHECK(clReleaseMemObject(q_img)); - q_img = nullptr; - } - } -}; - -struct ggml_tensor_extra_cl_q5_K { - // Lower 4 bits of quantized weights. - cl_mem q = nullptr; - // Quantized values in image1d_buffer_t. - cl_mem q_img = nullptr; - // Upper 1 bit of quantized weights. - cl_mem qh = nullptr; - // Scales for each block. - cl_mem s = nullptr; - // Scales for each super block. - cl_mem d = nullptr; - // Min for each super block. - cl_mem dm = nullptr; - // Uniform per-32-block scale (2/block) + min (1/block, = dm*mn) decoded from the - // 6-bit packed s[] for the generic dp4a MoE GEMM kernel_gemm_moe_q8_1_dp4a. - // Built from s/d/dm at set_tensor; q/qh are reused as-is. - cl_mem scale = nullptr; - cl_mem min = nullptr; - - size_t size_q = 0; - size_t size_qh = 0; - size_t size_s = 0; - size_t size_d = 0; - size_t size_dm = 0; - - ~ggml_tensor_extra_cl_q5_K() { - reset(); - } - - void reset() { - if (q != nullptr) { - CL_CHECK(clReleaseMemObject(q)); - q = nullptr; - } - if (qh != nullptr) { - CL_CHECK(clReleaseMemObject(qh)); - qh = nullptr; - } - if (s != nullptr) { - CL_CHECK(clReleaseMemObject(s)); - s = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (dm != nullptr) { - CL_CHECK(clReleaseMemObject(dm)); - dm = nullptr; - } - if (q_img != nullptr) { - CL_CHECK(clReleaseMemObject(q_img)); - q_img = nullptr; - } - if (scale != nullptr) { - CL_CHECK(clReleaseMemObject(scale)); - scale = nullptr; - } - if (min != nullptr) { - CL_CHECK(clReleaseMemObject(min)); - min = nullptr; - } - - size_q = 0; - size_qh = 0; - size_s = 0; - size_d = 0; - size_dm = 0; - } -}; - -struct ggml_tensor_extra_cl_q2_K { - bool noshuffle = false; - cl_mem qs = nullptr; // quantized values - cl_mem sc = nullptr; // one uchar per 16 weights: scale nibble + min nibble - cl_mem dm = nullptr; // half2 per super-block: d, dmin - - size_t size_qs = 0, size_sc = 0, size_dm = 0; - - ~ggml_tensor_extra_cl_q2_K() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } - if (dm != nullptr) { CL_CHECK(clReleaseMemObject(dm)); dm = nullptr; } - size_qs = size_sc = size_dm = 0; - } -}; - -struct ggml_tensor_extra_cl_q3_K { - bool noshuffle = false; - cl_mem qs = nullptr; // quantized values - cl_mem hm = nullptr; // high bits - cl_mem sc = nullptr; // packed 6-bit scales - cl_mem d = nullptr; // super-block scales - - size_t size_qs = 0, size_hm = 0, size_sc = 0, size_d = 0; - - ~ggml_tensor_extra_cl_q3_K() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (hm != nullptr) { CL_CHECK(clReleaseMemObject(hm)); hm = nullptr; } - if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_hm = size_sc = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_iq3_xxs { - bool noshuffle = false; - cl_mem qs = nullptr; // grid indices - cl_mem sas = nullptr; // packed sign codes and scales - cl_mem d = nullptr; // super-block scales - - size_t size_qs = 0, size_sas = 0, size_d = 0; - - ~ggml_tensor_extra_cl_iq3_xxs() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (sas != nullptr) { CL_CHECK(clReleaseMemObject(sas)); sas = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_sas = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_iq3_s { - bool noshuffle = false; - cl_mem qs = nullptr; // grid index low bits - cl_mem sg = nullptr; // sign bits - cl_mem qh = nullptr; // grid index high bits - cl_mem sc = nullptr; // packed scales - cl_mem d = nullptr; // super-block scales - - size_t size_qs = 0, size_sg = 0, size_qh = 0, size_sc = 0, size_d = 0; - - ~ggml_tensor_extra_cl_iq3_s() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (sg != nullptr) { CL_CHECK(clReleaseMemObject(sg)); sg = nullptr; } - if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } - if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_sg = size_qh = size_sc = size_d = 0; - } -}; - - -struct ggml_tensor_extra_cl_iq2_xxs { - bool noshuffle = false; - cl_mem qs = nullptr; // grid indices - cl_mem sas = nullptr; // packed sign codes and scales - cl_mem d = nullptr; // super-block scales - - size_t size_qs = 0, size_sas = 0, size_d = 0; - - ~ggml_tensor_extra_cl_iq2_xxs() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (sas != nullptr) { CL_CHECK(clReleaseMemObject(sas)); sas = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_sas = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_iq2_xs { - bool noshuffle = false; - cl_mem qs = nullptr; // packed grid indices and sign codes - cl_mem sc = nullptr; // packed scales - cl_mem d = nullptr; // super-block scales - - size_t size_qs = 0, size_sc = 0, size_d = 0; - - ~ggml_tensor_extra_cl_iq2_xs() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_sc = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_iq2_s { - bool noshuffle = false; - cl_mem qs = nullptr; // grid index low bits - cl_mem sg = nullptr; // sign bits - cl_mem qh = nullptr; // grid index high bits - cl_mem sc = nullptr; // packed scales - cl_mem d = nullptr; // super-block scales - - size_t size_qs = 0, size_sg = 0, size_qh = 0, size_sc = 0, size_d = 0; - - ~ggml_tensor_extra_cl_iq2_s() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (sg != nullptr) { CL_CHECK(clReleaseMemObject(sg)); sg = nullptr; } - if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } - if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_sg = size_qh = size_sc = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_q2_0 { - bool noshuffle = false; - cl_mem qs = nullptr; - cl_mem d = nullptr; - - size_t size_qs = 0, size_d = 0; - - ~ggml_tensor_extra_cl_q2_0() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_iq1_s { - bool noshuffle = false; - cl_mem qs = nullptr; // grid indices - cl_mem qh = nullptr; // high grid bits, scales, and shifts - cl_mem d = nullptr; // super-block scales - - size_t size_qs = 0, size_qh = 0, size_d = 0; - - ~ggml_tensor_extra_cl_iq1_s() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_qh = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_iq1_m { - bool noshuffle = false; - cl_mem qs = nullptr; // grid indices - cl_mem qh = nullptr; // high grid bits and shifts - cl_mem sc = nullptr; // packed block and super-block scales - - size_t size_qs = 0, size_qh = 0, size_sc = 0; - - ~ggml_tensor_extra_cl_iq1_m() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (qh != nullptr) { CL_CHECK(clReleaseMemObject(qh)); qh = nullptr; } - if (sc != nullptr) { CL_CHECK(clReleaseMemObject(sc)); sc = nullptr; } - size_qs = size_qh = size_sc = 0; - } -}; - -struct ggml_tensor_extra_cl_iq4_xs { - bool noshuffle = false; - cl_mem qs = nullptr; - cl_mem sl = nullptr; - cl_mem sh = nullptr; - cl_mem d = nullptr; - - size_t size_qs = 0, size_sl = 0, size_sh = 0, size_d = 0; - - ~ggml_tensor_extra_cl_iq4_xs() { reset(); } - - void reset() { - noshuffle = false; - if (qs != nullptr) { CL_CHECK(clReleaseMemObject(qs)); qs = nullptr; } - if (sl != nullptr) { CL_CHECK(clReleaseMemObject(sl)); sl = nullptr; } - if (sh != nullptr) { CL_CHECK(clReleaseMemObject(sh)); sh = nullptr; } - if (d != nullptr) { CL_CHECK(clReleaseMemObject(d)); d = nullptr; } - size_qs = size_sl = size_sh = size_d = 0; - } -}; - -struct ggml_tensor_extra_cl_q6_K { - // Lower 4 bits of quantized weights. - cl_mem ql = nullptr; - // Lower 4 bits as image1d_buffer_t - cl_mem ql_img = nullptr; - // Upper 2 bits of quantized weights. - cl_mem qh = nullptr; - // Upper 2 bits as image1d_buffer_t - cl_mem qh_img = nullptr; - // Scales for each block. - cl_mem s = nullptr; - // Scales for each super block. - cl_mem d = nullptr; - - size_t size_ql = 0; - size_t size_qh = 0; - size_t size_s = 0; - size_t size_d = 0; - - ~ggml_tensor_extra_cl_q6_K() { - reset(); - } - - void reset() { - if (ql != nullptr) { - CL_CHECK(clReleaseMemObject(ql)); - ql = nullptr; - } - if (qh != nullptr) { - CL_CHECK(clReleaseMemObject(qh)); - qh = nullptr; - } - if (s != nullptr) { - CL_CHECK(clReleaseMemObject(s)); - s = nullptr; - } - if (d != nullptr) { - CL_CHECK(clReleaseMemObject(d)); - d = nullptr; - } - if (ql_img != nullptr) { - CL_CHECK(clReleaseMemObject(ql_img)); - ql_img = nullptr; - } - if (qh_img != nullptr) { - CL_CHECK(clReleaseMemObject(qh_img)); - qh_img = nullptr; - } - - size_ql = 0; - size_qh = 0; - size_s = 0; - size_d = 0; - } -}; - -//------------------------------------------------------------------------------ -// Backend API -//------------------------------------------------------------------------------ - -// -// backend -// -static const char * ggml_backend_opencl_name(ggml_backend_t backend) { - return "OpenCL"; - - UNUSED(backend); -} - -static void ggml_backend_opencl_free(ggml_backend_t backend) { - ggml_cl_free(backend); -} - -static void ggml_backend_opencl_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { - GGML_UNUSED(backend); - GGML_UNUSED(tensor); - GGML_UNUSED(data); - GGML_UNUSED(offset); - GGML_UNUSED(size); -} - -static void ggml_backend_opencl_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { - GGML_UNUSED(backend); - GGML_UNUSED(tensor); - GGML_UNUSED(data); - GGML_UNUSED(offset); - GGML_UNUSED(size); -} - -static bool ggml_backend_opencl_cpy_tensor_async(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) { - GGML_UNUSED(backend); - GGML_UNUSED(src); - GGML_UNUSED(dst); - return false; -} - -static void ggml_backend_opencl_synchronize(ggml_backend_t backend) { - auto * backend_ctx = static_cast(backend->context); - - cl_event evt; - CL_CHECK(clEnqueueBarrierWithWaitList(backend_ctx->queue, 0, nullptr, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); -} - -// Synchronizes the 'backend_ctx's device with others so that commands -// enqueued to it won't start until commands in the other devices have -// completed. -static void sync_with_other_backends(ggml_backend_opencl_context * backend_ctx) { - if (g_ggml_backend_opencl_devices.size() < 2) { - return; // No other devices to synchronize with. - } - - std::vector events; - events.reserve(g_ggml_backend_opencl_devices.size()); - - for (ggml_backend_device & backend_dev : g_ggml_backend_opencl_devices) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) backend_dev.context; - auto * other_backend_ctx = dev_ctx->backend_ctx; - - if (backend_ctx != other_backend_ctx) { - cl_event ev; - CL_CHECK(clEnqueueMarkerWithWaitList(other_backend_ctx->queue, 0, nullptr, &ev)); - CL_CHECK(clFlush(other_backend_ctx->queue)); - events.push_back(ev); - } - } - - CL_CHECK(clEnqueueBarrierWithWaitList(backend_ctx->queue, events.size(), events.data(), nullptr)); - for (auto ev : events) { - CL_CHECK(clReleaseEvent(ev)); - } -} - -static void sync_with_other_backends(ggml_backend_t backend) { - auto * backend_ctx = static_cast(backend->context); - sync_with_other_backends(backend_ctx); -} - -// True if two tensors share a device buffer with overlapping byte ranges. The pool -// allocator may place a fused op's output over a sequentially-dead input (safe for the -// original separate kernels, but a read/write race inside one fused kernel). -static bool ggml_cl_tensors_overlap(const ggml_tensor * x, const ggml_tensor * y) { - ggml_tensor_extra_cl * ex = (ggml_tensor_extra_cl *)x->extra; - ggml_tensor_extra_cl * ey = (ggml_tensor_extra_cl *)y->extra; - if (!ex || !ey || ex->data_device != ey->data_device) { return false; } - const cl_ulong xo = ex->offset + x->view_offs, xe = xo + ggml_nbytes(x); - const cl_ulong yo = ey->offset + y->view_offs, ye = yo + ggml_nbytes(y); - return xo < ye && yo < xe; -} - -// Detect the MoE combine epilogue: router-weight MUL ([n_embd,k,nt] * [1,k,nt]) followed -// by k VIEWs of it and a (k-1)-long ADD reduction chain producing [n_embd, nt]. When it -// matches (and the output does not alias the inputs), the whole subgraph collapses to one -// weighted-sum-across-experts kernel. -static bool ggml_opencl_can_fuse_moe_combine(const struct ggml_cgraph * cgraph, int node_idx, - const ggml_tensor ** out_final_add) { - const ggml_tensor * mul = cgraph->nodes[node_idx]; - if (mul->op != GGML_OP_MUL) { return false; } - const ggml_tensor * experts = mul->src[0]; - const ggml_tensor * weights = mul->src[1]; - if (!experts || !weights) { return false; } - if (experts->type != GGML_TYPE_F32 || weights->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32) { return false; } - - const int64_t n_embd = experts->ne[0]; - const int64_t k = experts->ne[1]; - const int64_t nt = experts->ne[2]; - if (k < 2 || k > 64 || experts->ne[3] != 1 || n_embd % 4 != 0) { return false; } - if (weights->ne[0] != 1 || weights->ne[1] != k || weights->ne[2] != nt || weights->ne[3] != 1) { return false; } - if (mul->ne[0] != n_embd || mul->ne[1] != k || mul->ne[2] != nt) { return false; } - // the fused kernel needs contiguous experts/weights and a contiguous 2D dst - if (!ggml_is_contiguous(experts) || !ggml_is_contiguous(weights)) { return false; } - - const int n_nodes = 1 + (int)k + (int)(k - 1); // MUL + k*VIEW + (k-1)*ADD - if (n_nodes >= 32) { return false; } - if (node_idx + n_nodes > cgraph->n_nodes) { return false; } - - enum ggml_op ops[1 + 64 + 63]; - int n = 0; - ops[n++] = GGML_OP_MUL; - for (int j = 0; j < (int)k; ++j) { ops[n++] = GGML_OP_VIEW; } - for (int j = 0; j < (int)k - 1; ++j) { ops[n++] = GGML_OP_ADD; } - const int outs[] = { node_idx + n_nodes - 1 }; - if (!ggml_can_fuse_subgraph(cgraph, node_idx, n_nodes, ops, outs, 1)) { return false; } - - for (int j = 0; j < (int)k; ++j) { - const ggml_tensor * vw = cgraph->nodes[node_idx + 1 + j]; - if (vw->op != GGML_OP_VIEW || vw->src[0] != mul || vw->ne[0] != n_embd || vw->ne[1] != nt) { return false; } - } - const ggml_tensor * final_add = cgraph->nodes[node_idx + n_nodes - 1]; - if (final_add->op != GGML_OP_ADD || final_add->type != GGML_TYPE_F32 || - final_add->ne[0] != n_embd || final_add->ne[1] != nt || final_add->ne[2] != 1) { return false; } - if (!ggml_is_contiguous(final_add)) { return false; } - // the fused kernel reads experts + writes final_add in one pass; bail if the - // pool allocator overlapped the output with the (large) experts input -- would race. - // The small weights input is copied to a private scratch in the dispatch, so its own - // aliasing with the output is handled there and does not block the fusion. - if (ggml_cl_tensors_overlap(experts, final_add)) { return false; } - - *out_final_add = final_add; - return true; -} - -// Detect the gpt-oss MoE bias+activation epilogue on the PREFILL path: -// {MUL_MAT_ID(gate), ADD_ID(gate_bias), MUL_MAT_ID(up), ADD_ID(up_bias), GLU(swiglu_oai)}. -// The two matmuls still run as their own dispatches (the prefill GEMM is the vendor's); -// what collapses is the epilogue — both add_id passes are in-place read-modify-writes of a -// tensor the GLU immediately reads again, so they are three full passes over the same -// [n_ff, n_expert_used, n_tokens] f32 tensor where one suffices. -// -// The decode counterpart is handled by the mxfp4 fused GEMV arm in ggml_opencl_can_fuse, -// which folds the matmul too; this one deliberately fires only when that cannot (ne[2] > 1). -static bool ggml_opencl_can_fuse_moe_bias_glu(const struct ggml_cgraph * cgraph, int node_idx) { - if (node_idx + 4 >= cgraph->n_nodes) { - return false; - } - - const enum ggml_op mg_ops[] = { GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_MUL_MAT_ID, GGML_OP_ADD_ID, GGML_OP_GLU }; - const int mg_out[] = { node_idx + 4 }; - if (!ggml_can_fuse_subgraph(cgraph, node_idx, 5, mg_ops, mg_out, 1)) { - return false; - } - - const ggml_tensor * gmm = cgraph->nodes[node_idx]; - const ggml_tensor * gad = cgraph->nodes[node_idx+1]; - const ggml_tensor * umm = cgraph->nodes[node_idx+2]; - const ggml_tensor * uad = cgraph->nodes[node_idx+3]; - const ggml_tensor * glu = cgraph->nodes[node_idx+4]; - - if (ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU_OAI) { - return false; - } - // Prefill only — at one token the mxfp4 arm above folds the matmul as well. - if (gmm->src[1]->ne[2] == 1) { - return false; - } - // Wiring: both matmuls share the activation and the expert selection, each add_id - // biases its own matmul, and the GLU consumes the two biased results as separate - // operands (so the same-buffer ne00_off/ne10_off split path is not in play). - if (gad->src[0] != gmm || uad->src[0] != umm || - glu->src[0] != gad || glu->src[1] != uad || - umm->src[1] != gmm->src[1] || umm->src[2] != gmm->src[2]) { - return false; - } - // A swapped GLU would exchange the gate/up roles the fused kernel hard-codes. - if (ggml_get_op_params_i32(glu, 1)) { - return false; - } - if (gad->type != GGML_TYPE_F32 || uad->type != GGML_TYPE_F32 || glu->type != GGML_TYPE_F32) { - return false; - } - if (!gad->src[1] || gad->src[1]->type != GGML_TYPE_F32 || - !uad->src[1] || uad->src[1]->type != GGML_TYPE_F32) { - return false; - } - if (!gad->src[2] || gad->src[2]->type != GGML_TYPE_I32 || uad->src[2] != gad->src[2]) { - return false; - } - // Full width on both operands: the kernel writes one output element per input pair. - if (!ggml_are_same_shape(gad, uad) || glu->ne[0] != gad->ne[0] || - glu->ne[1] != gad->ne[1] || glu->ne[2] != gad->ne[2] || glu->ne[3] != gad->ne[3]) { - return false; - } - if (gad->ne[3] != 1) { - return false; - } - // The destination is addressed by (expert slot, token) rather than the GLU's flat row - // walk; those agree only for a contiguous destination. - if (!ggml_is_contiguous(glu) || !ggml_is_contiguous(gmm) || !ggml_is_contiguous(umm)) { - return false; - } - return true; -} - -// Run a malu int8 (dp4a ila malu bin) MoE GEMM: fused reorder + q8_1 quant of the activations, then the GEMM. -// The weight buffers come first in the kernel args, in the order of the ns kernel of the same type. -// use_sa: the kernel takes the q8_1 block sums (min types), or an unused buffer in that slot (q4_0). -static void ggml_cl_moe_gemm_malu_bin( - ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, std::initializer_list weights, bool use_sa, - cl_mem sub_buf_src1_pre, cl_mem buf_src2, cl_mem buf_src2_emap, - cl_mem dst_data, cl_ulong offsetd, size_t n_dst, const ggml_tensor * dst, - int ne00, int ne01, unsigned short map_ratio, int max_post_router_tile, int n_tile_size) { - cl_int status; - - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - cl_uint ne00_u = ne00; - cl_uint tile_u = n_tile_size; - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00_u)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &tile_u)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - // dst as an image - cl_buffer_region region; - region.origin = offsetd; - region.size = n_dst * sizeof(float); - cl_mem sub_buf_dst = clCreateSubBuffer(dst_data, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, n_dst, 0,0,0,0,0,0,0, {sub_buf_dst}}; - cl_mem buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - int aidx = 0; - for (cl_mem w : weights) { - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &w)); - } - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - if (use_sa) { - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - } - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); -} - -// Run a cl_qcom_kernel_cooperative_matrix MoE GEMM: f16 reorder of the activations, then the GEMM. -// The weight buffers come first in the kernel args, in the order of the ns kernel of the same type. -static void ggml_cl_moe_gemm_coopmat( - ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, std::initializer_list weights, - cl_mem sub_buf_src1_pre, cl_mem buf_src2, cl_mem buf_src2_emap, - cl_mem dst_data, cl_ulong offsetd, size_t n_dst, const ggml_tensor * dst, - int ne00, int ne01, unsigned short map_ratio, int max_post_router_tile, int n_tile_size) { - cl_int status; - - // f16 reordered activations, read by the coopmat kernel as a buffer - cl_buffer_region region; - region.origin = 0; - region.size = (size_t)ne00 * max_post_router_tile * n_tile_size * sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - cl_mem buf_src1_reordered = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - cl_kernel rk = backend_ctx->kernel_moe_reorder_b_f16; - unsigned int ne00_u = ne00; - unsigned int tile_u = n_tile_size; - CL_CHECK(clSetKernelArg(rk, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rk, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rk, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(rk, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rk, 4, sizeof(unsigned int), &ne00_u)); - CL_CHECK(clSetKernelArg(rk, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(rk, 6, sizeof(unsigned int), &tile_u)); - - size_t rk_local_size[3] = {256, 1, 1}; - size_t rk_global_size[3] = {(size_t)(((ne00 / 8) + 255) / 256 * 256), (size_t)max_post_router_tile * n_tile_size, 1}; - backend_ctx->enqueue_ndrange_kernel(rk, 3, rk_global_size, rk_local_size, dst); - - // dst as an image - region.origin = offsetd; - region.size = n_dst * sizeof(float); - cl_mem sub_buf_dst = clCreateSubBuffer(dst_data, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, n_dst, 0,0,0,0,0,0,0, {sub_buf_dst}}; - cl_mem buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - int arg_idx = 0; - for (cl_mem w : weights) { - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &w)); - } - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // coopmat kernels need a uniform NDRange - size_t global_size[3] = {64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile}; - size_t local_size[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); -} - -static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); - -// Runs the gate and up matmuls unchanged, then one kernel in place of -// add_id(gate) + add_id(up) + swiglu_oai. See ggml_opencl_can_fuse_moe_bias_glu. -static void ggml_cl_moe_bias_glu_fused(ggml_backend_t backend, ggml_tensor * gate_mm, const ggml_tensor * gate_add, - ggml_tensor * up_mm, const ggml_tensor * up_add, const ggml_tensor * glu) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_cl_mul_mat_ext(backend, gate_mm->src[0], gate_mm->src[1], gate_mm); - ggml_cl_mul_mat_ext(backend, up_mm->src[0], up_mm->src[1], up_mm); - - const ggml_tensor * gbias = gate_add->src[1]; - const ggml_tensor * ubias = up_add->src[1]; - const ggml_tensor * ids = gate_add->src[2]; - - ggml_tensor_extra_cl * eg = (ggml_tensor_extra_cl *)gate_mm->extra; - ggml_tensor_extra_cl * egb = (ggml_tensor_extra_cl *)gbias->extra; - ggml_tensor_extra_cl * eu = (ggml_tensor_extra_cl *)up_mm->extra; - ggml_tensor_extra_cl * eub = (ggml_tensor_extra_cl *)ubias->extra; - ggml_tensor_extra_cl * ei = (ggml_tensor_extra_cl *)ids->extra; - ggml_tensor_extra_cl * ed = (ggml_tensor_extra_cl *)glu->extra; - - cl_ulong off_g = eg->offset + gate_mm->view_offs; - cl_ulong off_gb = egb->offset + gbias->view_offs; - cl_ulong off_u = eu->offset + up_mm->view_offs; - cl_ulong off_ub = eub->offset + ubias->view_offs; - cl_ulong off_i = ei->offset + ids->view_offs; - cl_ulong off_d = ed->offset + glu->view_offs; - - const cl_ulong nb01_g = gate_mm->nb[1]; - const cl_ulong nb02_g = gate_mm->nb[2]; - const cl_ulong nb01_u = up_mm->nb[1]; - const cl_ulong nb02_u = up_mm->nb[2]; - const cl_ulong nb11_g = gbias->nb[1]; - const cl_ulong nb11_u = ubias->nb[1]; - const cl_ulong nb21 = ids->nb[1]; - const cl_ulong nbd1 = glu->nb[1]; - const cl_ulong nbd2 = glu->nb[2]; - - const int ne0 = (int)glu->ne[0]; - const float alpha = ggml_get_op_params_f32(glu, 2); - const float limit = ggml_get_op_params_f32(glu, 3); - - cl_kernel kernel = backend_ctx->kernel_add_id_add_id_swiglu_oai; - - int i = 0; - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &eg->data_device)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_g)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &egb->data_device)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_gb)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &eu->data_device)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_u)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &eub->data_device)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_ub)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &ei->data_device)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_i)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &ed->data_device)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_d)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb01_g)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb02_g)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb01_u)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb02_u)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb11_g)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb11_u)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nbd1)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nbd2)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(float), &limit)); - CL_CHECK(clSetKernelArg(kernel, i++, sizeof(float), &alpha)); - - const int nth = MIN(ne0, (int) backend_ctx->get_kernel_workgroup_size(kernel)); - size_t global_work_size[] = { (size_t)glu->ne[1]*nth, (size_t)glu->ne[2], 1 }; - size_t local_work_size[] = { (size_t)nth, 1, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, glu); -} - -// Fusion B: the MoE down-projection bias add feeding the combine. -// -// The graph runs ADD_ID(down_bias) and then immediately the combine subgraph -// {MUL(router weights), k VIEWs, k-1 ADDs}, and the ADD_ID's only consumer is that -// MUL. Since the ADD_ID is an in-place read-modify-write of a tensor the combine -// reads once more, the bias can be added inside the combine instead, dropping a -// full pass over [n_embd, k, n_tokens]. -// -// Shape checks for the combine tail are delegated to ggml_opencl_can_fuse_moe_combine -// (which also owns the n_nodes >= 32 bail and the experts/dst aliasing bail); what is -// added here is the ADD_ID wiring plus a subgraph check over the WHOLE run, so that -// the intermediate bias result is confirmed not to escape. -static bool ggml_opencl_can_fuse_moe_bias_combine(const struct ggml_cgraph * cgraph, int node_idx, - const ggml_tensor ** out_final_add) { - if (node_idx + 1 >= cgraph->n_nodes) { - return false; - } - const ggml_tensor * add = cgraph->nodes[node_idx]; - if (add->op != GGML_OP_ADD_ID) { - return false; - } - const ggml_tensor * mul = cgraph->nodes[node_idx+1]; - if (mul->op != GGML_OP_MUL || mul->src[0] != add) { - return false; - } - - const ggml_tensor * final_add = NULL; - if (!ggml_opencl_can_fuse_moe_combine(cgraph, node_idx+1, &final_add)) { - return false; - } - - const ggml_tensor * raw = add->src[0]; - const ggml_tensor * bias = add->src[1]; - const ggml_tensor * ids = add->src[2]; - if (!raw || !bias || !ids) { - return false; - } - if (raw->type != GGML_TYPE_F32 || bias->type != GGML_TYPE_F32 || - ids->type != GGML_TYPE_I32 || add->type != GGML_TYPE_F32) { - return false; - } - // The combine reads the raw matmul output with the strides it computed from the - // add_id result, so the two must have the same layout. - if (!ggml_are_same_shape(raw, add) || !ggml_is_contiguous(raw)) { - return false; - } - if (raw->nb[1] != add->nb[1] || raw->nb[2] != add->nb[2]) { - return false; - } - // ids is indexed as [expert slot, token]; the combine walks the same two axes. - if (ids->ne[0] < add->ne[1] || ids->ne[1] < add->ne[2]) { - return false; - } - - // Whole-run escape check: ADD_ID + MUL + k VIEWs + (k-1) ADDs, only the last node escapes. - const int k = (int)add->ne[1]; - const int n_nodes = 2 + k + (k - 1); - if (n_nodes >= 32 || node_idx + n_nodes > cgraph->n_nodes) { - return false; - } - enum ggml_op ops[32]; - int n = 0; - ops[n++] = GGML_OP_ADD_ID; - ops[n++] = GGML_OP_MUL; - for (int j = 0; j < k; ++j) ops[n++] = GGML_OP_VIEW; - for (int j = 0; j < k - 1; ++j) ops[n++] = GGML_OP_ADD; - const int outs[] = { node_idx + n_nodes - 1 }; - if (!ggml_can_fuse_subgraph(cgraph, node_idx, n_nodes, ops, outs, 1)) { - return false; - } - - *out_final_add = final_add; - return true; -} - - -// Fusion B dispatch: the combine, reading the RAW matmul output and adding the -// per-expert bias row inline. See ggml_opencl_can_fuse_moe_bias_combine. -static void ggml_cl_moe_bias_combine_fused(ggml_backend_t backend, const ggml_tensor * add, - const ggml_tensor * mul, const ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - - const ggml_tensor * experts = add->src[0]; // raw matmul output, bias not yet applied - const ggml_tensor * bias = add->src[1]; - const ggml_tensor * ids = add->src[2]; - const ggml_tensor * weights = mul->src[1]; - - ggml_tensor_extra_cl * ee = (ggml_tensor_extra_cl *)experts->extra; - ggml_tensor_extra_cl * eb = (ggml_tensor_extra_cl *)bias->extra; - ggml_tensor_extra_cl * ei = (ggml_tensor_extra_cl *)ids->extra; - ggml_tensor_extra_cl * ew = (ggml_tensor_extra_cl *)weights->extra; - ggml_tensor_extra_cl * ed = (ggml_tensor_extra_cl *)dst->extra; - cl_ulong off_e = ee->offset + experts->view_offs; - cl_ulong off_b = eb->offset + bias->view_offs; - cl_ulong off_i = ei->offset + ids->view_offs; - cl_ulong off_w = ew->offset + weights->view_offs; - cl_ulong off_d = ed->offset + dst->view_offs; - - const int n_embd4 = (int)(experts->ne[0] / 4); - const int k = (int)experts->ne[1]; - const int nt = (int)experts->ne[2]; - const cl_uint e1 = (cl_uint)(experts->nb[1] / sizeof(float)); - const cl_uint e2 = (cl_uint)(experts->nb[2] / sizeof(float)); - const cl_uint w1 = (cl_uint)(weights->nb[1] / sizeof(float)); - const cl_uint w2 = (cl_uint)(weights->nb[2] / sizeof(float)); - const cl_uint d1 = (cl_uint)(dst->nb[1] / sizeof(float)); - const cl_ulong nb_b1 = bias->nb[1]; - const cl_ulong nb_i1 = ids->nb[1]; - - const size_t w_bytes = ggml_nbytes(weights); - backend_ctx->prealloc_moe_combine_w.allocate(backend_ctx->context, w_bytes); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, ew->data_device, backend_ctx->prealloc_moe_combine_w.buffer, - off_w, 0, w_bytes, 0, NULL, NULL)); - cl_mem w_dev = backend_ctx->prealloc_moe_combine_w.buffer; - cl_ulong w_off = 0; - - cl_kernel kernel = backend_ctx->kernel_moe_combine_bias_f32; - int a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &ee->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_e)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &w_dev)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &w_off)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &eb->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_b)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &ei->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &ed->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_d)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_embd4)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nt)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &e1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &e2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &w1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &w2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &d1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb_b1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb_i1)); - - size_t lws[2] = { 64, 1 }; - size_t gws[2] = { (size_t)(((n_embd4 + 63) / 64) * 64), (size_t)nt }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, gws, lws, dst); -} - - -static void ggml_cl_moe_combine_fused(ggml_backend_t backend, const ggml_tensor * mul, const ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - const ggml_tensor * experts = mul->src[0]; - const ggml_tensor * weights = mul->src[1]; - - ggml_tensor_extra_cl * ee = (ggml_tensor_extra_cl *)experts->extra; - ggml_tensor_extra_cl * ew = (ggml_tensor_extra_cl *)weights->extra; - ggml_tensor_extra_cl * ed = (ggml_tensor_extra_cl *)dst->extra; - cl_ulong off_e = ee->offset + experts->view_offs; - cl_ulong off_w = ew->offset + weights->view_offs; - cl_ulong off_d = ed->offset + dst->view_offs; - - const int n_embd4 = (int)(experts->ne[0] / 4); - const int k = (int)experts->ne[1]; - const int nt = (int)experts->ne[2]; - const cl_uint e1 = (cl_uint)(experts->nb[1] / sizeof(float)); - const cl_uint e2 = (cl_uint)(experts->nb[2] / sizeof(float)); - const cl_uint w1 = (cl_uint)(weights->nb[1] / sizeof(float)); - const cl_uint w2 = (cl_uint)(weights->nb[2] / sizeof(float)); - const cl_uint d1 = (cl_uint)(dst->nb[1] / sizeof(float)); - - // The router weights are tiny ([1,k,nt]) and may share a pool buffer with the output; - // copy them into a private scratch so the fused kernel never reads aliased memory. - const size_t w_bytes = ggml_nbytes(weights); - backend_ctx->prealloc_moe_combine_w.allocate(backend_ctx->context, w_bytes); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, ew->data_device, backend_ctx->prealloc_moe_combine_w.buffer, - off_w, 0, w_bytes, 0, NULL, NULL)); - cl_mem w_dev = backend_ctx->prealloc_moe_combine_w.buffer; - cl_ulong w_off = 0; - - cl_kernel kernel = backend_ctx->kernel_moe_combine_f32; - int a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &ee->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_e)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &w_dev)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &w_off)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &ed->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_d)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_embd4)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nt)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &e1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &e2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &w1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &w2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &d1)); - - size_t lws[2] = { 64, 1 }; - size_t gws[2] = { (size_t)(((n_embd4 + 63) / 64) * 64), (size_t)nt }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, gws, lws, dst); -} - -inline bool use_q4k_tiled(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor); // defined below (used by the GLU-subgraph fuse check) -inline bool use_q4_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor); -inline bool use_adreno_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor); // defined below - -static bool ggml_opencl_can_fuse(const ggml_backend_opencl_context * backend_ctx, const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list ops) { - - // glu(mul_mat(Wg,x), mul_mat(Wu,x)) — the FFN gate/up GEMVs + GLU. This is a - // non-linear subgraph (up does NOT consume gate), so the contiguous - // ggml_can_fuse below rejects it; use ggml_can_fuse_subgraph with the glu as - // the sole output and validate the edges explicitly. q4_K decode only; - // byte-identical to the per-op path. - if (ops.size() == 3 && ops.begin()[0] == GGML_OP_MUL_MAT && - ops.begin()[1] == GGML_OP_MUL_MAT && ops.begin()[2] == GGML_OP_GLU) { - const enum ggml_op glu_ops[] = { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU }; - const int glu_out[] = { node_idx + 2 }; - if (!ggml_can_fuse_subgraph(cgraph, node_idx, 3, glu_ops, glu_out, 1)) { - return false; - } - - const ggml_tensor *gate = cgraph->nodes[node_idx]; - const ggml_tensor *up = cgraph->nodes[node_idx+1]; - const ggml_tensor *glu = cgraph->nodes[node_idx+2]; - - if (ggml_get_src_scale(gate, 0) || ggml_get_src_scale(up, 0)) { - return false; - } - - // decode GEMV path only (single token); prefill GEMM is separate - if (gate->ne[1] != 1 || up->ne[1] != 1) { - return false; - } - // both projections must be q4_K weights, f32 activation/output - if (gate->src[0]->type != GGML_TYPE_Q4_K || up->src[0]->type != GGML_TYPE_Q4_K || - gate->src[1]->type != GGML_TYPE_F32 || up->src[1]->type != GGML_TYPE_F32 || - gate->type != GGML_TYPE_F32 || up->type != GGML_TYPE_F32 || glu->type != GGML_TYPE_F32) { - return false; - } - // gate and up must share the same activation and have matching shape/stride - if (gate->src[1] != up->src[1] || - !ggml_are_same_shape(gate->src[0], up->src[0]) || - !ggml_are_same_stride(gate->src[0], up->src[0])) { - return false; - } - // GLU must read gate as src[0] and up as src[1], no swap (the fused - // epilogue applies the activation to gate, multiplies by up) - if (glu->src[0] != gate || glu->src[1] != up) { - return false; - } - if (ggml_get_op_params_i32(glu, 1) /* swapped */) { - return false; - } - // SWIGLU_OAI carries extra alpha/limit params -> not handled by the fused kernel - if (ggml_get_glu_op(glu) == GGML_GLU_OP_SWIGLU_OAI) { - return false; - } - // the fused kernel reads the standard noshuffle image layout; the tiled - // layout packs weights differently -> defer those to the per-op path - if (use_q4k_tiled(backend_ctx, gate->src[0]) || use_q4k_tiled(backend_ctx, up->src[0])) { - return false; - } - // q4_K bin kernel requires 32b transposed layout, not compatible with the fused gemv - if (use_q4_k_bin_kernels(backend_ctx, gate->src[0]) || use_q4_k_bin_kernels(backend_ctx, up->src[0])) { - return false; - } - // that noshuffle layout is only produced at set_tensor time when - // use_adreno_kernels() accepts the weight (ne0 >= 512 && ne1 >= 512). - // Smaller weights stay in the plain q4_K layout, which this kernel would - // misread -> defer them to the per-op path. Real FFN gate/up weights are - // far above the threshold, so production dispatch is unchanged. - if (!use_adreno_kernels(backend_ctx, gate->src[0]) || - !use_adreno_kernels(backend_ctx, up->src[0])) { - return false; - } - return true; - } - - if (!ggml_can_fuse(cgraph, node_idx, ops)) { - return false; - } - - if (ops.size() == 2 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) { - const ggml_tensor *rms_norm = cgraph->nodes[node_idx]; - const ggml_tensor *mul = cgraph->nodes[node_idx+1]; - - GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32); - GGML_ASSERT(rms_norm->type == GGML_TYPE_F32); - - // rms_norm only supports f32 - if (mul->src[0]->type != GGML_TYPE_F32 || - mul->src[1]->type != GGML_TYPE_F32 || - mul->type != GGML_TYPE_F32) { - return false; - } - - // if rms_norm is the B operand, then we don't handle broadcast - if (rms_norm == mul->src[1] && - !ggml_are_same_shape(mul->src[0], rms_norm)) { - return false; - } - - // rms_norm assumes contiguous rows - if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1])) { - return false; - } - } else if (ops.size() == 3 && ops.begin()[0] == GGML_OP_NORM && ops.begin()[1] == GGML_OP_MUL && ops.begin()[2] == GGML_OP_ADD) { - const ggml_tensor *norm = cgraph->nodes[node_idx]; - const ggml_tensor *mul = cgraph->nodes[node_idx+1]; - const ggml_tensor *add = cgraph->nodes[node_idx+2]; - const ggml_tensor *w = mul->src[0] == norm ? mul->src[1] : mul->src[0]; - const ggml_tensor *b = add->src[0] == mul ? add->src[1] : add->src[0]; - - // norm fusion only supports F32 - if (norm->src[0]->type != GGML_TYPE_F32 || w->type != GGML_TYPE_F32 || b->type != GGML_TYPE_F32) { - return false; - } - - if (norm->src[0]->ne[0] % 4 != 0) { - return false; - } - - if (!ggml_is_contiguous(norm->src[0]) || !ggml_is_contiguous(w) || !ggml_is_contiguous(b)) { - return false; - } - } else if (ops.size() == 3 && ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL && ops.begin()[2] == GGML_OP_ADD) { - // rms_norm(x) * w + b, fused (residual). Mirrors the RMS_NORM+MUL gate - // plus the residual-add operand's constraints. - const ggml_tensor *rms_norm = cgraph->nodes[node_idx]; - const ggml_tensor *mul = cgraph->nodes[node_idx+1]; - const ggml_tensor *add = cgraph->nodes[node_idx+2]; - const ggml_tensor *w = mul->src[0] == rms_norm ? mul->src[1] : mul->src[0]; - const ggml_tensor *b = add->src[0] == mul ? add->src[1] : add->src[0]; - - GGML_ASSERT(rms_norm->src[0]->type == GGML_TYPE_F32); - GGML_ASSERT(rms_norm->type == GGML_TYPE_F32); - - if (w->type != GGML_TYPE_F32 || mul->type != GGML_TYPE_F32 || - b->type != GGML_TYPE_F32 || add->type != GGML_TYPE_F32) { - return false; - } - if (rms_norm->src[0]->ne[0] % 4 != 0) { - return false; - } - // if rms_norm is the B operand of mul, broadcast is not handled - if (rms_norm == mul->src[1] && !ggml_are_same_shape(mul->src[0], rms_norm)) { - return false; - } - // the residual must match the normed output shape (no add broadcast) - if (!ggml_are_same_shape(b, add)) { - return false; - } - // rms_norm assumes contiguous rows - if (!ggml_is_contiguous_rows(mul->src[0]) || !ggml_is_contiguous_rows(mul->src[1]) || - !ggml_is_contiguous_rows(b)) { - return false; - } - } else if (ops.size() == 3 && ops.begin()[0] == GGML_OP_GROUP_NORM && ops.begin()[1] == GGML_OP_MUL && ops.begin()[2] == GGML_OP_ADD) { - const ggml_tensor *gn = cgraph->nodes[node_idx]; - const ggml_tensor *mul = cgraph->nodes[node_idx+1]; - const ggml_tensor *add = cgraph->nodes[node_idx+2]; - const ggml_tensor *w = mul->src[0] == gn ? mul->src[1] : mul->src[0]; - const ggml_tensor *b = add->src[0] == mul ? add->src[1] : add->src[0]; - - if (gn->src[0]->type != GGML_TYPE_F32 || w->type != GGML_TYPE_F32 || b->type != GGML_TYPE_F32) { - return false; - } - - if (!ggml_is_contiguous(gn->src[0]) || !ggml_is_contiguous(w) || !ggml_is_contiguous(b)) { - return false; - } - } - - return true; -} - -static void ggml_opencl_op_rms_norm_fused(ggml_backend_t backend, ggml_tensor * rms_norm_tensor, ggml_tensor * mul_tensor); -static void ggml_opencl_op_norm_fused(ggml_backend_t backend, ggml_tensor * norm_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor); -static void ggml_opencl_op_group_norm_fused(ggml_backend_t backend, ggml_tensor * gn_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor); - -static void ggml_cl_mul_mat_q4_k_glu_fused(ggml_backend_t backend, ggml_tensor * gate_tensor, ggml_tensor * up_tensor, ggml_tensor * glu_tensor) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(gate_tensor && up_tensor && glu_tensor); - - const ggml_tensor * Wg = gate_tensor->src[0]; - const ggml_tensor * Wu = up_tensor->src[0]; - const ggml_tensor * src1 = gate_tensor->src[1]; // == up_tensor->src[1] - const ggml_tensor * dst = glu_tensor; - - GGML_ASSERT(Wg && Wg->extra); - GGML_ASSERT(Wu && Wu->extra); - GGML_ASSERT(src1 && src1->extra); - GGML_ASSERT(dst && dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q4_K * extra_g = (ggml_tensor_extra_cl_q4_K *)Wg->extra; - ggml_tensor_extra_cl_q4_K * extra_u = (ggml_tensor_extra_cl_q4_K *)Wu->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int K = Wg->ne[0]; // ne00 - const int M = Wg->ne[1]; // ne01 (= ffn intermediate width) - const int N = 1; // decode GEMV - - const cl_uchar mask_d6 = 0x3F, mask_d4 = 0x0F, mask_hi2 = 0xC0; - const int glu_op = (int)ggml_get_glu_op(dst); - - cl_context context = backend_ctx->context; - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - // q images for the two weight matrices (standard noshuffle layout) - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * K / 2 / 4; - img_desc.buffer = extra_g->q; - cl_mem qg_img = nullptr, qu_img = nullptr; - CL_CHECK((qg_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - img_desc.buffer = extra_u->q; - CL_CHECK((qu_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // shared activation image (one column at decode) - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - cl_mem b_sub_buf = nullptr, b_img = nullptr; - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - img_fmt = { CL_RGBA, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_gemv_noshuffle_q4_k_f32_glu; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qg_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra_g->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_g->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra_g->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &qu_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra_u->d)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra_u->dm)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extra_u->s)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_int), &K)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_int), &glu_op)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_uchar), &mask_hi2)); - - // K-split = nsg_y subgroups. HARD-CAP at 8 (512 work-items): the fused - // kernel's cross-subgroup reduce uses a float4 reduceLM (gate+up packed) = - // 2x the LDS of the base GEMV's float2 reduce, so 16 co-resident subgroups - // exceed the per-CU LDS budget on X2 and the WG barrier DEADLOCKS -> GPU TDR - // (reproduced on upstream gemma-4 E4B decode, K=2560 M=10240). This used to - // be masked: get_kernel_workgroup_size reported 896 for this kernel (so the - // cap loop fell to 8), but it now returns 1024 and the Adreno per-kernel WG - // query is unreliable (over-reports), so cap explicitly instead of trusting - // it. nsg_y < 16 also means the cross-subgroup accumulation grouping differs - // from the standalone wide (nsg=16) GEMV, so the output is coherent but NOT - // byte-identical to the per-op path. Keep the maxwg query as a further floor - // for any driver that reports < 512. - size_t maxwg = backend_ctx->get_kernel_workgroup_size(kernel); - // X2E: 4 is faster than 8 on every q4_K FFN shape measured there - size_t nsg_y = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 4 : 8; - while (nsg_y > 1 && 64 * nsg_y > maxwg) { nsg_y >>= 1; } - size_t local_work_size[3] = { 64, nsg_y, 1 }; - size_t global_work_size[3] = { (size_t)CEIL_DIV(M / 2, 64) * 64, nsg_y, 1 }; - - if (getenv("GGML_OPENCL_FUSE_DEBUG")) { - static int dbg = 0; - if (dbg < 3) { fprintf(stderr, "[FUSE_MM_GLU] fired #%d K=%d M=%d glu_op=%d nsg=%zu maxwg=%zu\n", ++dbg, K, M, glu_op, nsg_y, maxwg); fflush(stderr); } - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(qg_img)); - CL_CHECK(clReleaseMemObject(qu_img)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -#else - GGML_UNUSED(backend); - GGML_UNUSED(gate_tensor); - GGML_UNUSED(up_tensor); - GGML_UNUSED(glu_tensor); -#endif -} - - -static void ggml_opencl_op_rms_norm_mul_add_fused(ggml_backend_t backend, ggml_tensor * rms_norm_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor) { - GGML_ASSERT(rms_norm_tensor && mul_tensor && add_tensor); - - const ggml_tensor * src0 = rms_norm_tensor->src[0]; - const ggml_tensor * src1 = mul_tensor->src[0] == rms_norm_tensor ? mul_tensor->src[1] : mul_tensor->src[0]; - const ggml_tensor * src2 = add_tensor->src[0] == mul_tensor ? add_tensor->src[1] : add_tensor->src[0]; - const ggml_tensor * dst = add_tensor; - - GGML_ASSERT(src0 && src0->extra); - GGML_ASSERT(src1 && src1->extra); - GGML_ASSERT(src2 && src2->extra); - GGML_ASSERT(dst && dst->extra); - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offset2 = extra2->offset + src2->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - float eps; - memcpy(&eps, rms_norm_tensor->op_params, sizeof(float)); - - const int ne00 = src0->ne[0], ne01 = src0->ne[1], ne02 = src0->ne[2], ne03 = src0->ne[3]; - const cl_ulong nb01 = src0->nb[1], nb02 = src0->nb[2], nb03 = src0->nb[3]; - const int ne10 = src1->ne[0], ne11 = src1->ne[1], ne12 = src1->ne[2], ne13 = src1->ne[3]; - const cl_ulong nb11 = src1->nb[1], nb12 = src1->nb[2], nb13 = src1->nb[3]; - const int ne20 = src2->ne[0], ne21 = src2->ne[1], ne22 = src2->ne[2], ne23 = src2->ne[3]; - const cl_ulong nb21 = src2->nb[1], nb22 = src2->nb[2], nb23 = src2->nb[3]; - const cl_ulong nb1 = dst->nb[1], nb2 = dst->nb[2], nb3 = dst->nb[3]; - - GGML_ASSERT(ne00 % 4 == 0); - - size_t sgs; - if (backend_ctx->gpu_family == ADRENO) sgs = 64; - else if (backend_ctx->gpu_family == INTEL) sgs = 32; - else GGML_ASSERT(false && "Unsupported GPU"); - - cl_kernel kernel = backend_ctx->kernel_rms_norm_mul_add; - - int nth = sgs; - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - while (nth < ne00 && nth < max_workgroup_size) nth *= 2; - nth = MIN(nth, max_workgroup_size); - nth = MIN(nth, ne00); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne22)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne23)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb22)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb23)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 32, sizeof(float), &eps)); - CL_CHECK(clSetKernelArg(kernel, 33, sizeof(float)*sgs, NULL)); - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static ggml_status ggml_backend_opencl_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) { - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - for (int i = 0; i < cgraph->n_nodes; i++) { - ggml_tensor * node = cgraph->nodes[i]; - - // NOTE: this may oversynchronize by synchronizing with - // backends/devices which don't compute 'cgraph's - // dependencies. - sync_with_other_backends(backend); - - if (ggml_is_empty(node) || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_TRANSPOSE || node->op == GGML_OP_VIEW || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_NONE) { - continue; - } - - if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { - continue; - } - - if (!backend_ctx->disable_fusion && ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_NORM, GGML_OP_MUL, GGML_OP_ADD })) { - ggml_opencl_op_norm_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); - i += 2; - continue; - } - if (!backend_ctx->disable_fusion && ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_GROUP_NORM, GGML_OP_MUL, GGML_OP_ADD })) { - ggml_opencl_op_group_norm_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); - i += 2; - continue; - } - // Fuse the MoE combine: router-weight mul + cross-expert add chain -> - // one weighted-sum-across-experts kernel. - // Fold the gpt-oss MoE bias epilogue: add_id(gate_bias) + add_id(up_bias) + - // glu(swiglu_oai) -> one kernel, leaving the two matmuls as their own dispatches. - // Both add_ids are in-place passes over a tensor the GLU reads again, so this - // drops two full read+write passes per layer. Opt out GGML_OPENCL_FUSE_MOE_BIAS_GLU=0. - if (backend_ctx->fuse_moe_bias_glu && !backend_ctx->disable_fusion && - ggml_opencl_can_fuse_moe_bias_glu(cgraph, i)) { - ggml_cl_moe_bias_glu_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2], - cgraph->nodes[i+3], cgraph->nodes[i+4]); - i += 4; - continue; - } - - // Fold the MoE down-projection bias into the combine: add_id(down_bias) + the whole - // combine subgraph -> one kernel. Checked before the plain combine arm so the longer - // pattern wins. Opt out GGML_OPENCL_FUSE_MOE_BIAS_COMBINE=0. - if (backend_ctx->fuse_moe_bias_combine && backend_ctx->fuse_moe_combine && - !backend_ctx->disable_fusion) { - const ggml_tensor * bias_combine_out = nullptr; - if (ggml_opencl_can_fuse_moe_bias_combine(cgraph, i, &bias_combine_out)) { - ggml_cl_moe_bias_combine_fused(backend, node, cgraph->nodes[i+1], bias_combine_out); - i += 2 * (int)node->ne[1]; // ADD_ID + MUL + k VIEWs + (k-1) ADDs - continue; - } - } - - if (backend_ctx->fuse_moe_combine && !backend_ctx->disable_fusion) { - const ggml_tensor * combine_out = nullptr; - if (ggml_opencl_can_fuse_moe_combine(cgraph, i, &combine_out)) { - ggml_cl_moe_combine_fused(backend, node, combine_out); - i += 2 * (int)node->ne[1] - 1; // skip the k VIEWs + (k-1) ADDs - continue; - } - } - - // Fuse rms_norm + mul(weight) + add(residual). Checked before the - // rms_norm+mul fuse so the 3-op pattern wins over its 2-op prefix. - // Default on, opt-out GGML_OPENCL_FUSE_RMS_ADD=0. - if (!backend_ctx->disable_fusion && backend_ctx->fuse_rms_add && - ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL, GGML_OP_ADD })) { - ggml_opencl_op_rms_norm_mul_add_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); - i += 2; - continue; - } - if (!backend_ctx->disable_fusion && ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_RMS_NORM, GGML_OP_MUL })) { - ggml_opencl_op_rms_norm_fused(backend, node, cgraph->nodes[i+1]); - i++; - continue; - } - // Fuse mul_mat(Wg,x) + mul_mat(Wu,x) + glu — fold the FFN's two decode - // GEMVs and the GLU into one dispatch. q4_K only (guarded below); the - // fused kernel uses the same accumulation/reduction order and the same - // scalar GLU formula -> coherent. Default on, opt-out GGML_OPENCL_FUSE_MM_GLU=0. -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // The fused executor (ggml_cl_mul_mat_q4_k_glu_fused) is image-path / - // Adreno-only (GGML_ABORT on the non-Adreno #else); gate the dispatch to - // match so the FFN GLU subgraph stays dormant on Intel/other drivers. - if (backend_ctx->fuse_mm_glu && !backend_ctx->disable_fusion && - ggml_opencl_can_fuse(backend_ctx, cgraph, i, { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT, GGML_OP_GLU })) { - ggml_cl_mul_mat_q4_k_glu_fused(backend, node, cgraph->nodes[i+1], cgraph->nodes[i+2]); - i += 2; - continue; - } -#endif - - bool ok = ggml_cl_compute_forward(backend, node); - if (!ok) { - GGML_LOG_ERROR("%s: error: op not supported %s (%s)\n", __func__, node->name, ggml_op_name(node->op)); - } - GGML_ASSERT(ok); - } - - return GGML_STATUS_SUCCESS; -} - -// The optimized gemm and gemv kernels are used for large matrices without batch. -// tensor is the quantized weights matrix. -inline bool use_adreno_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - int64_t threshold_ne0 = 512; - int64_t threshold_ne1 = 512; - if (!backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 38, 11, 0) && - backend_ctx->adreno_cl_compiler_version.type != DX) { - threshold_ne0 = 128; - threshold_ne1 = 128; - } - // K floor 256 on X2E: the gemma-4 E2B/E4B MTP drafters' weights are all K = 256. - // Default on for X2E, GGML_OPENCL_K_FLOOR_256=0/1 forces it. - static const char * k_floor_256_env = getenv("GGML_OPENCL_K_FLOOR_256"); - const bool k_floor_256 = k_floor_256_env ? atoi(k_floor_256_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; - if (k_floor_256 && threshold_ne0 > 256) { - threshold_ne0 = 256; - } - bool threashold_ok = tensor->ne[0] >= threshold_ne0 && tensor->ne[1] >= threshold_ne1 && - tensor->ne[2] == 1 && tensor->ne[3] == 1; - - // the transposed layout needs K % 32 == 0 and M % 4 == 0 - if (tensor->ne[0] % 32 != 0 || tensor->ne[1] % 4 != 0) { - return false; - } - - // The noshuffle layout packs 2 rows per 32-bit texel and the GEMV reads it at an - // ne1/2 texel stride with an exact-cover dispatch, so it is only addressable when - // ne1 is a multiple of 64; an unaligned ne1 truncates the stride and the weight is - // read misaligned. That is a property of the layout, not of one quant -- q4_K, q5_K - // and q8_0 read the same packing as q6_K. The bound is 64, not 128: a q8_0 attention - // weight of ne1 = 2880 is a multiple of 64 but not 128 and is correct. - switch (tensor->type) { - case GGML_TYPE_Q4_K: - case GGML_TYPE_Q5_K: - case GGML_TYPE_Q6_K: - case GGML_TYPE_Q8_0: - return threashold_ok && tensor->ne[1] % 64 == 0; - default: - break; - } - return threashold_ok; -} - -static bool adreno_e17_compiler_quirks(const ggml_backend_opencl_context *backend_ctx) { - if (!backend_ctx || backend_ctx->gpu_family != GPU_FAMILY::ADRENO || - backend_ctx->adreno_cl_compiler_version.type != ADRENO_CL_COMPILER_TYPE::E17) { - return false; - } - - static const bool enabled = []() { - const char * e = getenv("GGML_OPENCL_ADRENO_E17_QUIRKS"); - return e && e[0] && e[0] != '0'; - }(); - return enabled; -} - -static bool ggml_cl_q2_k_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_Q2_K_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_Q2_K && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_q3_k_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_Q3_K_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_Q3_K && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq4_xs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ4_XS_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ4_XS && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq3_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ3_S_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ3_S && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq3_xxs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ3_XXS_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ3_XXS && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq1_m_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ1_M_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ1_M && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq1_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ1_S_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ1_S && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_q2_0_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_Q2_0_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_Q2_0 && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq2_s_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ2_S_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ2_S && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq2_xs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ2_XS_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ2_XS && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_iq2_xxs_use_noshuffle(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * tensor) { -#if defined(GGML_OPENCL_SOA_Q) && defined(GGML_OPENCL_USE_ADRENO_KERNELS) - if (const char * env = getenv("GGML_OPENCL_IQ2_XXS_NOSHUFFLE")) { - if (env[0] == '0') { - return false; - } - } - return tensor->type == GGML_TYPE_IQ2_XXS && - backend_ctx->gpu_family == ADRENO && - ggml_is_contiguous(tensor) && !tensor->view_src && - use_adreno_kernels(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -inline bool use_adreno_moe_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - // The moe weight repack kernels *_trans4_ns alias a private ushort8 through a uchar*. - // Certain compilers (found with some A7x and A6x) miscompiles this, corrupting the weights. - // So, exclude A6x and A7x from using Adreno MoE kernels for now. - // The quants that have a general mul_mat_id kernel fallback to the general version; the - // rest fallback to CPU. - if (backend_ctx && (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::ADRENO_UNKNOWN)) { - return false; - } - - if (adreno_e17_compiler_quirks(backend_ctx)) { - return false; - } - - int ne01 = tensor->ne[1]; - return (((strstr(tensor->name, "ffn") != NULL) && (strstr(tensor->name, "exps") != NULL)) || (strstr(tensor->name, "as") != NULL)) && (ne01 % 32 == 0); -} - -// Device default for the tiled-wide lm_head/embed GEMV layout: ON for X2E and A8X. -// -// These kernels were previously off everywhere on the grounds that they compute -// wrong values at multi-superblock K. They do not: that NMSE ~2 came from the -// backend having no get_tensor restore path for the tiled layout, so -// test-backend-ops (which builds its CPU reference by copying the weights back -// out of the backend) compared a correct GPU result against a reference -// dequantized from tiled bytes. With the restore path added, MUL_MAT passes with -// the tiled kernels on, unmodified, on both devices. -// -// Perf, Qwen3-4B-Q4_K_M (q6_K lm_head 151936x2560), tg128, matched pairs with -// alternating lead, tiled vs o4: -// -// A8X +11.9% 6/6 pairs positive, order bias -0.06% (16.93 vs 15.14 tok/s) -// X2E +6.9% 4/4 pairs positive, order bias -0.03% (35.24 vs 32.87 tok/s) -// -// Measure this one on a COLD device. These kernels are far more clock-sensitive -// than the o4 route they replace: on a heat-soaked A8X (CPU cap at 1.5-1.9 GHz) -// tiled pins at ~14.2 tok/s while o4 still makes ~14.9, which reads as a 4-5% -// LOSS and inverts the ranking. The same box, after a reboot and a gate that -// waits for policy6 to return to 4396800, reports the +11.9% above with no -// order bias. A7X regresses hard on this layout and stays off. -// GGML_OPENCL_{Q4K,Q6K}_GEMV_TILED forces either way (=0 off, any other value on). -inline bool tiled_gemv_default_on(const ggml_backend_opencl_context *backend_ctx) { - return backend_ctx && (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X); -} - -// Tiled-wide q6_K GEMV (default OFF; GGML_OPENCL_Q6K_GEMV_TILED forces either -// way: =0 off everywhere, any other value on everywhere). -// Both the convert (set_tensor) and the GEMV dispatch must agree on this so the -// buffer layout matches the kernel. -inline bool q6k_gemv_tiled_enabled(const ggml_backend_opencl_context *backend_ctx) { - static const char * e = std::getenv("GGML_OPENCL_Q6K_GEMV_TILED"); - if (e && e[0] != '\0') { - return e[0] != '0'; - } - return tiled_gemv_default_on(backend_ctx); -} - -// Only the long-vocab lm_head/embed shapes use the tiled layout; ne01 % 64 == 0 -// is required by the 64-row tiling (no row padding in the buffers). -// use_adreno_kernels is required: only the Adreno GEMV path can read the tiled -// layout, so converting a weight it would decline (e.g. ne00 < 512) leaves the -// generic kernel reading tiled bytes as plain SOA. -inline bool use_q6k_tiled(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - return q6k_gemv_tiled_enabled(backend_ctx) && tensor->type == GGML_TYPE_Q6_K && - tensor->ne[1] >= 32768 && tensor->ne[1] % 64 == 0 && - use_adreno_kernels(backend_ctx, tensor); -} - -// Select untiled Q4_K before upload if the batched DP4A reader is unavailable. -inline bool q4k_gemv_tiled_enabled(const ggml_backend_opencl_context *backend_ctx) { - if (!backend_ctx->has_integer_dot) { - return false; - } - static const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_TILED"); - if (e && e[0] != '\0') { - return e[0] != '0'; - } - return tiled_gemv_default_on(backend_ctx); -} -inline bool use_q4k_tiled(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - return q4k_gemv_tiled_enabled(backend_ctx) && tensor->type == GGML_TYPE_Q4_K && - tensor->ne[1] >= 32768 && tensor->ne[1] % 64 == 0 && - use_adreno_kernels(backend_ctx, tensor); -} - -inline bool enable_adreno_trans_weight(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - - bool adreno_kernel = use_adreno_kernels(backend_ctx, tensor); - - size_t elem_num = tensor->ne[0] * tensor->ne[1] * tensor->ne[2] * tensor->ne[3]; - - // The 2D weight transpose (transpose_2d_as_*) tiles rows by 4 over a 2D matrix, - // so it requires K(ne0)%32==0, M(ne1)%4==0 and ne2==ne3==1. - const bool shape_ok = (tensor->ne[0] % 32 == 0) && (tensor->ne[1] % 4 == 0) && - (tensor->ne[2] == 1) && (tensor->ne[3] == 1); - - return ((elem_num < 128 * 1024 * 1024) && adreno_kernel && shape_ok); // max element num: 2**27 -} - -inline bool enable_adreno_trans_weight_q5_K(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - if (!use_adreno_kernels(backend_ctx, tensor)) { - return false; - } - - const size_t elem_num = ggml_nelements(tensor); - const size_t q_img_width = elem_num / 8; - const size_t qh_img_width = elem_num / 16; - const bool shape_ok = tensor->ne[0] % 32 == 0 && tensor->ne[1] % 4 == 0 && - tensor->ne[2] == 1 && tensor->ne[3] == 1; - - return shape_ok && q_img_width <= backend_ctx->image_max_buffer_size && - qh_img_width <= backend_ctx->image_max_buffer_size; -} - -inline bool use_q4_0_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (!backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans || - !(backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin || - backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat)) { - return false; - } - - // bin kernels require ne2 == 1 and ne3 == 1 for weights - return tensor->ne[2] == 1 && tensor->ne[3] == 1 && - (tensor->ne[0] % 32 == 0) && (tensor->ne[1] % 64 == 0); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static bool use_fa_bin_kernels_prefill(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v) { - if (backend_ctx->fa.kernel_flash_attn_f32_f16_bin == nullptr) { - return false; - } - - const bool is_mixed = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16; - const bool is_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0; - - const int n_q = q->ne[1]; - const int dk = q->ne[0]; - const int dv = v->ne[0]; - - // do not choose bin FA kernels to avoid repacking the KV cache for small - // verify batches on X2 - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && is_mixed && - (dk == 256 || dk == 512) && n_q <= 4) { - return false; - } - - constexpr bool prefill_only = true; - - // The repacked Q/K/V are 3D images: Q {n_q, n_batch*n_head, dk/4}, K {dk, n_kv/4, n_batch*n_head_kv}, - // V {n_kv, dv/4, n_batch*n_head_kv}. Past the device's 3D image limits clCreateImage fails and the - // call asserts (X2-90: V is n_kv wide, so any prefill past ~16k tokens of context), so decline those shapes. - const size_t n_kv = (size_t) k->ne[1]; - const size_t n_bh = (size_t) q->ne[3] * (size_t) q->ne[2]; - const size_t n_bhkv = (size_t) q->ne[3] * (size_t) k->ne[2]; - if ((size_t) n_q > backend_ctx->image3d_max_width || n_bh > backend_ctx->image3d_max_height || - (size_t) dk / 4 > backend_ctx->image3d_max_depth || - (size_t) dk > backend_ctx->image3d_max_width || (n_kv + 3) / 4 > backend_ctx->image3d_max_height || - n_kv > backend_ctx->image3d_max_width || (size_t) dv / 4 > backend_ctx->image3d_max_height || - n_bhkv > backend_ctx->image3d_max_depth) { - return false; - } - - // q8_0 K/V at DK=512 gives wrong results here when V differs from K (f16 K/V is correct). - // Decline it, as this backend does without the kernel library. - if (is_q8_0 && dk == 512) { - return false; - } - - return (backend_ctx->gpu_family == GPU_FAMILY::ADRENO && - (is_mixed || is_q8_0) && (dk == dv) - && (dk == 64 || dk == 128 || dk == 256 || dk == 512) - && (!prefill_only || n_q != 1)); -} -#endif - -// The flat-GEMV large-m escape is OPT-IN (GGML_OPENCL_FLAT_LARGE_M=1) because it -// is SLOWER than the route it replaces, not because it is unsafe. It was first -// parked on the theory that it out-of-bounds-writes at vocab-scale shapes; that -// was a misattribution (the test-backend-ops dst sentinel was tripped by the o4 -// GEMV's unguarded tail store, fixed separately - and at the shape it was blamed -// for, k=1536, this predicate returns false anyway, so the flat route never ran). -// -// The escape's original rationale, "gemv_noshuffle perf drops for large M", -// predates the o4 kernel, which now covers the same long-vocab shapes and beats -// this route on every device measured (Qwen3-4B-Q4_K_M, q6_K lm_head -// 151936x2560, tg128, matched pairs vs o4): A8X -10.3% (0/3 pairs), X2E -3.7% -// (0/3). Keep it reachable for shapes o4 declines, but do not default it on. -static inline bool flat_large_m_enabled() { - static const char * e = getenv("GGML_OPENCL_FLAT_LARGE_M"); - static const bool en = e != nullptr && atoi(e) != 0; - return en; -} - -// The noshuffle Q4_K weight image stores eight weights per uint texel. -static inline bool q4_K_weight_image_fits(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - const size_t texels = (size_t) ggml_nelements(tensor) / 8; - return texels != 0 && texels <= backend_ctx->image_max_buffer_size; -} - -static inline bool use_flat_gemv_for_large_m_q4_K(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - if (tensor->ne[1] % 4 != 0 && tensor->ne[2] == 1 && tensor->ne[3] == 1) { - return true; - } - - if (tensor->ne[2] != 1 || tensor->ne[3] != 1 || use_q4k_tiled(backend_ctx, tensor)) { - return false; - } - - // The image limit is a correctness guard, independent of the large-M opt-in. - if (!q4_K_weight_image_fits(backend_ctx, tensor)) { - return true; - } - - // gemv_noshuffle variant perf drops for large M, use flat variant for large M. - // threshold is well above typical hidden/FFN dims, but below typical vocab sizes. - // note that this forces large M weights to use LM GEMM. - return flat_large_m_enabled() && tensor->ne[1] >= 32768; -} - -static inline bool use_flat_gemv_for_large_m_q6_K(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { - // NOTE on ordering: the ne01 % 128 escape below is a CORRECTNESS guard, not a - // performance one, so it must be reachable regardless of flat_large_m_enabled(). - // The opt-in gate therefore sits after it, and after the tiled deferral. - // gemv_noshuffle variant perf drops for large M, use flat variant for large M. - // threshold is well above typical hidden/FFN dims, but below typical vocab sizes. - // q6_K flat gemv is worse for smaller K; 2048 seems to be a reasonable threshold. - // note that this forces large M weights to use LM GEMM. - // When this branch's tiled-canonical lm_head/embed layout is active, the weight is - // converted to the 64-row tiled layout, which the flat gemv would misread as - // garbage. use_q6k_tiled owns these large-M weights (it requires ne01 % 64 == 0, - // so it never claims an odd-vocab weight), so defer to it first. - if (use_q6k_tiled(backend_ctx, tensor)) { - return false; - } - // The noshuffle (transposed-weight) layout packs 2 rows per 32-bit texel and the - // gemv reads it with a ne01/2 texel stride and an exact-cover dispatch of - // ceil(ne01/2 / 64)*64 work-items with no store guard; the gemm uses 4-row tiles. - // It is therefore only correct for ne01 % 128 == 0: an odd ne01 (e.g. granitemoe - // lm_head [1536, 49155] -- odd vocab) truncates the texel stride, misaligning every - // odd column of the transposed layout (gross garbage) and dropping the last row; - // other non-multiples over-dispatch and write past the end of dst. Route such - // tensors to the flat GEMV + regular convert; the matching GEMM (ne1>1) falls back - // to CPU (see supports_op). All standard even-vocab/hidden dims are multiples of - // 128 and keep the noshuffle path. - if ((tensor->ne[1] % 128 != 0) && tensor->ne[2] == 1 && tensor->ne[3] == 1) { - return true; - } - - if (!flat_large_m_enabled()) { - return false; - } - - // The gemv_noshuffle slowdown tracks TOTAL weight size, not ne0 alone; ne0 >= 2048 is a - // proxy for "large weight" that misses a narrow-hidden vocab-scale lm_head. - // Add a direct size escape so such weights also take the flat path, without changing - // which weights ne0 >= 2048 already routes there. - // The size escape is not taken on the A7X since its compiler miscompiles the flat K-quant GEMV - return tensor->ne[1] >= 32768 - && (tensor->ne[0] >= 2048 || (backend_ctx->adreno_gen != ADRENO_GPU_GEN::A7X && ggml_nbytes(tensor) >= (256ull << 20))) - && tensor->ne[2] == 1 && tensor->ne[3] == 1; -} - -inline bool use_q6_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (!backend_ctx->kernel_gemv_noshuffle_q6_k_f32_32b_trans || - !(backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin || - backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat)) { - return false; - } - // bin kernels require ne2 == 1 and ne3 == 1 for weights - return tensor->ne[2] == 1 && tensor->ne[3] == 1 && - (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0) && - !use_q6k_tiled(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -inline bool use_q4_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (!backend_ctx->kernel_gemv_noshuffle_q4_k_f32_32b_trans || - !(backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin || - backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat)) { - return false; - } - // bin kernels require ne2 == 1 and ne3 == 1 for weights - return tensor->ne[2] == 1 && tensor->ne[3] == 1 && - (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0) && - !use_q4k_tiled(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -inline bool use_q5_k_bin_kernels(const ggml_backend_opencl_context *backend_ctx, const ggml_tensor *tensor) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (!backend_ctx->kernel_gemv_noshuffle_q5_k_f32_32b_trans || - !(backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin || - backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin || - backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat)) { - return false; - } - return (tensor->ne[0] % 256 == 0) && (tensor->ne[1] % 64 == 0); -#else - GGML_UNUSED(backend_ctx); - GGML_UNUSED(tensor); - return false; -#endif -} - -static bool ggml_cl_mul_mat_can_use_fwht(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * op) { - const ggml_tensor * a = op->src[0]; - const ggml_tensor * b = op->src[1]; - const int64_t n = a->ne[0]; - - return ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD && - a->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && - (b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16) && - n >= 2 && n <= std::numeric_limits::max() && (n & (n - 1)) == 0 && a->ne[1] == n && - (uint64_t)n <= backend_ctx->local_mem_size/sizeof(float) && - ggml_is_contiguous_rows(b) && ggml_is_contiguous(op) && ggml_are_same_shape(b, op); -} - -static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *)dev->context; - ggml_backend_opencl_context * backend_ctx = dev_ctx->backend_ctx; - - // reject ops that match the opfilter regex - if (dev_ctx->opfilter && std::regex_match(std::string(ggml_op_desc(op)), *dev_ctx->opfilter)) { - return false; - } - - switch (op->op) { - case GGML_OP_NONE: - return true; - case GGML_OP_GET_ROWS: - switch (op->src[0]->type) { - case GGML_TYPE_I32: - return op->type == GGML_TYPE_I32; - case GGML_TYPE_F32: - case GGML_TYPE_F16: - return true; - case GGML_TYPE_Q4_0: -#ifdef GGML_OPENCL_SOA_Q - // We do not support flattened Q4_0 (and possibly other Q's) - return false; -#else // GGML_OPENCL_SOA_Q - return true; -#endif // GGML_OPENCL_SOA_Q - default: - return false; - } - case GGML_OP_SET_ROWS: - { - // TODO: add support - // ref: https://github.com/ggml-org/llama.cpp/pull/14274 -#pragma message("TODO: implement BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, IQ4_NL support (https://github.com/ggml-org/llama.cpp/pull/14661)") - if (op->src[0]->type != GGML_TYPE_F32) { - return false; - } - switch (op->type) { - case GGML_TYPE_F16: - case GGML_TYPE_F32: - case GGML_TYPE_Q8_0: - case GGML_TYPE_Q4_0: - return (op->src[1]->type == GGML_TYPE_I64 || op->src[1]->type == GGML_TYPE_I32); - default: - return false; - } - } - case GGML_OP_CPY: - case GGML_OP_DUP: - case GGML_OP_CONT: - switch (op->src[0]->type) { - case GGML_TYPE_F32: - switch (op->type) { - case GGML_TYPE_I32: - case GGML_TYPE_F16: - case GGML_TYPE_F32: - return true; - default: - return false; - } - case GGML_TYPE_F16: - switch (op->type) { - case GGML_TYPE_F16: - case GGML_TYPE_F32: - return true; - default: - return false; - } - case GGML_TYPE_I32: - switch (op->type) { - case GGML_TYPE_F32: - case GGML_TYPE_I32: - return true; - default: - return false; - } - default: - return false; - } - case GGML_OP_SET: { - return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_I32) && - op->type == op->src[0]->type && - op->type == op->src[1]->type; - } - case GGML_OP_SCALE: - return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && - op->src[0]->type == op->type && ggml_is_contiguous_rows(op->src[0]); - case GGML_OP_ADD: - if (op->type == GGML_TYPE_F16) { - const bool src0_ok = op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32; - const bool src1_ok = op->src[1]->type == GGML_TYPE_F16 || op->src[1]->type == GGML_TYPE_F32; - if (src0_ok && src1_ok) { - return true; - } - } - case GGML_OP_MUL: - case GGML_OP_DIV: - case GGML_OP_SUB: - return (op->src[0]->type == op->src[1]->type) && - (op->src[0]->type == op->type) && - (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); - case GGML_OP_ADD_ID: - return op->src[0]->type == GGML_TYPE_F32; - case GGML_OP_LOG: - return op->src[0]->type == op->type && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); - case GGML_OP_SQR: - case GGML_OP_SQRT: - return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && - ggml_is_contiguous(op->src[0]); - case GGML_OP_UNARY: - switch (ggml_get_unary_op(op)) { - case GGML_UNARY_OP_SILU: - return op->src[0]->type == op->type && - (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); - case GGML_UNARY_OP_XIELU: - for (int64_t ne : op->src[0]->ne) { - if (ne > INT_MAX) { - return false; - } - } - return op->src[0]->type == op->type && - (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); - case GGML_UNARY_OP_GELU: - case GGML_UNARY_OP_RELU: - case GGML_UNARY_OP_GELU_ERF: - case GGML_UNARY_OP_GELU_QUICK: - return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; - case GGML_UNARY_OP_SIGMOID: - return op->src[0]->type == op->type && - (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_BF16); - case GGML_UNARY_OP_TANH: - case GGML_UNARY_OP_NEG: - case GGML_UNARY_OP_EXP: - // Adreno F16 exp/expm1 overflow even post-half->float convert. - return op->src[0]->type == GGML_TYPE_F32; - case GGML_UNARY_OP_EXPM1: - return op->src[0]->type == GGML_TYPE_F32; - case GGML_UNARY_OP_ABS: - case GGML_UNARY_OP_SGN: - case GGML_UNARY_OP_STEP: - case GGML_UNARY_OP_ELU: - case GGML_UNARY_OP_HARDSWISH: - case GGML_UNARY_OP_HARDSIGMOID: - case GGML_UNARY_OP_FLOOR: - case GGML_UNARY_OP_CEIL: - case GGML_UNARY_OP_ROUND: - case GGML_UNARY_OP_TRUNC: - return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; - case GGML_UNARY_OP_SOFTPLUS: - return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; - default: - return false; - } - case GGML_OP_GLU: - switch (ggml_get_glu_op(op)) { - case GGML_GLU_OP_GEGLU: - case GGML_GLU_OP_REGLU: - case GGML_GLU_OP_SWIGLU: - case GGML_GLU_OP_SWIGLU_OAI: - case GGML_GLU_OP_GEGLU_ERF: - case GGML_GLU_OP_GEGLU_QUICK: - case GGML_GLU_OP_SWIGLU_CLAMP: - return ggml_is_contiguous_1(op->src[0]) && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); - default: - return false; - } - case GGML_OP_TRI: - return op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); - case GGML_OP_FILL: - return op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); - case GGML_OP_ARANGE: - return op->type == GGML_TYPE_F32; - case GGML_OP_CLAMP: - return op->src[0]->type == GGML_TYPE_F32; - case GGML_OP_SOFT_MAX: - case GGML_OP_NORM: - return true; - case GGML_OP_RMS_NORM: - return op->src[0]->type == GGML_TYPE_F32 && op->ne[0] % 4 == 0 && ggml_is_contiguous_rows(op->src[0]); - case GGML_OP_L2_NORM: - return ggml_is_contiguous_rows(op->src[0]); - case GGML_OP_REPEAT: - switch (op->type) { - case GGML_TYPE_F32: - case GGML_TYPE_F16: - case GGML_TYPE_I32: - case GGML_TYPE_I16: - case GGML_TYPE_BF16: - return op->src[0]->type == op->type; - default: - return false; - } - case GGML_OP_PAD: - // TODO: add circular padding support for opencl, see https://github.com/ggml-org/llama.cpp/pull/16985 - if (ggml_get_op_params_i32(op, 8) != 0) { - return false; - } - return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; - case GGML_OP_UPSCALE: { - ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(op, 0) & 0xFF); - const bool antialias = (ggml_scale_mode)(ggml_get_op_params_i32(op, 0) & GGML_SCALE_FLAG_ANTIALIAS); - return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && - (mode == GGML_SCALE_MODE_NEAREST || mode == GGML_SCALE_MODE_BILINEAR) && !antialias; - } - case GGML_OP_CONV_2D: - return (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16 && op->type == GGML_TYPE_F16) || - (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32) || - (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32); - case GGML_OP_CONV_2D_DW: - return op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && - op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && - op->src[1]->nb[0] == sizeof(float) && op->nb[0] == sizeof(float) && - (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); - case GGML_OP_SSM_CONV: - return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32); - case GGML_OP_SSM_SCAN: { - if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32 || - op->src[1]->type != GGML_TYPE_F32 || op->src[2]->type != GGML_TYPE_F32 || - op->src[3]->type != GGML_TYPE_F32 || op->src[4]->type != GGML_TYPE_F32 || - op->src[5]->type != GGML_TYPE_F32 || op->src[6]->type != GGML_TYPE_I32) { - return false; - } - - const int64_t d_state = op->src[0]->ne[0]; - return d_state >= 1 && d_state <= 256 && (d_state & (d_state - 1)) == 0; - } - case GGML_OP_GATED_DELTA_NET: - { - // Match the Vulkan backend: only F32 -> F32, S_v in {16, 32, 64, 128}. - if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) { - return false; - } - const int64_t S_v = op->src[2]->ne[0]; - return S_v == 16 || S_v == 32 || S_v == 64 || S_v == 128; - } - case GGML_OP_CONCAT: - { - const ggml_type t = op->src[0]->type; - return op->src[1]->type == t && op->type == t && - !ggml_is_quantized(t) && ggml_blck_size(t) == 1 && - (ggml_type_size(t) == 1 || ggml_type_size(t) == 2 || - ggml_type_size(t) == 4 || ggml_type_size(t) == 8); - } - case GGML_OP_TIMESTEP_EMBEDDING: - return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; - case GGML_OP_GROUP_NORM: - return ggml_is_contiguous(op->src[0]); - case GGML_OP_MUL_MAT: - if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) { - return false; - } - if (ggml_cl_mul_mat_can_use_fwht(backend_ctx, op)) { - return true; - } - if (op->src[0]->type == GGML_TYPE_F16) { - return true; - } else if (op->src[0]->type == GGML_TYPE_BF16) { - return true; - } else if (op->src[0]->type == GGML_TYPE_F32) { - return op->src[1]->type == GGML_TYPE_F32; - } else if (op->src[0]->type == GGML_TYPE_Q1_0) { - return op->src[1]->type == GGML_TYPE_F32; - } else if (op->src[0]->type == GGML_TYPE_Q4_0) { - // Non-contig src0 routes through on-device dequant-to-f16. - return op->src[1]->type == GGML_TYPE_F32; - } else if (op->src[0]->type == GGML_TYPE_IQ2_XXS) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq2_xxs_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_IQ2_XS) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq2_xs_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_IQ2_S) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq2_s_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_Q2_0) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_q2_0_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_IQ1_S) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq1_s_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_IQ1_M) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq1_m_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_IQ3_S) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq3_s_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_IQ3_XXS) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq3_xxs_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_IQ4_XS) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_iq4_xs_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_Q3_K) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_q3_k_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_Q2_K) { - const ggml_tensor * weight = op->src[0]->view_src; - if (weight && ggml_cl_q2_k_use_noshuffle(backend_ctx, weight)) { - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && - ggml_is_contiguous_rows(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_Q4_1 || - op->src[0]->type == GGML_TYPE_Q5_0 || op->src[0]->type == GGML_TYPE_Q5_1 || - op->src[0]->type == GGML_TYPE_MXFP4 || - op->src[0]->type == GGML_TYPE_IQ4_NL || - op->src[0]->type == GGML_TYPE_Q4_K || - op->src[0]->type == GGML_TYPE_Q5_K || - op->src[0]->type == GGML_TYPE_Q6_K) { - // The E031.41 compiler (usually with A7x) miscompiles the flat K-quant - // GEMV kernels (kernel_mul_mv_q*_K_f32_flat) and makes lm_head run much - // slower than it should. So, make it fallback to CPU to preserve performance - // for this compiler series. - static const char * a7x_lmhead_env = getenv("GGML_OPENCL_A7X_LMHEAD_CPU"); - static const bool a7x_lmhead_cpu = (a7x_lmhead_env == nullptr || a7x_lmhead_env[0] != '0'); - if (a7x_lmhead_cpu && - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X && - (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K || - op->src[0]->type == GGML_TYPE_Q6_K) && - op->src[0]->ne[1] >= 32768) { // vocab-scale weight; no FFN/attn weight is this tall - return false; - } - return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]); - } else if (op->src[0]->type == GGML_TYPE_Q8_0) { - // ggml_cl_mul_mat_q8_0_f32_adreno now honors src1/dst view_offs (the - // activation sub-buffer starts at offset1 and the kernels take offsetd), - // so a broadcast q8_0 matmul (src1 batch > src0 batch, e.g. Qwen3.5-9B-UD - // / Qwen3.6-35B q8_0 GDN ssm_out) runs on GPU via the per-slice broadcast - // iteration in ggml_cl_mul_mat. No special-casing needed. - return op->src[1]->type == GGML_TYPE_F32; - } - return false; - case GGML_OP_MUL_MAT_ID: - if (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) { - return op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 && op->type == GGML_TYPE_F32 && - op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && op->src[1]->nb[0] == sizeof(float) && - op->nb[0] == sizeof(float) && op->src[0]->ne[0] <= INT_MAX - 256 && op->ne[0] <= INT_MAX - 64 && - op->src[1]->ne[1] <= INT_MAX && op->ne[1] <= INT_MAX && op->ne[2] <= INT_MAX - 64; - } -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if ((ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) && - use_adreno_moe_kernels(backend_ctx, op->src[0])) { - return false; - } -#endif - if (op->src[0]->type == GGML_TYPE_Q4_0 || - op->src[0]->type == GGML_TYPE_Q8_0 || - op->src[0]->type == GGML_TYPE_MXFP4) { - if (op->src[1]->type == GGML_TYPE_F32) { - return ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]); - } - } - // q4_0, q8_0 and mxfp4 have general MUL_MAT_ID support, - // the quantizations here currently do not - they are only supported by Adreno with certain shapes - if (op->src[0]->type == GGML_TYPE_Q4_1 || - op->src[0]->type == GGML_TYPE_Q5_0 || - op->src[0]->type == GGML_TYPE_Q5_1 || - op->src[0]->type == GGML_TYPE_Q4_K || - op->src[0]->type == GGML_TYPE_Q5_K || - op->src[0]->type == GGML_TYPE_Q6_K) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (op->src[1]->type == GGML_TYPE_F32) { - return use_adreno_moe_kernels(backend_ctx, op->src[0]) - && ggml_is_contiguous(op->src[0]) - && ggml_is_contiguous(op->src[1]); - } -#endif - return false; - } - return false; - case GGML_OP_RESHAPE: - case GGML_OP_VIEW: - case GGML_OP_PERMUTE: - case GGML_OP_TRANSPOSE: - return true; - case GGML_OP_DIAG: - return op->src[0]->type == GGML_TYPE_F32; - case GGML_OP_ROPE: { - const int mode = ((const int32_t *) op->op_params)[2]; - if (!ggml_rope_get_truncate(op)) { - return false; - } - const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; - const bool is_vision = mode == GGML_ROPE_TYPE_VISION; - if (is_mrope && !is_vision) { - if (op->src[0]->type == GGML_TYPE_F32 || - op->src[0]->type == GGML_TYPE_F16) { - return true; - } - return false; - } - if (is_vision) { - if (op->src[0]->type == GGML_TYPE_F32 || - op->src[0]->type == GGML_TYPE_F16) { - return true; - } - return false; - } - return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; - } - case GGML_OP_SOLVE_TRI: - return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); - case GGML_OP_IM2COL: - return true; - case GGML_OP_IM2COL_3D: - return true; - case GGML_OP_ARGMAX: - load_cl_kernels_argmax(backend_ctx); - return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_I32 && - ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) && - backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_argmax_f32_i32) >= 64; - case GGML_OP_LIGHTNING_INDEXER: - return op->src[0]->type == GGML_TYPE_F32 && - (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16 || op->src[1]->type == GGML_TYPE_BF16) && - op->src[2]->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F16 && - op->src[0]->nb[0] == sizeof(float) && op->src[1]->nb[0] == ggml_type_size(op->src[1]->type) && - op->src[2]->nb[0] == sizeof(float) && op->src[3]->nb[0] == sizeof(ggml_fp16_t); - case GGML_OP_TOP_K: - return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_I32; - case GGML_OP_TOP_K_MASK: - return (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32) && - op->src[0]->type == op->type && - op->src[0]->nb[0] == ggml_type_size(op->type) && op->nb[0] == ggml_type_size(op->type) && - op->src[1]->type == GGML_TYPE_I32 && - (!op->src[2] || op->src[2]->type == GGML_TYPE_F32) && - (!op->src[3] || op->src[3]->type == GGML_TYPE_I32) && - (!op->src[4] || op->src[4]->type == GGML_TYPE_I32); - case GGML_OP_ARGSORT: { - load_cl_kernels_argsort(backend_ctx); - - cl_kernel kernel = backend_ctx->kernel_argsort_f32_i32; - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - - int cols = 1; - while (cols < op->ne[0]) { - cols *= 2; - } - - return cols <= max_workgroup_size && op->src[0]->type == GGML_TYPE_F32; - } - case GGML_OP_SUM_ROWS: - case GGML_OP_CUMSUM: - return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); - case GGML_OP_DSV4_HC_PRE: - case GGML_OP_DSV4_HC_POST: - for (int i = 0; i < (op->op == GGML_OP_DSV4_HC_PRE ? 2 : 4); ++i) { - if (op->src[i] && op->src[i]->type != GGML_TYPE_F32) { - return false; - } - } - return op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); - case GGML_OP_MEAN: - return op->src[0]->type == GGML_TYPE_F32; - case GGML_OP_FLASH_ATTN_EXT: { - // K/V row lists and bias are not supported - if (op->src[5] != nullptr || ggml_flash_attn_ext_has_bias(op)) { - return false; - } -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_fa_bin_kernels_prefill(backend_ctx, op->src[0], op->src[1], op->src[2])) { - return true; - } -#endif - // Some E17 compilers crash while building FA kernels. - if (adreno_e17_compiler_quirks(backend_ctx)) { - return false; - } - const ggml_tensor * q = op->src[0]; - const ggml_tensor * k = op->src[1]; - const ggml_tensor * v = op->src[2]; - - const int dk = q->ne[0]; - const int dv = v->ne[0]; - - const struct { int dk; int dv; } supported_dims[] = { - { 40, 40}, { 64, 64}, { 80, 80}, { 96, 96}, - {112, 112}, {128, 128}, {192, 128}, - {192, 192}, {256, 256}, - {512, 512}, - }; - - bool dims_supported = false; - for (size_t i = 0; i < sizeof(supported_dims)/sizeof(supported_dims[0]); ++i) { - if (supported_dims[i].dk == dk && supported_dims[i].dv == dv) { - dims_supported = true; - break; - } - } - if (!dims_supported) { - return false; - } - - const bool is_f32_f32 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F32 && - v->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; - const bool is_f16_f16 = q->type == GGML_TYPE_F16 && k->type == GGML_TYPE_F16 && - v->type == GGML_TYPE_F16 && op->type == GGML_TYPE_F16; - const bool is_f32_f16 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && - v->type == GGML_TYPE_F16 && op->type == GGML_TYPE_F32; - - const bool is_f32_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && - v->type == GGML_TYPE_Q8_0 && op->type == GGML_TYPE_F32 && - dk % 32 == 0 && dv % 32 == 0; - const bool is_f32_q4_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q4_0 && - v->type == GGML_TYPE_Q4_0 && op->type == GGML_TYPE_F32 && - dk % 32 == 0 && dv % 32 == 0; - - // A7X (Adreno 740, compiler E031.41) SIGSEGVs inside clBuildProgram - // building the flash_attn programs whose KV path is mixed-type or - // dequantized — f32_f16, q8_0, q4_0 (reproduced at DK=40 and DK=64; it - // is DK-independent). It is a driver crash, not codegen-wrong-output, so - // it cannot be caught in-process (fatal=false only handles clean compile - // errors). The uniform f16_f16 / f32_f32 programs compile fine on this - // compiler, so decline only the KV-convert variants; ggml then runs - // those (f16-KV / quant-KV) attention layers on the CPU backend. - // Negative compiler carve-out, same idiom as the Intel DK=512 decline - // below and the X1E driver-quirk guards. - if (backend_ctx && backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X && - (is_f32_f16 || is_f32_q8_0 || is_f32_q4_0)) { - return false; - } - - // Asymmetric KV: host-dequants both sides to F32, uses f32 kernel. - auto is_kv_type_ok = [](ggml_type t) { - return t == GGML_TYPE_F16 || t == GGML_TYPE_F32 || - t == GGML_TYPE_Q4_0 || t == GGML_TYPE_Q8_0; - }; - const bool is_f32_asym = q->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && - k->type != v->type && - is_kv_type_ok(k->type) && is_kv_type_ok(v->type); - - const bool kv_combo_ok = is_f32_f32 || is_f16_f16 || is_f32_f16 || - is_f32_q8_0 || is_f32_q4_0 || is_f32_asym; - if (!kv_combo_ok) { - return false; - } - - // Some compilers for A7x (Adreno 740, compiler E031.41) crashes when - // building FA kernels with mixed or quant types (f32_f16, f32_q8_0, f32_q4_0) - // Here we skip all A7x for these kernels to avoid crash - if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X && - (is_f32_f16 || is_f32_q8_0 || is_f32_q4_0)) { - return false; - } - - if (dk == 512) { - if (backend_ctx->gpu_family == INTEL) { - return false; - } - if (!is_f32_f16) { - return false; - } - if (q->ne[1] == 1) { - const char * decode_env = getenv("GGML_OPENCL_FA_DK512_DECODE"); - const int64_t gqa = k->ne[2] > 0 ? q->ne[2] / k->ne[2] : 0; - // GQA 2 and 16 decode on the X2E MQ kernels (see mq_decode_x2e in ggml_cl_flash_attn) - const bool gqa_ok = gqa == 4 || gqa == 8 || - (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && (gqa == 2 || gqa == 16)); - if ((decode_env && decode_env[0] == '0') || - backend_ctx->gpu_family != ADRENO || k->ne[2] <= 0 || - !gqa_ok || q->ne[2] % k->ne[2] != 0 || - !ggml_opencl_ensure_fa_f32_f16_vec_512(backend_ctx)) { - return false; - } - } else { - // prefill, BM-tile in its own FA_PREFILL_ONLY program - if (!ggml_opencl_ensure_fa_f32_f16_prefill_512(backend_ctx, /*split=*/false)) { - return false; - } - } - } - return true; - } - default: - return false; - } -} - -// Forward declaration - implementation appears later in the file. -static const char * ggml_backend_opencl_buffer_type_get_name(ggml_backend_buffer_type_t buffer_type); - -static ggml_guid_t ggml_backend_opencl_guid() { - static ggml_guid guid = { 0xde, 0xe0, 0x70, 0xa2, 0x73, 0x4e, 0x4d, 0xbc, 0xb0, 0xc7, 0x4f, 0xd4, 0x6d, 0x4e, 0x90, 0xfe }; - return &guid; -} - -static ggml_backend_i ggml_backend_opencl_i = { - /* .get_name = */ ggml_backend_opencl_name, - /* .free = */ ggml_backend_opencl_free, - /* .set_tensor_async = */ NULL, /* ggml_backend_opencl_set_tensor_async */ - /* .get_tensor_async = */ NULL, /* ggml_backend_opencl_get_tensor_async */ - /* .set_tensor_2d_async = */ NULL, - /* .get_tensor_2d_async = */ NULL, - /* .cpy_tensor_async = */ NULL, /* ggml_backend_opencl_cpy_tensor_async */ - /* .synchronize = */ ggml_backend_opencl_synchronize, - /* .graph_plan_create = */ NULL, - /* .graph_plan_free = */ NULL, - /* .graph_plan_update = */ NULL, - /* .graph_plan_compute = */ NULL, - /* .graph_compute = */ ggml_backend_opencl_graph_compute, - /* .event_record = */ NULL, - /* .event_wait = */ NULL, - /* .graph_optimize = */ NULL, -}; - -ggml_backend_t ggml_backend_opencl_init(void) { - ggml_backend_dev_t dev = ggml_backend_reg_dev_get(ggml_backend_opencl_reg(), 0); - ggml_backend_opencl_context *backend_ctx = ggml_cl_init(dev); - backend_ctx->ref_count++; - - ggml_backend_t backend = new ggml_backend { - /* .guid = */ ggml_backend_opencl_guid(), - /* .iface = */ ggml_backend_opencl_i, - /* .device = */ dev, - /* .context = */ backend_ctx - }; - - return backend; -} - -bool ggml_backend_is_opencl(ggml_backend_t backend) { - return backend && backend->iface.get_name == ggml_backend_opencl_name; -} - -// -// buffer -// -struct ggml_backend_opencl_buffer_context { - // A buffer context can hold multiple cl_mem objects. This is for flattening - // quantized weights and should be used with GGML_OPENCL_SMALL_ALLOC where - // each tensor is allocated a separate buffer. When flattening is enabled - // with small allocation, each tensor is backed by two cl_mem objects (for - // quants and scales) packed into a backend_opencl_buffer. - ggml_backend_opencl_buffer_context(cl_mem buf) - : name("OpenCL") { - buffer.push_back(buf); - } - - ~ggml_backend_opencl_buffer_context() { - for (cl_mem buf : buffer) { - CL_CHECK(clReleaseMemObject(buf)); - } - for (cl_mem im : img) { - CL_CHECK(clReleaseMemObject(im)); - } - - // Delete all extras to trigger their destructors - for (ggml_tensor_extra_cl * e : temp_tensor_extras) { - delete e; - } - for (ggml_tensor_extra_cl * e : temp_tensor_extras_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q4_0 * e : temp_tensor_extras_q4_0) { - delete e; - } - for (ggml_tensor_extra_cl_q4_0 * e : temp_tensor_extras_q4_0_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q4_1 * e : temp_tensor_extras_q4_1) { - delete e; - } - for (ggml_tensor_extra_cl_q4_1 * e : temp_tensor_extras_q4_1_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q5_0 * e : temp_tensor_extras_q5_0) { - delete e; - } - for (ggml_tensor_extra_cl_q5_0 * e : temp_tensor_extras_q5_0_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q5_1 * e : temp_tensor_extras_q5_1) { - delete e; - } - for (ggml_tensor_extra_cl_q5_1 * e : temp_tensor_extras_q5_1_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_mxfp4 * e : temp_tensor_extras_mxfp4) { - delete e; - } - for (ggml_tensor_extra_cl_mxfp4 * e : temp_tensor_extras_mxfp4_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q8_0 * e : temp_tensor_extras_q8_0) { - delete e; - } - for (ggml_tensor_extra_cl_q8_0 * e : temp_tensor_extras_q8_0_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q1_0 * e : temp_tensor_extras_q1_0) { - delete e; - } - for (ggml_tensor_extra_cl_q1_0 * e : temp_tensor_extras_q1_0_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq4_nl * e : temp_tensor_extras_iq4_nl) { - delete e; - } - for (ggml_tensor_extra_cl_iq4_nl * e : temp_tensor_extras_iq4_nl_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q4_K * e : temp_tensor_extras_q4_K) { - delete e; - } - for (ggml_tensor_extra_cl_q4_K * e : temp_tensor_extras_q4_K_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q6_K * e : temp_tensor_extras_q6_K) { - delete e; - } - for (ggml_tensor_extra_cl_q2_K * e : temp_tensor_extras_q2_K) { - delete e; - } - for (ggml_tensor_extra_cl_q3_K * e : temp_tensor_extras_q3_K) { - delete e; - } - for (ggml_tensor_extra_cl_iq2_s * e : temp_tensor_extras_iq2_s) { - delete e; - } - for (ggml_tensor_extra_cl_iq2_xs * e : temp_tensor_extras_iq2_xs) { - delete e; - } - for (ggml_tensor_extra_cl_iq2_xxs * e : temp_tensor_extras_iq2_xxs) { - delete e; - } - for (ggml_tensor_extra_cl_q2_0 * e : temp_tensor_extras_q2_0) { - delete e; - } - for (ggml_tensor_extra_cl_iq1_m * e : temp_tensor_extras_iq1_m) { - delete e; - } - for (ggml_tensor_extra_cl_iq1_s * e : temp_tensor_extras_iq1_s) { - delete e; - } - for (ggml_tensor_extra_cl_iq3_s * e : temp_tensor_extras_iq3_s) { - delete e; - } - for (ggml_tensor_extra_cl_iq3_xxs * e : temp_tensor_extras_iq3_xxs) { - delete e; - } - for (ggml_tensor_extra_cl_iq4_xs * e : temp_tensor_extras_iq4_xs) { - delete e; - } - for (ggml_tensor_extra_cl_q6_K * e : temp_tensor_extras_q6_K_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q2_K * e : temp_tensor_extras_q2_K_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q3_K * e : temp_tensor_extras_q3_K_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq2_s * e : temp_tensor_extras_iq2_s_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq2_xs * e : temp_tensor_extras_iq2_xs_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq2_xxs * e : temp_tensor_extras_iq2_xxs_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q2_0 * e : temp_tensor_extras_q2_0_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq1_m * e : temp_tensor_extras_iq1_m_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq1_s * e : temp_tensor_extras_iq1_s_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq3_s * e : temp_tensor_extras_iq3_s_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq3_xxs * e : temp_tensor_extras_iq3_xxs_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_iq4_xs * e : temp_tensor_extras_iq4_xs_in_use) { - delete e; - } - for (ggml_tensor_extra_cl_q5_K * e : temp_tensor_extras_q5_K) { - delete e; - } - for (ggml_tensor_extra_cl_q5_K * e : temp_tensor_extras_q5_K_in_use) { - delete e; - } - } - - ggml_tensor_extra_cl * ggml_opencl_alloc_temp_tensor_extra() { - ggml_tensor_extra_cl * extra; - if (temp_tensor_extras.empty()) { - extra = new ggml_tensor_extra_cl(); - } else { - extra = temp_tensor_extras.back(); - temp_tensor_extras.pop_back(); - } - - temp_tensor_extras_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q1_0 * ggml_opencl_alloc_temp_tensor_extra_q1_0() { - ggml_tensor_extra_cl_q1_0 * extra; - if (temp_tensor_extras_q1_0.empty()) { - extra = new ggml_tensor_extra_cl_q1_0(); - } else { - extra = temp_tensor_extras_q1_0.back(); - temp_tensor_extras_q1_0.pop_back(); - } - - temp_tensor_extras_q1_0_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q4_0 * ggml_opencl_alloc_temp_tensor_extra_q4_0() { - ggml_tensor_extra_cl_q4_0 * extra; - if (temp_tensor_extras_q4_0.empty()) { - extra = new ggml_tensor_extra_cl_q4_0(); - } else { - extra = temp_tensor_extras_q4_0.back(); - temp_tensor_extras_q4_0.pop_back(); - } - - temp_tensor_extras_q4_0_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q4_1 * ggml_opencl_alloc_temp_tensor_extra_q4_1() { - ggml_tensor_extra_cl_q4_1 * extra; - if (temp_tensor_extras_q4_1.empty()) { - extra = new ggml_tensor_extra_cl_q4_1(); - } else { - extra = temp_tensor_extras_q4_1.back(); - temp_tensor_extras_q4_1.pop_back(); - } - - temp_tensor_extras_q4_1_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q5_0 * ggml_opencl_alloc_temp_tensor_extra_q5_0() { - ggml_tensor_extra_cl_q5_0 * extra; - if (temp_tensor_extras_q5_0.empty()) { - extra = new ggml_tensor_extra_cl_q5_0(); - } else { - extra = temp_tensor_extras_q5_0.back(); - temp_tensor_extras_q5_0.pop_back(); - } - - temp_tensor_extras_q5_0_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q5_1 * ggml_opencl_alloc_temp_tensor_extra_q5_1() { - ggml_tensor_extra_cl_q5_1 * extra; - if (temp_tensor_extras_q5_1.empty()) { - extra = new ggml_tensor_extra_cl_q5_1(); - } else { - extra = temp_tensor_extras_q5_1.back(); - temp_tensor_extras_q5_1.pop_back(); - } - - temp_tensor_extras_q5_1_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_mxfp4 * ggml_opencl_alloc_temp_tensor_extra_mxfp4() { - ggml_tensor_extra_cl_mxfp4 * extra; - if (temp_tensor_extras_mxfp4.empty()) { - extra = new ggml_tensor_extra_cl_mxfp4(); - } else { - extra = temp_tensor_extras_mxfp4.back(); - temp_tensor_extras_mxfp4.pop_back(); - } - - temp_tensor_extras_mxfp4_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q8_0 * ggml_opencl_alloc_temp_tensor_extra_q8_0() { - ggml_tensor_extra_cl_q8_0 * extra; - if (temp_tensor_extras_q8_0.empty()) { - extra = new ggml_tensor_extra_cl_q8_0(); - } else { - extra = temp_tensor_extras_q8_0.back(); - temp_tensor_extras_q8_0.pop_back(); - } - - temp_tensor_extras_q8_0_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq4_nl * ggml_opencl_alloc_temp_tensor_extra_iq4_nl() { - ggml_tensor_extra_cl_iq4_nl * extra; - if (temp_tensor_extras_iq4_nl.empty()) { - extra = new ggml_tensor_extra_cl_iq4_nl(); - } else { - extra = temp_tensor_extras_iq4_nl.back(); - temp_tensor_extras_iq4_nl.pop_back(); - } - - temp_tensor_extras_iq4_nl_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q4_K * ggml_opencl_alloc_temp_tensor_extra_q4_K() { - ggml_tensor_extra_cl_q4_K * extra; - if (temp_tensor_extras_q4_K.empty()) { - extra = new ggml_tensor_extra_cl_q4_K(); - } else { - extra = temp_tensor_extras_q4_K.back(); - temp_tensor_extras_q4_K.pop_back(); - } - - temp_tensor_extras_q4_K_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q5_K * ggml_opencl_alloc_temp_tensor_extra_q5_K() { - ggml_tensor_extra_cl_q5_K * extra; - if (temp_tensor_extras_q5_K.empty()) { - extra = new ggml_tensor_extra_cl_q5_K(); - } else { - extra = temp_tensor_extras_q5_K.back(); - temp_tensor_extras_q5_K.pop_back(); - } - - temp_tensor_extras_q5_K_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q2_K * ggml_opencl_alloc_temp_tensor_extra_q2_K() { - ggml_tensor_extra_cl_q2_K * extra; - if (temp_tensor_extras_q2_K.empty()) { - extra = new ggml_tensor_extra_cl_q2_K(); - } else { - extra = temp_tensor_extras_q2_K.back(); - temp_tensor_extras_q2_K.pop_back(); - } - - temp_tensor_extras_q2_K_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q3_K * ggml_opencl_alloc_temp_tensor_extra_q3_K() { - ggml_tensor_extra_cl_q3_K * extra; - if (temp_tensor_extras_q3_K.empty()) { - extra = new ggml_tensor_extra_cl_q3_K(); - } else { - extra = temp_tensor_extras_q3_K.back(); - temp_tensor_extras_q3_K.pop_back(); - } - - temp_tensor_extras_q3_K_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq2_s * ggml_opencl_alloc_temp_tensor_extra_iq2_s() { - ggml_tensor_extra_cl_iq2_s * extra; - if (temp_tensor_extras_iq2_s.empty()) { - extra = new ggml_tensor_extra_cl_iq2_s(); - } else { - extra = temp_tensor_extras_iq2_s.back(); - temp_tensor_extras_iq2_s.pop_back(); - } - - temp_tensor_extras_iq2_s_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq2_xs * ggml_opencl_alloc_temp_tensor_extra_iq2_xs() { - ggml_tensor_extra_cl_iq2_xs * extra; - if (temp_tensor_extras_iq2_xs.empty()) { - extra = new ggml_tensor_extra_cl_iq2_xs(); - } else { - extra = temp_tensor_extras_iq2_xs.back(); - temp_tensor_extras_iq2_xs.pop_back(); - } - - temp_tensor_extras_iq2_xs_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq2_xxs * ggml_opencl_alloc_temp_tensor_extra_iq2_xxs() { - ggml_tensor_extra_cl_iq2_xxs * extra; - if (temp_tensor_extras_iq2_xxs.empty()) { - extra = new ggml_tensor_extra_cl_iq2_xxs(); - } else { - extra = temp_tensor_extras_iq2_xxs.back(); - temp_tensor_extras_iq2_xxs.pop_back(); - } - - temp_tensor_extras_iq2_xxs_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q2_0 * ggml_opencl_alloc_temp_tensor_extra_q2_0() { - ggml_tensor_extra_cl_q2_0 * extra; - if (temp_tensor_extras_q2_0.empty()) { - extra = new ggml_tensor_extra_cl_q2_0(); - } else { - extra = temp_tensor_extras_q2_0.back(); - temp_tensor_extras_q2_0.pop_back(); - } - - temp_tensor_extras_q2_0_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq1_m * ggml_opencl_alloc_temp_tensor_extra_iq1_m() { - ggml_tensor_extra_cl_iq1_m * extra; - if (temp_tensor_extras_iq1_m.empty()) { - extra = new ggml_tensor_extra_cl_iq1_m(); - } else { - extra = temp_tensor_extras_iq1_m.back(); - temp_tensor_extras_iq1_m.pop_back(); - } - - temp_tensor_extras_iq1_m_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq1_s * ggml_opencl_alloc_temp_tensor_extra_iq1_s() { - ggml_tensor_extra_cl_iq1_s * extra; - if (temp_tensor_extras_iq1_s.empty()) { - extra = new ggml_tensor_extra_cl_iq1_s(); - } else { - extra = temp_tensor_extras_iq1_s.back(); - temp_tensor_extras_iq1_s.pop_back(); - } - - temp_tensor_extras_iq1_s_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq3_s * ggml_opencl_alloc_temp_tensor_extra_iq3_s() { - ggml_tensor_extra_cl_iq3_s * extra; - if (temp_tensor_extras_iq3_s.empty()) { - extra = new ggml_tensor_extra_cl_iq3_s(); - } else { - extra = temp_tensor_extras_iq3_s.back(); - temp_tensor_extras_iq3_s.pop_back(); - } - - temp_tensor_extras_iq3_s_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq3_xxs * ggml_opencl_alloc_temp_tensor_extra_iq3_xxs() { - ggml_tensor_extra_cl_iq3_xxs * extra; - if (temp_tensor_extras_iq3_xxs.empty()) { - extra = new ggml_tensor_extra_cl_iq3_xxs(); - } else { - extra = temp_tensor_extras_iq3_xxs.back(); - temp_tensor_extras_iq3_xxs.pop_back(); - } - - temp_tensor_extras_iq3_xxs_in_use.push_back(extra); - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_iq4_xs * ggml_opencl_alloc_temp_tensor_extra_iq4_xs() { - ggml_tensor_extra_cl_iq4_xs * extra; - if (temp_tensor_extras_iq4_xs.empty()) { - extra = new ggml_tensor_extra_cl_iq4_xs(); - } else { - extra = temp_tensor_extras_iq4_xs.back(); - temp_tensor_extras_iq4_xs.pop_back(); - } - - temp_tensor_extras_iq4_xs_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - ggml_tensor_extra_cl_q6_K * ggml_opencl_alloc_temp_tensor_extra_q6_K() { - ggml_tensor_extra_cl_q6_K * extra; - if (temp_tensor_extras_q6_K.empty()) { - extra = new ggml_tensor_extra_cl_q6_K(); - } else { - extra = temp_tensor_extras_q6_K.back(); - temp_tensor_extras_q6_K.pop_back(); - } - - temp_tensor_extras_q6_K_in_use.push_back(extra); - - extra->reset(); - return extra; - } - - void reset() { - for (ggml_tensor_extra_cl * e : temp_tensor_extras_in_use) { - temp_tensor_extras.push_back(e); - } - temp_tensor_extras_in_use.clear(); - - for (ggml_tensor_extra_cl_q1_0 * e : temp_tensor_extras_q1_0_in_use) { - temp_tensor_extras_q1_0.push_back(e); - } - temp_tensor_extras_q1_0_in_use.clear(); - - for (ggml_tensor_extra_cl_q4_0 * e : temp_tensor_extras_q4_0_in_use) { - temp_tensor_extras_q4_0.push_back(e); - } - temp_tensor_extras_q4_0_in_use.clear(); - - for (ggml_tensor_extra_cl_q4_1 * e : temp_tensor_extras_q4_1_in_use) { - temp_tensor_extras_q4_1.push_back(e); - } - temp_tensor_extras_q4_1_in_use.clear(); - - for (ggml_tensor_extra_cl_q5_0 * e : temp_tensor_extras_q5_0_in_use) { - temp_tensor_extras_q5_0.push_back(e); - } - temp_tensor_extras_q5_0_in_use.clear(); - - for (ggml_tensor_extra_cl_q5_1 * e : temp_tensor_extras_q5_1_in_use) { - temp_tensor_extras_q5_1.push_back(e); - } - temp_tensor_extras_q5_1_in_use.clear(); - - for (ggml_tensor_extra_cl_mxfp4 * e : temp_tensor_extras_mxfp4_in_use) { - temp_tensor_extras_mxfp4.push_back(e); - } - temp_tensor_extras_mxfp4_in_use.clear(); - - for (ggml_tensor_extra_cl_q8_0 * e : temp_tensor_extras_q8_0_in_use) { - temp_tensor_extras_q8_0.push_back(e); - } - temp_tensor_extras_q8_0_in_use.clear(); - - for (ggml_tensor_extra_cl_iq4_nl * e : temp_tensor_extras_iq4_nl_in_use) { - temp_tensor_extras_iq4_nl.push_back(e); - } - temp_tensor_extras_iq4_nl_in_use.clear(); - - for (ggml_tensor_extra_cl_q4_K * e : temp_tensor_extras_q4_K_in_use) { - temp_tensor_extras_q4_K.push_back(e); - } - temp_tensor_extras_q4_K_in_use.clear(); - - for (ggml_tensor_extra_cl_q5_K * e : temp_tensor_extras_q5_K_in_use) { - temp_tensor_extras_q5_K.push_back(e); - } - temp_tensor_extras_q5_K_in_use.clear(); - - for (ggml_tensor_extra_cl_q6_K * e : temp_tensor_extras_q6_K_in_use) { - temp_tensor_extras_q6_K.push_back(e); - } - temp_tensor_extras_q6_K_in_use.clear(); - - for (ggml_tensor_extra_cl_q2_K * e : temp_tensor_extras_q2_K_in_use) { - temp_tensor_extras_q2_K.push_back(e); - } - temp_tensor_extras_q2_K_in_use.clear(); - - for (ggml_tensor_extra_cl_q3_K * e : temp_tensor_extras_q3_K_in_use) { - temp_tensor_extras_q3_K.push_back(e); - } - temp_tensor_extras_q3_K_in_use.clear(); - - for (ggml_tensor_extra_cl_iq2_s * e : temp_tensor_extras_iq2_s_in_use) { - temp_tensor_extras_iq2_s.push_back(e); - } - temp_tensor_extras_iq2_s_in_use.clear(); - - for (ggml_tensor_extra_cl_iq2_xs * e : temp_tensor_extras_iq2_xs_in_use) { - temp_tensor_extras_iq2_xs.push_back(e); - } - temp_tensor_extras_iq2_xs_in_use.clear(); - - for (ggml_tensor_extra_cl_iq2_xxs * e : temp_tensor_extras_iq2_xxs_in_use) { - temp_tensor_extras_iq2_xxs.push_back(e); - } - temp_tensor_extras_iq2_xxs_in_use.clear(); - - for (ggml_tensor_extra_cl_q2_0 * e : temp_tensor_extras_q2_0_in_use) { - temp_tensor_extras_q2_0.push_back(e); - } - temp_tensor_extras_q2_0_in_use.clear(); - - for (ggml_tensor_extra_cl_iq1_m * e : temp_tensor_extras_iq1_m_in_use) { - temp_tensor_extras_iq1_m.push_back(e); - } - temp_tensor_extras_iq1_m_in_use.clear(); - - for (ggml_tensor_extra_cl_iq1_s * e : temp_tensor_extras_iq1_s_in_use) { - temp_tensor_extras_iq1_s.push_back(e); - } - temp_tensor_extras_iq1_s_in_use.clear(); - - for (ggml_tensor_extra_cl_iq3_s * e : temp_tensor_extras_iq3_s_in_use) { - temp_tensor_extras_iq3_s.push_back(e); - } - temp_tensor_extras_iq3_s_in_use.clear(); - - for (ggml_tensor_extra_cl_iq3_xxs * e : temp_tensor_extras_iq3_xxs_in_use) { - temp_tensor_extras_iq3_xxs.push_back(e); - } - temp_tensor_extras_iq3_xxs_in_use.clear(); - for (ggml_tensor_extra_cl_iq4_xs * e : temp_tensor_extras_iq4_xs_in_use) { - temp_tensor_extras_iq4_xs.push_back(e); - } - temp_tensor_extras_iq4_xs_in_use.clear(); - - q8_0_soa_tensors.clear(); - q4_0_soa_tensors.clear(); - } - - // Pools for extras. Available extras are in `temp_tensor_extras`. Extras - // being used are in `temp_tensor_extras_in_use`. At the first run, new - // extras get created and put in `in_use`. When the buffer is reset via - // the `reset` callback, all extras in `in_use` get moved to available extras - // for reuse. - std::vector temp_tensor_extras; - std::vector temp_tensor_extras_in_use; - std::vector temp_tensor_extras_q1_0; - std::vector temp_tensor_extras_q1_0_in_use; - std::vector temp_tensor_extras_q4_0; - std::vector temp_tensor_extras_q4_0_in_use; - std::vector temp_tensor_extras_q4_1; - std::vector temp_tensor_extras_q4_1_in_use; - std::vector temp_tensor_extras_q5_0; - std::vector temp_tensor_extras_q5_0_in_use; - std::vector temp_tensor_extras_q5_1; - std::vector temp_tensor_extras_q5_1_in_use; - std::vector temp_tensor_extras_mxfp4; - std::vector temp_tensor_extras_mxfp4_in_use; - std::vector temp_tensor_extras_q8_0; - std::vector temp_tensor_extras_q8_0_in_use; - std::vector temp_tensor_extras_iq4_nl; - std::vector temp_tensor_extras_iq4_nl_in_use; - std::vector temp_tensor_extras_q4_K; - std::vector temp_tensor_extras_q4_K_in_use; - std::vector temp_tensor_extras_q5_K; - std::vector temp_tensor_extras_q5_K_in_use; - std::vector temp_tensor_extras_q2_K; - std::vector temp_tensor_extras_q3_K; - std::vector temp_tensor_extras_iq2_s; - std::vector temp_tensor_extras_iq2_xs; - std::vector temp_tensor_extras_iq2_xxs; - std::vector temp_tensor_extras_iq3_xxs; - std::vector temp_tensor_extras_q2_K_in_use; - std::vector temp_tensor_extras_q3_K_in_use; - std::vector temp_tensor_extras_iq2_s_in_use; - std::vector temp_tensor_extras_iq2_xs_in_use; - std::vector temp_tensor_extras_iq2_xxs_in_use; - std::vector temp_tensor_extras_q2_0; - std::vector temp_tensor_extras_q2_0_in_use; - std::vector temp_tensor_extras_iq1_s; - std::vector temp_tensor_extras_iq1_m; - std::vector temp_tensor_extras_iq1_m_in_use; - std::vector temp_tensor_extras_iq1_s_in_use; - std::vector temp_tensor_extras_iq3_s; - std::vector temp_tensor_extras_iq3_s_in_use; - std::vector temp_tensor_extras_iq3_xxs_in_use; - std::vector temp_tensor_extras_iq4_xs; - std::vector temp_tensor_extras_iq4_xs_in_use; - std::vector temp_tensor_extras_q6_K; - std::vector temp_tensor_extras_q6_K_in_use; - - // q8_0 tensors with AoS->SoA layout conversion installed by set_tensor. - // Two types of tensors get SOA'ed - normal weights and MoE weights. - // In Q8_0's case, we only have normal weights. If we ever have Q8_0 as MoE - // weights, they need to be added to this set in `set_tensors`. - std::unordered_set q8_0_soa_tensors; - - // Same for q4_0. KV-cache q4_0 tensors are allocated but never pass - // through set_tensor, so they stay AoS and aren't in this set. - // In Q4_0's case, in addition to normal weights, we have MoE weights. - std::unordered_set q4_0_soa_tensors; - - // The buffer_context is initially created by ggml_backend_buft_alloc_buffer - // before any tensor is initialized (at the beginning of alloc_tensor_range). - // Hence, there is always a buffer object in this vector. When each tensor is - // being initialized, this original buffer object will be released if both - // flattening and small allocation are enabled, and additional buffer - // objects will be created in init_tensor to represent flattened quantized - // weights. - std::vector buffer; - // These are image1d_buffer_t objects that wrap around the quants and scales. - // For Q4_0 quantization, there should be two of them - one for quants and - // one for scales. They should be populated only when flattening and small - // allocation are enabled. - std::vector img; - std::string name; -}; - -static void ggml_backend_opencl_buffer_free_buffer(ggml_backend_buffer_t buffer) { - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - delete ctx; -} - -static void * ggml_backend_opencl_buffer_get_base(ggml_backend_buffer_t buffer) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; - return (void *) (uintptr_t) dev_ctx->backend_ctx->alignment; -} - -static enum ggml_status ggml_backend_opencl_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) { - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - - if (tensor->view_src != nullptr) { - GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft); - - ggml_tensor_extra_cl * view_extra = (ggml_tensor_extra_cl *) tensor->view_src->extra; - GGML_ASSERT(view_extra && "view_extra is nullptr?"); - - // Reuse extra of the parent tensor. The offset of this view tensor - // becomes `extra->offset + view_offs` and needs to be calculated when - // it is used. This changes is needed because of the change to - // ggml_alloc.c in https://github.com/ggml-org/llama.cpp/pull/7640. - // `buffer` passed in here will always be `tensor->buffer`. It is OK - // to allocate extras from the same buffer context for ordinary - // intermediate tensors. But for views into kv cache tensors, doing so - // would mess up the extras used by kv cache. - // Before #7640, `buffer` is for intermediate tensors, which is always - // different from that of kv cache tensors. - // - // NB: now extra->offset no longer accounts for view_offs. - // NB: this should not apply to weight tensors (for end-to-end runs, but - // may apply for test-backend-ops). - // FIXME: if any unexpected results are seen, double check the offset - - // there could be other places that need fix. - tensor->extra = view_extra; - } else { - { - size_t offset = (char *) tensor->data - (char *) ggml_backend_opencl_buffer_get_base(buffer); - - ggml_tensor_extra_cl * extra = ctx->ggml_opencl_alloc_temp_tensor_extra(); - extra->offset = offset; - extra->data_device = ctx->buffer[0]; - extra->actual_size = ggml_nbytes(tensor); - - tensor->extra = extra; - } - } - return GGML_STATUS_SUCCESS; -} - -// Allocate a temporary upload buffer of `nbytes` and populate it with `data` -// from host. On Adreno X1-85 the device-only pool intermittently fails to -// allocate at hundreds of MB once model weights fragment the heap (observed -// on Qwen3.5-9B output.weight Q6_K at 834 MB). Three-step retry: -// 1. CL_MEM_READ_WRITE alloc + clEnqueueWriteBuffer (normal fast path). -// 2. clFinish + retry (drains in-flight allocs that may be holding heap; -// mirrors the proven pattern at the FD-split partial buffer alloc). -// 3. CL_MEM_ALLOC_HOST_PTR + map(WRITE_INVALIDATE) + memcpy + unmap — -// different memory pool (host-pinned); true zero-copy on Adreno per -// QCOM guidance. (CL_MEM_USE_HOST_PTR is NOT zero-copy on Adreno: the -// driver triggers an internal copy because arbitrary host pages aren't -// guaranteed mappable/coherent, AND it draws from the same exhausted -// device pool — so it doesn't solve the problem.) -// Returns the ready-to-read buffer (caller must clReleaseMemObject) or NULL -// if all three strategies fail. The buffer is opaque to the caller — it can -// be passed as a kernel argument like any normal cl_mem. -static cl_mem ggml_cl_create_temp_upload_buffer( - cl_context context, cl_command_queue queue, - size_t nbytes, const void * data, - const char * tensor_name_for_log) -{ - cl_int err; - cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); - if (err != CL_SUCCESS) { - clFinish(queue); - buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); - } - if (err == CL_SUCCESS) { - const cl_int werr = clEnqueueWriteBuffer(queue, buf, CL_TRUE, 0, nbytes, data, 0, NULL, NULL); - if (werr == CL_SUCCESS) { - return buf; - } - clReleaseMemObject(buf); - } - buf = clCreateBuffer(context, - CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR | CL_MEM_HOST_WRITE_ONLY, - nbytes, NULL, &err); - if (err != CL_SUCCESS) { - return NULL; - } - void * mapped = clEnqueueMapBuffer(queue, buf, CL_TRUE, - CL_MAP_WRITE_INVALIDATE_REGION, 0, nbytes, 0, NULL, NULL, &err); - if (err != CL_SUCCESS) { - clReleaseMemObject(buf); - return NULL; - } - memcpy(mapped, data, nbytes); - const cl_int uerr = clEnqueueUnmapMemObject(queue, buf, mapped, 0, NULL, NULL); - if (uerr != CL_SUCCESS) { - clReleaseMemObject(buf); - return NULL; - } - if (tensor_name_for_log) { - GGML_LOG_INFO("ggml_opencl: %s (%.1f MiB) — device alloc failed, using CL_MEM_ALLOC_HOST_PTR fallback\n", - tensor_name_for_log, nbytes / 1024.0 / 1024.0); - } - return buf; -} - -// Allocate a temporary download buffer of `nbytes`. The caller runs a kernel -// that writes into it, then reads it back to host via clEnqueueReadBuffer (or -// equivalent). Mirrors ggml_cl_create_temp_upload_buffer; the host-pinned -// fallback flags are flipped (CL_MEM_WRITE_ONLY | HOST_READ_ONLY) and the -// helper doesn't populate the buffer. -static cl_mem ggml_cl_create_temp_download_buffer( - cl_context context, cl_command_queue queue, - size_t nbytes, const char * tensor_name_for_log) -{ - cl_int err; - cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); - if (err != CL_SUCCESS) { - clFinish(queue); - buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); - } - if (err == CL_SUCCESS) { - return buf; - } - buf = clCreateBuffer(context, - CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR | CL_MEM_HOST_READ_ONLY, - nbytes, NULL, &err); - if (err != CL_SUCCESS) { - return NULL; - } - if (tensor_name_for_log) { - GGML_LOG_INFO("ggml_opencl: %s download (%.1f MiB) — device alloc failed, using CL_MEM_ALLOC_HOST_PTR fallback\n", - tensor_name_for_log, nbytes / 1024.0 / 1024.0); - } - return buf; -} - -static void ggml_backend_opencl_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; - ggml_backend_opencl_context * backend_ctx = dev_ctx->backend_ctx; - - cl_context context = backend_ctx->context; - cl_command_queue queue = backend_ctx->queue; - -#ifdef GGML_OPENCL_SOA_Q - if (tensor->type == GGML_TYPE_Q2_K) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q2_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q2_K(); - extra->noshuffle = ggml_cl_q2_k_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * (blck/4); - const size_t size_sc = n_blk * (blck/16); - const size_t size_dm = n_blk * 2 * sizeof(ggml_fp16_t); - GGML_ASSERT(size_qs + size_sc + size_dm == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - auto previous_origin = region.origin; - - region.origin = align_to(previous_origin + size_qs, backend_ctx->alignment); - region.size = size_sc; - CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - - region.origin = align_to(previous_origin + size_sc, backend_ctx->alignment); - region.size = size_dm; - CL_CHECK((extra->dm = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = extra->noshuffle ? backend_ctx->kernel_convert_block_q2_k_noshuffle - : backend_ctx->kernel_convert_block_q2_K; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/16, m, true, true); - transpose_2d_as_32b(backend_ctx, extra->dm, extra->dm, size_dm, k/(int)blck, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_sc = size_sc; - extra->size_dm = size_dm; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_Q3_K) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q3_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q3_K(); - extra->noshuffle = ggml_cl_q3_k_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * (blck/4); - const size_t size_hm = n_blk * (blck/8); - const size_t size_sc = n_blk * 12; - const size_t size_d = n_blk * sizeof(ggml_fp16_t); - GGML_ASSERT(size_qs + size_hm + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - auto previous_origin = region.origin; - - region.origin = align_to(previous_origin + size_qs, backend_ctx->alignment); - region.size = size_hm; - CL_CHECK((extra->hm = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - - region.origin = align_to(previous_origin + size_hm, backend_ctx->alignment); - region.size = size_sc; - CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - - region.origin = align_to(previous_origin + size_sc, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = extra->noshuffle ? backend_ctx->kernel_convert_block_q3_k_noshuffle - : backend_ctx->kernel_convert_block_q3_K; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->hm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->hm, extra->hm, size_hm, k/8, m, true, true); - transpose_2d_as_32b(backend_ctx, extra->sc, extra->sc, size_sc, 3*k/(int)blck, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_hm = size_hm; - extra->size_sc = size_sc; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_IQ3_S) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq3_s * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq3_s(); - extra->noshuffle = ggml_cl_iq3_s_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 64; - const size_t size_sg = n_blk * 32; - const size_t size_qh = n_blk * 8; - const size_t size_sc = n_blk * 4; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_sg + size_qh + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_sg; - CL_CHECK((extra->sg = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sg, backend_ctx->alignment); - region.size = size_qh; - CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); - region.size = size_sc; - CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sc, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_iq3_s; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sg)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->sc)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->sg, extra->sg, size_sg, k/8, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, k/32, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/64, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/256, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_sg = size_sg; - extra->size_qh = size_qh; - extra->size_sc = size_sc; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_IQ3_XXS) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq3_xxs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq3_xxs(); - extra->noshuffle = ggml_cl_iq3_xxs_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 64; - const size_t size_sas = n_blk * 32; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_sas + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_sas; - CL_CHECK((extra->sas = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sas, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_iq3_xxs; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sas)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); - transpose_2d_as_32b(backend_ctx, extra->sas, extra->sas, size_sas, k/32, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/256, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_sas = size_sas; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_IQ1_M) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq1_m * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq1_m(); - extra->noshuffle = ggml_cl_iq1_m_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 32; - const size_t size_qh = n_blk * 16; - const size_t size_sc = n_blk * 8; - GGML_ASSERT(size_qs + size_qh + size_sc == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_qh; - CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); - region.size = size_sc; - CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_iq1_m; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, k/16, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->sc, extra->sc, size_sc, k/64, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_qh = size_qh; - extra->size_sc = size_sc; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_IQ1_S) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq1_s * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq1_s(); - extra->noshuffle = ggml_cl_iq1_s_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 32; - const size_t size_qh = n_blk * 16; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_qh + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_qh; - CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_iq1_s; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->qh, extra->qh, size_qh, k/32, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_qh = size_qh; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_IQ2_S) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq2_s * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq2_s(); - extra->noshuffle = ggml_cl_iq2_s_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 32; - const size_t size_sg = n_blk * 32; - const size_t size_qh = n_blk * 8; - const size_t size_sc = n_blk * 8; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_sg + size_qh + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_sg; - CL_CHECK((extra->sg = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sg, backend_ctx->alignment); - region.size = size_qh; - CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); - region.size = size_sc; - CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sc, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_iq2_s; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sg)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->sc)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->sg, extra->sg, size_sg, k/8, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, k/32, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/32, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_sg = size_sg; - extra->size_qh = size_qh; - extra->size_sc = size_sc; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_IQ2_XS) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq2_xs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq2_xs(); - extra->noshuffle = ggml_cl_iq2_xs_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 64; - const size_t size_sc = n_blk * 8; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_sc; - CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sc, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_iq2_xs; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/32, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_sc = size_sc; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_IQ2_XXS) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq2_xxs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq2_xxs(); - extra->noshuffle = ggml_cl_iq2_xxs_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 32; - const size_t size_sas = n_blk * 32; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_sas + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_sas; - CL_CHECK((extra->sas = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sas, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_iq2_xxs; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sas)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); - transpose_2d_as_32b(backend_ctx, extra->sas, extra->sas, size_sas, k/32, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_sas = size_sas; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_Q1_0) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q1_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q1_0(); - - // q1_0 block = ggml_half d + (QK1_0/8) quant bytes = 2 + 16 = 18 bytes - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)/8); - GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - // The original tensor memory is divided into scales and quants, i.e., - // we first store scales, then quants. - cl_buffer_region region; - - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for quants. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_kernel kernel = backend_ctx->kernel_convert_block_q1_0; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - - // q is uint32 (32 sign bits each); d is one half per 128-block. -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (enable_adreno_trans_weight(backend_ctx, tensor)) { - int M = tensor->ne[1]; // ne01 - int K = tensor->ne[0]; // ne00 - - GGML_ASSERT(K % 128 == 0); - GGML_ASSERT(M % 4 == 0); - GGML_ASSERT(tensor->ne[2] == 1); - GGML_ASSERT(tensor->ne[3] == 1); - - transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/32, M); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/128, M); - } // end transpose -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - return; - } - - if (tensor->type == GGML_TYPE_Q2_0) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q2_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q2_0(); - extra->noshuffle = ggml_cl_q2_0_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 16; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_q2_0; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/64, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - // We separate the quantized bits and scale from block_q4_0 by using an - // additional kernel, where each thread handles a block. We first read the - // original weights into a temporary buffer, then create two separate - // buffers for quantized bits and scales, which are then populated by the - // conversion kernel. - if (tensor->type == GGML_TYPE_Q4_0) { - // Views can't SoA-ify here — parent owns the layout (see q8_0 guard). - // A view of an AoS tensor (the KV cache, written by a state restore) - // is written in place. - if (tensor->view_src != nullptr || !ggml_is_contiguous(tensor)) { - if (!ggml_cl_is_q4_0_soa(tensor)) { - ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; - CL_CHECK(clEnqueueWriteBuffer( - queue, extra_aos->data_device, CL_TRUE, - extra_aos->offset + tensor->view_offs + offset, - size, data, 0, NULL, NULL)); - } - return; - } - // Tensors should have been preallocated, therefore they should - // already have ggml_tensor_extra_cl as extra. - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q4_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q4_0(); - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); - - // We consider the specified offset arg as always, although For weights - // the offset arg should be 0 (we do not assert this). - //GGML_ASSERT(offset == 0); - - // We create subbuffers from the original tensor buffer for scales and - // quants - i.e., scales and quants are aliases into the buffer object - // that backs the original tensor. This is a cleaner way to adapt to the - // new memory management. - // In the old code, we allocate new buffers for scales and quants - // respectively, which could still be done but would result in double - // allocation; properly deallocating the preallocated buffer that backs - // the tensors is tricky and would leak the backend specific information - // into the general backend code. - // Does this create misaligned subbuffers (alignment is 1024) in certain - // cases ? - cl_buffer_region region; - - // The original tensor memory is divided into scales and quants, i.e., - // we first store scales, then quants. - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for quants. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno moe q4_0 kernel needs special transpose and unshuffling - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_0_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - // Create image for Q - cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_q = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->q } - }; - extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); - tensor->extra = extra; - // MoE tensors are also SOA'ed - ctx->q4_0_soa_tensors.insert(tensor); - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_0; - - // The optimized kernels need weights in natural order, so unshuffle. - if (use_adreno_kernels(backend_ctx, tensor)) { - kernel = backend_ctx->kernel_convert_block_q4_0_noshuffle; - } -#else - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_0; -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - ctx->q4_0_soa_tensors.insert(tensor); - - // transpose the weights and scales -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Only do transpose for large, non batched matrix - // TODO: use preallocated images instead of sub-buffer then image - if (use_adreno_kernels(backend_ctx, tensor)) { - int M = tensor->ne[1]; - int K = tensor->ne[0]; - - GGML_ASSERT(K % 32 == 0); - - if (use_q4_0_bin_kernels(backend_ctx, tensor)) { - cl_int err; - cl_image_format wimg_fmt; - cl_image_desc wimg_desc; - - // transpose quants as 32-bit words (M-first) - GGML_ASSERT(M % 64 == 0); - transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K / 8, M); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K / 32, M); - - wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&wimg_desc, 0, sizeof(wimg_desc)); - wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - wimg_desc.image_width = (size_t)M * K / 8; - wimg_desc.buffer = extra->q; - CL_CHECK((extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); - - wimg_fmt = { CL_R, CL_HALF_FLOAT }; - memset(&wimg_desc, 0, sizeof(wimg_desc)); - wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - wimg_desc.image_width = (size_t)M * K / 32; - wimg_desc.buffer = extra->d; - CL_CHECK((extra->d_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); - } else { - // Transpose q and d as ushort - transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); - } - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - return; - } - if (tensor->type == GGML_TYPE_Q4_1) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q4_1 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q4_1(); - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_m = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - GGML_ASSERT(size_d + size_m + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); - - cl_buffer_region region; - - // The original tensor memory is divided into scales and quants, i.e., - // we first store scales, mins, then quants. - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for mins. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_m; - extra->m = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for quants. - region.origin = align_to(previous_origin + size_m, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno moe q4_1 kernel needs special transpose and unshuffling - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_1_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - // Create image for Q - cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_q = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->q } - }; - extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); - tensor->extra = extra; - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - // normal q4_1 repack -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_1; - - if (use_adreno_kernels(backend_ctx, tensor)) { - kernel = backend_ctx->kernel_convert_block_q4_1_noshuffle; - } -#else - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_1; -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_kernels(backend_ctx, tensor)) { - - int M = tensor->ne[1]; - int K = tensor->ne[0]; - - GGML_ASSERT(K % 32 == 0); - - // Transpose q as ushort - transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); - // Transpose d as ushort - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); - // Transpose m as ushort - transpose_2d_as_16b(backend_ctx, extra->m, extra->m, size_m, K/32, M); - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - return; - } - if (tensor->type == GGML_TYPE_Q5_0) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q5_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q5_0(); - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_qs = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(int32_t); - GGML_ASSERT(size_d + size_qs + size_qh == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); - - cl_buffer_region region; - - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for qh. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_qh; - extra->qh = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for qs. - region.origin = align_to(previous_origin + size_qh, backend_ctx->alignment); - region.size = size_qs; - extra->qs = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno moe q5_0 kernel needs special transpose and unshuffling - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_0_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - // Create image for Q - cl_image_format img_format_qs = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_qs = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->qs } - }; - extra->qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_qs, &img_desc_qs, NULL, &err); - tensor->extra = extra; - - // Generic dp4a MoE path - { - static const char * q5dp4a_env = getenv("GGML_OPENCL_Q5_MOE_DP4A"); - const bool q5dp4a = q5dp4a_env ? (atoi(q5dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - if (q5dp4a && ne02 > 1 && (ne00 % 32 == 0)) { - size_t nb32 = (size_t)ne00 / 32; - size_t sc_elems = (size_t)ne02 * ne01 * nb32 * 2; - size_t mn_elems = (size_t)ne02 * ne01 * nb32; - extra->scale = clCreateBuffer(context, CL_MEM_READ_WRITE, sc_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); - extra->min = clCreateBuffer(context, CL_MEM_READ_WRITE, mn_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); - cl_kernel ek = backend_ctx->kernel_moe_expand_scale_q5_0; - CL_CHECK(clSetKernelArg(ek, 0, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(ek, 1, sizeof(cl_mem), &extra->scale)); - CL_CHECK(clSetKernelArg(ek, 2, sizeof(cl_mem), &extra->min)); - CL_CHECK(clSetKernelArg(ek, 3, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(ek, 4, sizeof(int), &ne01)); - size_t eg[3] = { (size_t)(((ne01 + 63) / 64) * 64), nb32, (size_t)ne02 }; - size_t el[3] = { 64, 1, 1 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, ek, 3, NULL, eg, el, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - } - } - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_0_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - - int M = tensor->ne[1]; - int K = tensor->ne[0]; - GGML_ASSERT(K % 32 == 0); - - // Transpose qs as ushort - transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, K/4, M); - // Transpose qh as uchar - transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, K/8, M); - // Transpose d as ushort - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_0; - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64) * 64, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - return; - } - if (tensor->type == GGML_TYPE_Q5_1) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q5_1 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q5_1(); - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_m = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_qs = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(int32_t); - GGML_ASSERT(size_d + size_m + size_qs + size_qh == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); - - cl_buffer_region region; - - // The original tensor memory is divided into scales and quants, i.e., - // we first store scales, mins, then quants. - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for mins. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_m; - extra->m = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for qh. - region.origin = align_to(previous_origin + size_m, backend_ctx->alignment); - region.size = size_qh; - extra->qh = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for qs. - region.origin = align_to(previous_origin + size_qh, backend_ctx->alignment); - region.size = size_qs; - extra->qs = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno moe q5_1 kernel needs special transpose and unshuffling - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_1_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->m)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - // Create image for Q - cl_image_format img_format_qs = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_qs = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->qs } - }; - extra->qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_qs, &img_desc_qs, NULL, &err); - tensor->extra = extra; - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_1_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->m)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - - int M = tensor->ne[1]; - int K = tensor->ne[0]; - GGML_ASSERT(K % 32 == 0); - - // Transpose qs as ushort - transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, K/4, M); - // Transpose qh as uchar - transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, K/8, M); - // Transpose d as ushort - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); - // Transpose m as ushort - transpose_2d_as_16b(backend_ctx, extra->m, extra->m, size_m, K/32, M); - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_1; - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->m)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64) * 64, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - return; - } - if (tensor->type == GGML_TYPE_MXFP4) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_mxfp4 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_mxfp4(); - - size_t size_e = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(char); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - GGML_ASSERT(size_e + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); - - // The original tensor memory is divided into scales and quants, i.e., - // we first store scales, then quants. - cl_buffer_region region; - - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_e; - extra->e = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for quants. - region.origin = align_to(previous_origin + size_e, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno moe mxfp4 kernel needs special transpose and unshuffling - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_mxfp4_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->e)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - tensor->extra = extra; - - // Create image for Q - cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_q = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->q } - }; - extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); - tensor->extra = extra; - - return; - } - -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_convert_block_mxfp4; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->e)); - - size_t global_work_size[3] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[3] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - // Create image for Q - cl_image_format img_format_q = {CL_RG, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_q = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor)/32*2), - 0, 0, 0, 0, 0, 0, 0, - { extra->q } - }; - extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); - tensor->extra = extra; - - return; - } - if (tensor->type == GGML_TYPE_Q8_0) { - // Views share the parent's buffer; parent owns SoA conversion. - // A view of an AoS tensor (the KV cache, written by a state restore) - // is written in place. - if (tensor->view_src != nullptr || !ggml_is_contiguous(tensor)) { - if (!ggml_cl_is_q8_0_soa(tensor)) { - ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; - CL_CHECK(clEnqueueWriteBuffer( - queue, extra_aos->data_device, CL_TRUE, - extra_aos->offset + tensor->view_offs + offset, - size, data, 0, NULL, NULL)); - } - return; - } - - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q8_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q8_0(); - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)*sizeof(char)); - GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); - - // The original tensor memory is divided into scales and quants, i.e., - // we first store scales, then quants. - cl_buffer_region region; - - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for quants. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_kernel kernel = backend_ctx->kernel_convert_block_q8_0; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - ctx->q8_0_soa_tensors.insert(tensor); - - // Generic dp4a MoE path (opt-in GGML_OPENCL_Q8_MOE_DP4A) -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - { - static const char * q8dp4a_env = getenv("GGML_OPENCL_Q8_MOE_DP4A"); - const bool q8dp4a = q8dp4a_env ? (atoi(q8dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - if (q8dp4a && tensor->ne[2] > 1 && (tensor->ne[0] % 32 == 0)) { - int ne00 = (int)tensor->ne[0]; - int ne01 = (int)tensor->ne[1]; - int ne02 = (int)tensor->ne[2]; - size_t nb32 = (size_t)ne00 / 32; - size_t scale_elems = (size_t)ne02 * ne01 * nb32 * 2; // 2 per-16-seg scales / 32-block - extra->scale = clCreateBuffer(context, CL_MEM_READ_WRITE, scale_elems * sizeof(cl_half), NULL, &err); - CL_CHECK(err); - cl_kernel ek = backend_ctx->kernel_moe_expand_scale_q8_0; - CL_CHECK(clSetKernelArg(ek, 0, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(ek, 1, sizeof(cl_mem), &extra->scale)); - CL_CHECK(clSetKernelArg(ek, 2, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(ek, 3, sizeof(int), &ne01)); - size_t eg[3] = { (size_t)(((ne01 + 63) / 64) * 64), nb32, (size_t)ne02 }; - size_t el[3] = { 64, 1, 1 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, ek, 3, NULL, eg, el, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - } - } -#endif - - // Transpose the weights and scales -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (enable_adreno_trans_weight(backend_ctx, tensor)) { - - int M = tensor->ne[1]; // ne01 - int K = tensor->ne[0]; // ne00 - - GGML_ASSERT(K % 32 == 0); - GGML_ASSERT(M % 4 == 0); - GGML_ASSERT(tensor->ne[2] == 1); - GGML_ASSERT(tensor->ne[3] == 1); - - transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/4, M); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); - } // end transpose -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - return; - } - if (tensor->type == GGML_TYPE_IQ4_NL) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq4_nl * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq4_nl(); - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)/2); - GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); - - cl_buffer_region region; - - // Create subbuffer for scales. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for quants. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_convert_block_iq4_nl; - if (use_adreno_kernels(backend_ctx, tensor)) { - kernel = backend_ctx->kernel_convert_block_iq4_nl_noshuffle; - } - #else - cl_kernel kernel = backend_ctx->kernel_convert_block_iq4_nl; - #endif - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64)*64, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_kernels(backend_ctx, tensor)) { - int M = tensor->ne[1]; - int K = tensor->ne[0]; - GGML_ASSERT(K % 32 == 0); - - // Transpose q as ushort - transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); - // Transpose d as ushort - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); - } -#endif - return; - } - if (tensor->type == GGML_TYPE_IQ4_XS) { - GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_iq4_xs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq4_xs(); - extra->noshuffle = ggml_cl_iq4_xs_use_noshuffle(backend_ctx, tensor); - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - const size_t n_blk = ggml_nelements(tensor) / blck; - - const size_t size_qs = n_blk * 128; - const size_t size_sl = n_blk * 4; - const size_t size_sh = n_blk * 2; - const size_t size_d = n_blk * 2; - GGML_ASSERT(size_qs + size_sl + size_sh + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer( - queue, data_device, CL_TRUE, 0, - ggml_nbytes(tensor), data, 0, NULL, NULL)); - - cl_buffer_region region; - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_qs; - CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); - region.size = size_sl; - CL_CHECK((extra->sl = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sl, backend_ctx->alignment); - region.size = size_sh; - CL_CHECK((extra->sh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - region.origin = align_to(region.origin + size_sh, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = extra->noshuffle ? backend_ctx->kernel_convert_block_iq4_xs_noshuffle : backend_ctx->kernel_convert_block_iq4_xs; - cl_ulong nb_arg = (cl_ulong)n_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sl)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->sh)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clReleaseMemObject(data_device)); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (extra->noshuffle) { - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); - transpose_2d_as_32b(backend_ctx, extra->sl, extra->sl, size_sl, k/256, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->sh, extra->sh, size_sh, k/256, m, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/256, m, true, true); - } -#endif - - extra->size_qs = size_qs; - extra->size_sl = size_sl; - extra->size_sh = size_sh; - extra->size_d = size_d; - - tensor->extra = extra; - return; - } - - if (tensor->type == GGML_TYPE_Q4_K) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q4_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q4_K(); - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_dm = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(3 * ggml_blck_size(tensor->type) / 64); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - GGML_ASSERT(size_d + size_dm + size_s + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "q4_K set_tensor: temp upload buffer alloc failed"); - - cl_buffer_region region; - - // Create subbuffer for d. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for mins. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_dm; - extra->dm = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for s. - region.origin = align_to(previous_origin + size_dm, backend_ctx->alignment); - region.size = size_s; - extra->s = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for quants. - region.origin = align_to(previous_origin + size_s, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_k_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_q = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->q } - }; - extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); - CL_CHECK(err); - tensor->extra = extra; - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Tiled-wide convert for the long-vocab lm_head/embed (opt-in). The embed/ - // output q4_K weight (token_embd.weight, ne1=vocab) is NOT matched by - // use_adreno_moe_kernels, so it lands here in the general branch. Produce - // the final 64-row-tiled canonical layout directly into q/d/dm/s (buffer - // sizes already match), read back by kernel_gemv_noshuffle_q4_k_f32_tiled. - if (use_q4k_tiled(backend_ctx, tensor)) { - cl_kernel tk = backend_ctx->kernel_convert_block_q4_k_tiled_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - - CL_CHECK(clSetKernelArg(tk, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(tk, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(tk, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(tk, 3, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(tk, 4, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(tk, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(tk, 6, sizeof(int), &ne01)); - - size_t gws[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t lws[] = {64, 1, 1}; - - cl_event tevt; - CL_CHECK(clEnqueueNDRangeKernel(queue, tk, 3, NULL, gws, lws, 0, NULL, &tevt)); - CL_CHECK(clWaitForEvents(1, &tevt)); - CL_CHECK(clReleaseMemObject(data_device)); - - extra->q_img = nullptr; - tensor->extra = extra; - return; - } - - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_K; - if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor)) { - kernel = backend_ctx->kernel_convert_block_q4_K_noshuffle; - } -#else - cl_kernel kernel = backend_ctx->kernel_convert_block_q4_K; -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - tensor->extra = extra; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor)) { - - int M = tensor->ne[1]; - int K = tensor->ne[0]; - - GGML_ASSERT(K % 32 == 0); - - if (use_q4_k_bin_kernels(backend_ctx, tensor)) { - cl_int err; - cl_image_format wimg_fmt; - cl_image_desc wimg_desc; - - // transpose quants as 32-bit words (M-first) - GGML_ASSERT(M % 64 == 0); - transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/8, M); - - wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&wimg_desc, 0, sizeof(wimg_desc)); - wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - wimg_desc.image_width = (size_t)M * K / 8; - wimg_desc.buffer = extra->q; - CL_CHECK((extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); - } else { - // Transpose q as ushort - transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); - } - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/256, M); - transpose_2d_as_16b(backend_ctx, extra->dm, extra->dm, size_dm, K/256, M); - - // Transpose s as uchar - transpose_2d_as_8b(backend_ctx, extra->s, extra->s, size_s, K/256*12, M, true, true); - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - return; - } - if (tensor->type == GGML_TYPE_Q5_K) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q5_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q5_K(); - - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/8; - size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(3*ggml_blck_size(tensor->type)/64); - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_dm = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - GGML_ASSERT(size_q + size_qh + size_s + size_d + size_dm == ggml_nbytes(tensor) && - "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "q5_K set_tensor: temp upload buffer alloc failed"); - - cl_buffer_region region; - - // Create subbuffer for d. - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_d; - extra->d = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - auto previous_origin = region.origin; - - // Create subbuffer for dm. - region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); - region.size = size_dm; - extra->dm = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for s. - region.origin = align_to(previous_origin + size_dm, backend_ctx->alignment); - region.size = size_s; - extra->s = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for q (lower 4 bits) - region.origin = align_to(previous_origin + size_s, backend_ctx->alignment); - region.size = size_q; - extra->q = clCreateSubBuffer( - extra_orig->data_device, CL_MEM_READ_WRITE, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - previous_origin = region.origin; - - // Create subbuffer for qh (upper 1 bit) - region.origin = align_to(previous_origin + size_q, backend_ctx->alignment); - region.size = size_qh; - CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - CL_CHECK(err); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_k_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_q = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->q } - }; - extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); - CL_CHECK(err); - tensor->extra = extra; - - // Generic dp4a MoE path - { - static const char * q5kdp4a_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A"); - const bool q5kdp4a = q5kdp4a_env ? (atoi(q5kdp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - if (q5kdp4a && ne02 > 1 && (ne00 % 256 == 0)) { - size_t nb32 = (size_t)ne00 / 32; - size_t sc_elems = (size_t)ne02 * ne01 * nb32 * 2; - size_t mn_elems = (size_t)ne02 * ne01 * nb32; - extra->scale = clCreateBuffer(context, CL_MEM_READ_WRITE, sc_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); - extra->min = clCreateBuffer(context, CL_MEM_READ_WRITE, mn_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); - cl_kernel ek = backend_ctx->kernel_moe_expand_scale_q5_K; - CL_CHECK(clSetKernelArg(ek, 0, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(ek, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(ek, 2, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(ek, 3, sizeof(cl_mem), &extra->scale)); - CL_CHECK(clSetKernelArg(ek, 4, sizeof(cl_mem), &extra->min)); - CL_CHECK(clSetKernelArg(ek, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(ek, 6, sizeof(int), &ne01)); - size_t eg[3] = { (size_t)(((ne01 + 63) / 64) * 64), (size_t)(ne00 / 256), (size_t)ne02 }; - size_t el[3] = { 64, 1, 1 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, ek, 3, NULL, eg, el, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - } - } - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_K; - if (enable_adreno_trans_weight_q5_K(backend_ctx, tensor)) { - kernel = backend_ctx->kernel_convert_block_q5_K_noshuffle; - } -#else - cl_kernel kernel = backend_ctx->kernel_convert_block_q5_K; -#endif - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - extra->size_q = size_q; - extra->size_qh = size_qh; - extra->size_s = size_s; - extra->size_d = size_d; - extra->size_dm = size_dm; - - tensor->extra = extra; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (enable_adreno_trans_weight_q5_K(backend_ctx, tensor)) { - - int M = tensor->ne[1]; - int K = tensor->ne[0]; - - GGML_ASSERT(K % 32 == 0); - - if (use_q5_k_bin_kernels(backend_ctx, tensor)) { - cl_int err; - cl_image_format wimg_fmt; - cl_image_desc wimg_desc; - - // transpose q as 32-bit words (M-first); qh/d/dm stay in their existing layout - // (both new ILA kernels read qh via the existing [K/8][M] uchar plane directly). - GGML_ASSERT(M % 64 == 0); - transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/8, M); - - wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&wimg_desc, 0, sizeof(wimg_desc)); - wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - wimg_desc.image_width = (size_t)M * K / 8; - wimg_desc.buffer = extra->q; - CL_CHECK((extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); - - // Transpose s as uchar - transpose_2d_as_8b(backend_ctx, extra->s, extra->s, size_s, K/256*12, M, true, true); - } else { - // Transpose q as ushort - transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); - } - transpose_2d_as_8b (backend_ctx, extra->qh, extra->qh, size_qh, K/8, M); - transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/256, M); - transpose_2d_as_16b(backend_ctx, extra->dm, extra->dm, size_dm, K/256, M); - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - return; - } - if (tensor->type == GGML_TYPE_Q6_K) { - ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; - GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); - - // Allocate the new extra and create aliases from the original. - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ggml_tensor_extra_cl_q6_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q6_K(); - - size_t size_ql = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/4; - size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/16; - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - GGML_ASSERT(size_ql + size_qh + size_s + size_d == ggml_nbytes(tensor) && - "Incorrect tensor size"); - - cl_int err; - cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); - GGML_ASSERT(data_device != NULL && "q6_K set_tensor: temp upload buffer alloc failed"); - - cl_buffer_region region; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Adreno MoE Q6_K kernel needs special transposed layout - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - size_t moe_size_ql = (size_t)(ggml_nelements(tensor) / 8) * sizeof(uint32_t); // 4 bits per element - size_t moe_size_qh = (size_t)(ggml_nelements(tensor) / 16) * sizeof(uint32_t); // 2 bits per element - size_t moe_size_s = size_s; - size_t moe_size_d = size_d; - - // Subbuffer for ql - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = moe_size_ql; - CL_CHECK((extra->ql = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - auto previous_origin = region.origin; - - // Subbuffer for qh - region.origin = align_to(previous_origin + moe_size_ql, backend_ctx->alignment); - region.size = moe_size_qh; - CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - - // Subbuffer for scales - region.origin = align_to(previous_origin + moe_size_qh, backend_ctx->alignment); - region.size = moe_size_s; - CL_CHECK((extra->s = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - - // Subbuffer for d - region.origin = align_to(previous_origin + moe_size_s, backend_ctx->alignment); - region.size = moe_size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_kernel kernel = backend_ctx->kernel_convert_block_q6_k_trans4_ns; - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->ql)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - // Create image for ql - cl_image_format img_format_ql = {CL_R, CL_UNSIGNED_INT32}; - cl_image_desc img_desc_ql = { - CL_MEM_OBJECT_IMAGE1D_BUFFER, - static_cast(ggml_nelements(tensor) / 8), - 0, 0, 0, 0, 0, 0, 0, - { extra->ql } - }; - extra->ql_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_ql, &img_desc_ql, NULL, &err); - tensor->extra = extra; - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - // Subbuffer for ql - region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); - region.size = size_ql; - CL_CHECK((extra->ql = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - auto previous_origin = region.origin; - - // Subbuffer for qh - region.origin = align_to(previous_origin + size_ql, backend_ctx->alignment); - region.size = size_qh; - CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - - // Subbuffer for scales - region.origin = align_to(previous_origin + size_qh, backend_ctx->alignment); - region.size = size_s; - CL_CHECK((extra->s = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - - // Create subbuffer for d. - region.origin = align_to(previous_origin + size_s, backend_ctx->alignment); - region.size = size_d; - CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - previous_origin = region.origin; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Tiled-wide convert for the long-vocab lm_head/embed (opt-in). The embed - // /output q6_K weight (e.g. token_embd.weight, ne1=vocab) is NOT matched by - // use_adreno_moe_kernels, so it lands here in the general branch. Produce - // the final 64-row-tiled canonical layout directly into ql/qh/s/d (buffer - // sizes already match), read back by kernel_gemv_noshuffle_q6_K_f32_tiled. - // Bypasses the plain-SOA convert + per-array transpose below. - if (use_q6k_tiled(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_convert_block_q6_k_tiled_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->ql)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - - size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - extra->size_ql = size_ql; - extra->size_qh = size_qh; - extra->size_s = size_s; - extra->size_d = size_d; - tensor->extra = extra; - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - // Flatten the weights - cl_kernel kernel; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - kernel = backend_ctx->kernel_convert_block_q6_K; - if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor)) { - kernel = backend_ctx->kernel_convert_block_q6_K_noshuffle; - } -#else - kernel = backend_ctx->kernel_convert_block_q6_K; -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - cl_uchar mask = 0xff; - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->ql)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64)*64, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - - extra->size_ql = size_ql; - extra->size_qh = size_qh; - extra->size_s = size_s; - extra->size_d = size_d; - - tensor->extra = extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor)) { - cl_int M = tensor->ne[1]; // ne01 - cl_int K = tensor->ne[0]; // ne00 - - if (use_q6_k_bin_kernels(backend_ctx, tensor)) { - GGML_ASSERT(K % 256 == 0); - GGML_ASSERT(M % 64 == 0); - - transpose_2d_as_32b(backend_ctx, extra->ql, extra->ql, size_ql, K/8, M); - transpose_2d_as_32b(backend_ctx, extra->qh, extra->qh, size_qh, K/16, M); - - cl_image_format wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; - cl_image_desc wimg_desc; - memset(&wimg_desc, 0, sizeof(wimg_desc)); - wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - wimg_desc.image_width = static_cast(ggml_nelements(tensor) / 8); - wimg_desc.buffer = extra->ql; - CL_CHECK((extra->ql_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); - - memset(&wimg_desc, 0, sizeof(wimg_desc)); - wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - wimg_desc.image_width = static_cast(ggml_nelements(tensor) / 16); - wimg_desc.buffer = extra->qh; - CL_CHECK((extra->qh_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); - } else { - // Transpose ql as ushort - transpose_2d_as_16b(backend_ctx, - extra->ql, extra->ql, size_ql, K/4, M); - - // Transpose qh as uchar - transpose_2d_as_8b(backend_ctx, - extra->qh, extra->qh, size_qh, K/4, M); - - // Transpose s as ushort - transpose_2d_as_16b(backend_ctx, - extra->s, extra->s, size_s, K/16/2, M); - } - // Transpose d as ushort - transpose_2d_as_16b(backend_ctx, - extra->d, extra->d, size_d, K/256, M); - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - return; - } -#endif // GGML_OPENCL_SOA_Q - - // convert bf16 to f16 and store as f16 in device buffer - if (tensor->type == GGML_TYPE_BF16) { - GGML_ASSERT(offset % sizeof(ggml_fp16_t) == 0 && size % sizeof(ggml_fp16_t) == 0 - && "Offset and size must be multiples of 2 for bf16 tensors"); - - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; - GGML_ASSERT(extra); - - cl_ulong n_elements = size / sizeof(ggml_fp16_t); - cl_ulong off_dst = (extra->offset + tensor->view_offs + offset) / sizeof(ggml_fp16_t); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, - size, const_cast(data), &err); - CL_CHECK(err); - - cl_kernel kernel = backend_ctx->kernel_convert_bf16_to_f16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &off_dst)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &n_elements)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_elements, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseMemObject(data_device)); - CL_CHECK(clReleaseEvent(evt)); - - return; - } - - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; - GGML_ASSERT(extra); - - // a view reuses its parent's extra, whose offset does not include view_offs - CL_CHECK(clEnqueueWriteBuffer( - queue, extra->data_device, CL_TRUE, extra->offset + tensor->view_offs + offset, - size, data, 0, NULL, NULL)); - - GGML_UNUSED(buffer); -} - -static void ggml_backend_opencl_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { - GGML_ASSERT(tensor->extra); - - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; - ggml_backend_opencl_context *backend_ctx = dev_ctx->backend_ctx; - - cl_context context = backend_ctx->context; - cl_command_queue queue = backend_ctx->queue; - - // Make sure all previously submitted commands in other devices are finished. - sync_with_other_backends(backend_ctx); - -#ifdef GGML_OPENCL_SOA_Q - if (tensor->type == GGML_TYPE_Q2_K) { - ggml_tensor_extra_cl_q2_K * extra = (ggml_tensor_extra_cl_q2_K *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, sc = extra->sc, dm = extra->dm; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_sc, buf_dm; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - buf_sc.allocate(context, extra->size_sc); - buf_dm.allocate(context, extra->size_dm); - qs = buf_qs.buffer; - sc = buf_sc.buffer; - dm = buf_dm.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/16, true, true); - transpose_2d_as_32b(backend_ctx, extra->dm, dm, extra->size_dm, m, k/(int)blck, true, true); - } -#endif - cl_kernel kernel = extra->noshuffle ? backend_ctx->kernel_restore_block_q2_k_noshuffle - : backend_ctx->kernel_restore_block_q2_K; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_Q3_K) { - ggml_tensor_extra_cl_q3_K * extra = (ggml_tensor_extra_cl_q3_K *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, hm = extra->hm, sc = extra->sc, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_hm, buf_sc, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - buf_hm.allocate(context, extra->size_hm); - buf_sc.allocate(context, extra->size_sc); - buf_d.allocate(context, extra->size_d); - qs = buf_qs.buffer; - hm = buf_hm.buffer; - sc = buf_sc.buffer; - d = buf_d.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); - transpose_2d_as_8b(backend_ctx, extra->hm, hm, extra->size_hm, m, k/8, true, true); - transpose_2d_as_32b(backend_ctx, extra->sc, sc, extra->size_sc, m, 3*k/(int)blck, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); - } -#endif - cl_kernel kernel = extra->noshuffle ? backend_ctx->kernel_restore_block_q3_k_noshuffle - : backend_ctx->kernel_restore_block_q3_K; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &hm)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_IQ3_S) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq3_s * extra = (ggml_tensor_extra_cl_iq3_s *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, sg = extra->sg, qh = extra->qh, sc = extra->sc, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_sg, buf_qh, buf_sc, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - buf_sg.allocate(context, extra->size_sg); - buf_qh.allocate(context, extra->size_qh); - buf_sc.allocate(context, extra->size_sc); - buf_d.allocate(context, extra->size_d); - - qs = buf_qs.buffer; - sg = buf_sg.buffer; - qh = buf_qh.buffer; - sc = buf_sc.buffer; - d = buf_d.buffer; - - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); - transpose_2d_as_8b(backend_ctx, extra->sg, sg, extra->size_sg, m, k/8, true, true); - transpose_2d_as_8b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/32, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/64, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/256, true, true); - } -#endif - - cl_kernel kernel = backend_ctx->kernel_restore_block_iq3_s; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_IQ3_XXS) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq3_xxs * extra = (ggml_tensor_extra_cl_iq3_xxs *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, sas = extra->sas, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_sas, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - buf_sas.allocate(context, extra->size_sas); - buf_d.allocate(context, extra->size_d); - - qs = buf_qs.buffer; - sas = buf_sas.buffer; - d = buf_d.buffer; - - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); - transpose_2d_as_32b(backend_ctx, extra->sas, sas, extra->size_sas, m, k/32, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/256, true, true); - } -#endif - - cl_kernel kernel = backend_ctx->kernel_restore_block_iq3_xxs; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_IQ1_M) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq1_m * extra = (ggml_tensor_extra_cl_iq1_m *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, qh = extra->qh, sc = extra->sc; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_qh, buf_sc; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - qs = buf_qs.buffer; - buf_qh.allocate(context, extra->size_qh); - qh = buf_qh.buffer; - buf_sc.allocate(context, extra->size_sc); - sc = buf_sc.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); - transpose_2d_as_8b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/16, true, true); - transpose_2d_as_16b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/64, true, true); - } -#endif - cl_kernel kernel = backend_ctx->kernel_restore_block_iq1_m; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_IQ1_S) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq1_s * extra = (ggml_tensor_extra_cl_iq1_s *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, qh = extra->qh, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_qh, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - qs = buf_qs.buffer; - buf_qh.allocate(context, extra->size_qh); - qh = buf_qh.buffer; - buf_d.allocate(context, extra->size_d); - d = buf_d.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); - transpose_2d_as_16b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/32, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); - } -#endif - cl_kernel kernel = backend_ctx->kernel_restore_block_iq1_s; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_IQ2_S) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq2_s * extra = (ggml_tensor_extra_cl_iq2_s *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, sg = extra->sg, qh = extra->qh, sc = extra->sc, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_sg, buf_qh, buf_sc, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - qs = buf_qs.buffer; - buf_sg.allocate(context, extra->size_sg); - sg = buf_sg.buffer; - buf_qh.allocate(context, extra->size_qh); - qh = buf_qh.buffer; - buf_sc.allocate(context, extra->size_sc); - sc = buf_sc.buffer; - buf_d.allocate(context, extra->size_d); - d = buf_d.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); - transpose_2d_as_8b(backend_ctx, extra->sg, sg, extra->size_sg, m, k/8, true, true); - transpose_2d_as_8b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/32, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/32, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); - } -#endif - cl_kernel kernel = backend_ctx->kernel_restore_block_iq2_s; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_IQ2_XS) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq2_xs * extra = (ggml_tensor_extra_cl_iq2_xs *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, sc = extra->sc, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_sc, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - qs = buf_qs.buffer; - buf_sc.allocate(context, extra->size_sc); - sc = buf_sc.buffer; - buf_d.allocate(context, extra->size_d); - d = buf_d.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_16b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); - transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/32, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); - } -#endif - cl_kernel kernel = backend_ctx->kernel_restore_block_iq2_xs; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_IQ2_XXS) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq2_xxs * extra = (ggml_tensor_extra_cl_iq2_xxs *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, sas = extra->sas, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_sas, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - qs = buf_qs.buffer; - buf_sas.allocate(context, extra->size_sas); - sas = buf_sas.buffer; - buf_d.allocate(context, extra->size_d); - d = buf_d.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); - transpose_2d_as_32b(backend_ctx, extra->sas, sas, extra->size_sas, m, k/32, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); - } -#endif - cl_kernel kernel = backend_ctx->kernel_restore_block_iq2_xxs; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_Q1_0) { - ggml_tensor_extra_cl_q1_0 * extra = (ggml_tensor_extra_cl_q1_0 *)tensor->extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (enable_adreno_trans_weight(backend_ctx, tensor)) { - ggml_cl_buffer buf_trans_q; - ggml_cl_buffer buf_trans_d; - ggml_cl_buffer buf_unpacked; - - int M = tensor->ne[1]; - int K = tensor->ne[0]; - - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)/8); - - buf_trans_q.allocate(backend_ctx->context, size_q); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/32); - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/128); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q1_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } -#endif - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q1_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer(queue, data_device, CL_TRUE, offset, size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - - if (tensor->type == GGML_TYPE_Q2_0) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_q2_0 * extra = (ggml_tensor_extra_cl_q2_0 *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - qs = buf_qs.buffer; - buf_d.allocate(context, extra->size_d); - d = buf_d.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/64, true, true); - } -#endif - - cl_kernel kernel = backend_ctx->kernel_restore_block_q2_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - // In end-to-end runs, get_tensor is usually used to get back the logits, - // where we can simply do clEnqueueReadBuffer since they are f32. - // However, in test-backend-ops, the GPU graph is copied to the CPU backend, - // which requires reading back quantized weight tensors. - // To properly support this, we need to restore block_q4_0 struct arrays - // from the flattened buffers. - if (tensor->type == GGML_TYPE_Q4_0) { - // KV-cache q4_0 stays AoS — direct readback, no SoA restore. - if (!ggml_cl_is_q4_0_soa(tensor)) { - ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; - CL_CHECK(clEnqueueReadBuffer( - queue, extra_aos->data_device, CL_TRUE, - extra_aos->offset + tensor->view_offs + offset, - size, data, 0, NULL, NULL)); - return; - } - // SoA extra lives on the parent tensor — follow view_src. - const ggml_tensor * extra_src = tensor->view_src != nullptr ? tensor->view_src : tensor; - ggml_tensor_extra_cl_q4_0 * extra = (ggml_tensor_extra_cl_q4_0 *)extra_src->extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_0_trans4_ns; - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (use_adreno_kernels(backend_ctx, tensor)) { - ggml_cl_buffer buf_trans_q; - ggml_cl_buffer buf_trans_d; - ggml_cl_buffer buf_unpacked; - - cl_int M = tensor->ne[1]; // ne01 - cl_int K = tensor->ne[0]; // ne00 - - GGML_ASSERT(K % 32 == 0); - GGML_ASSERT(M % 4 == 0); - - size_t size_q = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; - size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); - GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - buf_trans_q.allocate(backend_ctx->context, size_q); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - if (use_q4_0_bin_kernels(backend_ctx, tensor)) { - transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K / 8); - } else { - transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K / 4); - } - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_0_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); - - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } -#endif - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_Q4_1) { - ggml_tensor_extra_cl_q4_1 * extra = (ggml_tensor_extra_cl_q4_1 *)tensor->extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_1_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->m)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (use_adreno_kernels(backend_ctx, tensor)) { - static ggml_cl_buffer buf_trans_q; - static ggml_cl_buffer buf_trans_m; - static ggml_cl_buffer buf_trans_d; - static ggml_cl_buffer buf_unpacked; - - cl_int M = tensor->ne[1]; - cl_int K = tensor->ne[0]; - - GGML_ASSERT(K % ggml_blck_size(tensor->type) == 0); - - size_t size_q = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; - size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); - size_t size_m = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); - GGML_ASSERT(size_d + size_q + size_m == ggml_nbytes(tensor) && "Incorrect tensor size"); - - buf_trans_q.allocate(backend_ctx->context, size_q); - buf_trans_m.allocate(backend_ctx->context, size_m); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - // transpose q, d, m back - transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); - transpose_2d_as_16b(backend_ctx, extra->m, buf_trans_m.buffer, size_m, M, K/32); - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_1_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_m.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_F0)); - - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } -#endif - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_1; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->m)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_Q5_0) { - ggml_tensor_extra_cl_q5_0 * extra = (ggml_tensor_extra_cl_q5_0 *)tensor->extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - // TODO: use ggml_cl_buffer to manage this temporary buffer - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_0_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (use_adreno_kernels(backend_ctx, tensor)) { - ggml_cl_buffer buf_trans_qs; - ggml_cl_buffer buf_trans_qh; - ggml_cl_buffer buf_trans_d; - ggml_cl_buffer buf_unpacked; - - cl_int M = tensor->ne[1]; - cl_int K = tensor->ne[0]; - - GGML_ASSERT(K % 32 == 0); - - size_t size_qs = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; - size_t size_qh = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(int32_t); - size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); - - buf_trans_qs.allocate(backend_ctx->context, size_qs); - buf_trans_qh.allocate(backend_ctx->context, size_qh); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - transpose_2d_as_16b(backend_ctx, extra->qs, buf_trans_qs.buffer, size_qs, M, K/4); - transpose_2d_as_8b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/8); - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_0_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_qs.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_F0)); - - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_Q5_1) { - ggml_tensor_extra_cl_q5_1 * extra = (ggml_tensor_extra_cl_q5_1 *)tensor->extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - // TODO: use ggml_cl_buffer to manage this temporary buffer - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_1_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - - if (use_adreno_kernels(backend_ctx, tensor)) { - ggml_cl_buffer buf_trans_qs; - ggml_cl_buffer buf_trans_qh; - ggml_cl_buffer buf_trans_d; - ggml_cl_buffer buf_trans_m; - ggml_cl_buffer buf_unpacked; - - cl_int M = tensor->ne[1]; - cl_int K = tensor->ne[0]; - GGML_ASSERT(K % 32 == 0); - - size_t size_qs = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; - size_t size_qh = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(int32_t); - size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); - size_t size_m = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); - - buf_trans_qs.allocate(backend_ctx->context, size_qs); - buf_trans_qh.allocate(backend_ctx->context, size_qh); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_trans_m.allocate(backend_ctx->context, size_m); - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - // Transpose back: from col-major to row-major - transpose_2d_as_16b(backend_ctx, extra->qs, buf_trans_qs.buffer, size_qs, M, K/4); - transpose_2d_as_8b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/8); - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); - transpose_2d_as_16b(backend_ctx, extra->m, buf_trans_m.buffer, size_m, M, K/32); - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_1_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_qs.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_m.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); - - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, - ggml_nbytes(tensor), NULL, &err); - CL_CHECK(err); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_1; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_MXFP4) { - ggml_tensor_extra_cl_mxfp4 * extra = (ggml_tensor_extra_cl_mxfp4 *)tensor->extra; - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_restore_block_mxfp4_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->e)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; - size_t local_work_size[3] = {64, 2, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - cl_kernel kernel = backend_ctx->kernel_restore_block_mxfp4; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->e)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_Q8_0) { - // KV-cache q8_0 stays AoS (see Q4_0 branch). - if (!ggml_cl_is_q8_0_soa(tensor)) { - ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; - CL_CHECK(clEnqueueReadBuffer( - queue, extra_aos->data_device, CL_TRUE, - extra_aos->offset + tensor->view_offs + offset, - size, data, 0, NULL, NULL)); - return; - } - // SoA extra lives on the parent — follow view_src. - const ggml_tensor * extra_src = tensor->view_src != nullptr ? tensor->view_src : tensor; - ggml_tensor_extra_cl_q8_0 * extra = (ggml_tensor_extra_cl_q8_0 *)extra_src->extra; - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (enable_adreno_trans_weight(backend_ctx, tensor)) { - cl_kernel kernel = backend_ctx->kernel_restore_block_q8_0_trans; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - GGML_ASSERT(tensor->ne[2] == 1); - GGML_ASSERT(tensor->ne[3] == 1); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); - - size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), 1, 1}; - size_t local_work_size[3] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } -#endif - cl_kernel kernel = backend_ctx->kernel_restore_block_q8_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_IQ4_NL) { - ggml_tensor_extra_cl_iq4_nl * extra = (ggml_tensor_extra_cl_iq4_nl *)tensor->extra; - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_kernels(backend_ctx, tensor)) { - static ggml_cl_buffer buf_trans_q; - static ggml_cl_buffer buf_trans_d; - static ggml_cl_buffer buf_unpacked; - - cl_int M = tensor->ne[1]; - cl_int K = tensor->ne[0]; - GGML_ASSERT(K % 32 == 0); - - size_t size_q = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*(ggml_blck_size(tensor->type)/2); - size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); - GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); - - buf_trans_q.allocate(backend_ctx->context, size_q); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - // transpose q, d back - transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - cl_kernel kernel = backend_ctx->kernel_restore_block_iq4_nl_noshuffle; - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)n_blk, 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } -#endif - cl_kernel kernel = backend_ctx->kernel_restore_block_iq4_nl; - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)n_blk, 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_IQ4_XS) { - if (tensor->view_src) { - offset += tensor->view_offs; - tensor = tensor->view_src; - } - ggml_tensor_extra_cl_iq4_xs * extra = (ggml_tensor_extra_cl_iq4_xs *)tensor->extra; - - const size_t blck = (size_t)ggml_blck_size(tensor->type); - - ggml_cl_buffer buf_unpacked; - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; - cl_ulong nb_arg = (cl_ulong)n_blk; - - cl_mem qs = extra->qs, sl = extra->sl, sh = extra->sh, d = extra->d; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - ggml_cl_buffer buf_qs, buf_sl, buf_sh, buf_d; - if (extra->noshuffle) { - buf_qs.allocate(context, extra->size_qs); - buf_sl.allocate(context, extra->size_sl); - buf_sh.allocate(context, extra->size_sh); - buf_d.allocate(context, extra->size_d); - - qs = buf_qs.buffer; - sl = buf_sl.buffer; - sh = buf_sh.buffer; - d = buf_d.buffer; - const int m = tensor->ne[1]; - const int k = tensor->ne[0]; - transpose_2d_as_16b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); - transpose_2d_as_32b(backend_ctx, extra->sl, sl, extra->size_sl, m, k/256, true, true); - transpose_2d_as_16b(backend_ctx, extra->sh, sh, extra->size_sh, m, k/256, true, true); - transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/256, true, true); - } -#endif - - cl_kernel kernel = extra->noshuffle ? backend_ctx->kernel_restore_block_iq4_xs_noshuffle : backend_ctx->kernel_restore_block_iq4_xs; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sl)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &sh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); - - size_t gws[] = { (n_blk + 63) / 64 * 64 }; - size_t lws[] = { 64 }; - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - return; - } - - if (tensor->type == GGML_TYPE_Q4_K) { - ggml_tensor_extra_cl_q4_K * extra = (ggml_tensor_extra_cl_q4_K *)tensor->extra; - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Undo the 64-row-tiled canonical pack (kernel_convert_block_q4_k_tiled_ns). - // Without this, a read-back of a tiled weight returns the tiled bytes - // reinterpreted as block_q4_K -- which is how test-backend-ops builds its - // CPU reference (ggml_backend_graph_copy -> tensor_get), so the tiled path - // "failed" the suite while computing the correct product. - if (use_q4k_tiled(backend_ctx, tensor)) { - const int ne00v = tensor->ne[0]; - const int ne01v = tensor->ne[1]; - const int nbv = ne00v / 256; - const size_t n_blk = (size_t)nbv * ne01v; - - std::vector tq(n_blk*32); - std::vector td(n_blk), tdm(n_blk); - std::vector ts(n_blk*12); - CL_CHECK(clEnqueueReadBuffer(queue, extra->q, CL_TRUE, 0, tq.size()*4, tq.data(), 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->d, CL_TRUE, 0, td.size()*2, td.data(), 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->dm, CL_TRUE, 0, tdm.size()*2, tdm.data(), 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->s, CL_TRUE, 0, ts.size(), ts.data(), 0, NULL, NULL)); - - std::vector rebuilt(ggml_nbytes(tensor), 0); - for (int i01 = 0; i01 < ne01v; ++i01) { - const int rt = i01/64, rit = i01%64; - for (int i00 = 0; i00 < nbv; ++i00) { - uint8_t * b = rebuilt.data() + ((size_t)i00 + (size_t)i01*nbv)*144; - const int tb = rt*nbv + i00; - const size_t si = (size_t)tb*64 + rit; - - memcpy(b + 0, &td [si], 2); - memcpy(b + 2, &tdm[si], 2); - memcpy(b + 4, &ts[si*12], 12); - - uint32_t qw[32]; - for (int gr = 0; gr < 8; ++gr) { - const size_t base = ((size_t)tb*8 + gr)*64 + rit; - for (int j = 0; j < 4; ++j) qw[gr*4 + j] = tq[base*4 + j]; - } - uint8_t * q = b + 16; - for (int e = 0; e < 256; ++e) { - const int g = e>>6, w = e&63, h = w>>5, l = w&31; - const uint32_t code = (qw[e>>3] >> ((e&7)*4)) & 0xF; - q[g*32 + l] |= (uint8_t)(h ? (code << 4) : code); - } - } - } - memcpy(data, rebuilt.data() + offset, size); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_k_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor)) { - int M = tensor->ne[1]; - int K = tensor->ne[0]; - - size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_dm = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*12; - - static ggml_cl_buffer buf_trans_q; - static ggml_cl_buffer buf_trans_d; - static ggml_cl_buffer buf_trans_dm; - static ggml_cl_buffer buf_trans_s; - - buf_trans_q.allocate(backend_ctx->context, size_q); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_trans_dm.allocate(backend_ctx->context, size_dm); - buf_trans_s.allocate(backend_ctx->context, size_s); - - // Transpose q, d, dm, s back - if (use_q4_k_bin_kernels(backend_ctx, tensor)) { - transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/8); - } else { - transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); - } - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/256); - transpose_2d_as_16b(backend_ctx, extra->dm, buf_trans_dm.buffer, size_dm, M, K/256); - transpose_2d_as_8b (backend_ctx, extra->s, buf_trans_s.buffer, size_s, M, K/256*12, true, true); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_K_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_s.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_dm.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_K; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_Q5_K) { - ggml_tensor_extra_cl_q5_K * extra = (ggml_tensor_extra_cl_q5_K *)tensor->extra; - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_k_trans4_ns; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (enable_adreno_trans_weight_q5_K(backend_ctx, tensor)) { - int M = tensor->ne[1]; - int K = tensor->ne[0]; - - size_t size_q = extra->size_q; - size_t size_qh = extra->size_qh; - size_t size_s = extra->size_s; - size_t size_d = extra->size_d; - size_t size_dm = extra->size_dm; - - static ggml_cl_buffer buf_trans_q; - static ggml_cl_buffer buf_trans_qh; - static ggml_cl_buffer buf_trans_s; - static ggml_cl_buffer buf_trans_d; - static ggml_cl_buffer buf_trans_dm; - - buf_trans_q.allocate(backend_ctx->context, size_q); - buf_trans_qh.allocate(backend_ctx->context, size_qh); - buf_trans_s.allocate(backend_ctx->context, size_s); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_trans_dm.allocate(backend_ctx->context, size_dm); - - // bin kernel transposes s but src kernel does not - cl_mem buf_s = extra->s; - - if (use_q5_k_bin_kernels(backend_ctx, tensor)) { - transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/8); - transpose_2d_as_8b (backend_ctx, extra->s, buf_trans_s.buffer, size_s, M, K/256*12, true, true); - buf_s = buf_trans_s.buffer; - } else { - transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); - } - transpose_2d_as_8b (backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/8); - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/256); - transpose_2d_as_16b(backend_ctx, extra->dm, buf_trans_dm.buffer, size_dm, M, K/256); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_K_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_trans_dm.buffer)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - cl_kernel kernel = backend_ctx->kernel_restore_block_q5_K; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->dm)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (tensor->type == GGML_TYPE_Q6_K) { - ggml_tensor_extra_cl_q6_K * extra = (ggml_tensor_extra_cl_q6_K *)tensor->extra; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // Undo the 64-row-tiled canonical pack (kernel_convert_block_q6_k_tiled_ns). - // See the q4_K tiled restore above for why a read-back path is required. - if (use_q6k_tiled(backend_ctx, tensor)) { - const int ne00v = tensor->ne[0]; - const int ne01v = tensor->ne[1]; - const int nbv = ne00v / 256; - const size_t n_blk = (size_t)nbv * ne01v; - - std::vector tql(n_blk*32), tqh(n_blk*16); - std::vector ts(n_blk*16); - std::vector td(n_blk); - CL_CHECK(clEnqueueReadBuffer(queue, extra->ql, CL_TRUE, 0, tql.size()*4, tql.data(), 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->qh, CL_TRUE, 0, tqh.size()*4, tqh.data(), 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->s, CL_TRUE, 0, ts.size(), ts.data(), 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->d, CL_TRUE, 0, td.size()*2, td.data(), 0, NULL, NULL)); - - std::vector rebuilt(ggml_nbytes(tensor), 0); - for (int i01 = 0; i01 < ne01v; ++i01) { - const int rt = i01/64, rit = i01%64; - for (int i00 = 0; i00 < nbv; ++i00) { - uint8_t * b = rebuilt.data() + ((size_t)i00 + (size_t)i01*nbv)*210; - const int tb = rt*nbv + i00; - const size_t si = (size_t)tb*64 + rit; - - uint32_t qlw[32], qhw[16]; - for (int g = 0; g < 8; ++g) { - const size_t base = ((size_t)tb*8 + g)*64 + rit; - for (int j = 0; j < 4; ++j) qlw[g*4 + j] = tql[base*4 + j]; - } - for (int g = 0; g < 4; ++g) { - const size_t base = ((size_t)tb*4 + g)*64 + rit; - for (int j = 0; j < 4; ++j) qhw[g*4 + j] = tqh[base*4 + j]; - } - - uint8_t * ql = b; - uint8_t * qh = b + 128; - for (int e = 0; e < 256; ++e) { - const int n = (e >= 128) ? 1 : 0; - const int within = e - n*128, q = within/32, l = within%32; - const int off_ql = n*64, off_qh = n*32; - const uint8_t low4 = (qlw[e>>3] >> ((e&7)*4)) & 0xF; - const uint8_t hi2 = (qhw[e>>4] >> ((e&15)*2)) & 0x3; - if (q == 0) ql[off_ql + l] |= low4; - else if (q == 1) ql[off_ql + l + 32] |= low4; - else if (q == 2) ql[off_ql + l] |= (uint8_t)(low4 << 4); - else ql[off_ql + l + 32] |= (uint8_t)(low4 << 4); - qh[off_qh + l] |= (uint8_t)(hi2 << (q*2)); - } - memcpy(b + 192, &ts[si*16], 16); - memcpy(b + 208, &td[si], 2); - } - } - memcpy(data, rebuilt.data() + offset, size); - return; - } - if (use_adreno_moe_kernels(backend_ctx, tensor)) { - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_kernel kernel = backend_ctx->kernel_restore_block_q6_k_trans4_ns; - - cl_uchar mask_0F = 0x0F; - cl_uchar mask_F0 = 0xF0; - - int ne00 = tensor->ne[0]; - int ne01 = tensor->ne[1]; - int ne02 = tensor->ne[2]; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->ql)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); - - size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; - size_t local_work_size[] = {64, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } - if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor)) { - static ggml_cl_buffer buf_trans_ql; - static ggml_cl_buffer buf_trans_qh; - static ggml_cl_buffer buf_trans_s; - static ggml_cl_buffer buf_trans_d; - static ggml_cl_buffer buf_unpacked; - - cl_int M = tensor->ne[1]; // ne01 - cl_int K = tensor->ne[0]; // ne00 - - GGML_ASSERT(K % ggml_blck_size(tensor->type) == 0); - - size_t size_ql = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; - size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/4; - size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/16; - size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); - GGML_ASSERT(size_ql + size_qh + size_s + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); - - buf_trans_ql.allocate(backend_ctx->context, size_ql); - buf_trans_qh.allocate(backend_ctx->context, size_qh); - buf_trans_d.allocate(backend_ctx->context, size_d); - buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); - - cl_mem s_buffer; - if (use_q6_k_bin_kernels(backend_ctx, tensor)) { - transpose_2d_as_32b(backend_ctx, extra->ql, buf_trans_ql.buffer, size_ql, M, K/8); - transpose_2d_as_32b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/16); - // s is left row-major, untransposed, for the binary layout. - s_buffer = extra->s; - } else { - // transpose ql, qh, s and d back - buf_trans_s.allocate(backend_ctx->context, size_s); - transpose_2d_as_16b(backend_ctx, extra->ql, buf_trans_ql.buffer, size_ql, M, K/4); - transpose_2d_as_8b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/4); - transpose_2d_as_16b(backend_ctx, extra->s, buf_trans_s.buffer, size_s, M, K/16/2); - s_buffer = buf_trans_s.buffer; - } - transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/256); - - // unpack - cl_uchar mask = 0xFF; - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - cl_kernel kernel = backend_ctx->kernel_restore_block_q6_K_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_ql.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s_buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_d.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)n_blk, 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); - - return; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); - GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); - - cl_uchar mask = 0xFF; - cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); - cl_kernel kernel = backend_ctx->kernel_restore_block_q6_K; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->ql)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &n_blk)); - - size_t global_work_size[] = {(size_t)n_blk, 1, 1}; - size_t local_work_size[] = {1, 1, 1}; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, offset, - size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - return; - } -#endif // GGML_OPENCL_SOA_Q - - if (tensor->type == GGML_TYPE_BF16) { - GGML_ASSERT(offset % sizeof(ggml_fp16_t) == 0 && size % sizeof(ggml_fp16_t) == 0 - && "Offset and size must be multiples of 2 for bf16 tensors"); - - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; - GGML_ASSERT(extra); - - cl_ulong n_elements = size / sizeof(ggml_fp16_t); - cl_ulong off_src = (extra->offset + tensor->view_offs + offset) / sizeof(ggml_fp16_t); - - cl_int err; - cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err); - CL_CHECK(err); - - cl_kernel kernel = backend_ctx->kernel_convert_f16_to_bf16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &n_elements)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(n_elements, 64)*64, 1, 1 }; - size_t local_work_size[] = { 64, 1, 1 }; - - cl_event evt; - CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); - CL_CHECK(clWaitForEvents(1, &evt)); - CL_CHECK(clReleaseEvent(evt)); - - CL_CHECK(clEnqueueReadBuffer( - queue, data_device, CL_TRUE, 0, size, data, 0, NULL, NULL)); - CL_CHECK(clReleaseMemObject(data_device)); - - return; - } - - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; - - CL_CHECK(clEnqueueReadBuffer( - queue, extra->data_device, CL_TRUE, extra->offset + tensor->view_offs + offset, - size, data, 0, NULL, NULL)); - - GGML_UNUSED(buffer); -} - -static void ggml_backend_opencl_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; - ggml_backend_opencl_context * backend_ctx = dev_ctx->backend_ctx; - - cl_command_queue queue = backend_ctx->queue; - - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - for (cl_mem buf : ctx->buffer) { - CL_CHECK(clEnqueueFillBuffer(queue, buf, &value, sizeof(value), 0, buffer->size, 0, NULL, NULL)); - } - CL_CHECK(clFinish(queue)); -} - -static void ggml_backend_opencl_buffer_reset(ggml_backend_buffer_t buffer) { - ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - ctx->reset(); -} - -static ggml_backend_buffer_i ggml_backend_opencl_buffer_interface = { - /* .free_buffer = */ ggml_backend_opencl_buffer_free_buffer, - /* .get_base = */ ggml_backend_opencl_buffer_get_base, - /* .init_tensor = */ ggml_backend_opencl_buffer_init_tensor, - /* .memset_tensor = */ NULL, - /* .set_tensor = */ ggml_backend_opencl_buffer_set_tensor, - /* .get_tensor = */ ggml_backend_opencl_buffer_get_tensor, - /* .set_tensor_2d = */ NULL, - /* .get_tensor_2d = */ NULL, - /* .cpy_tensor = */ NULL, - /* .clear = */ ggml_backend_opencl_buffer_clear, - /* .reset = */ ggml_backend_opencl_buffer_reset, - /* .set_tensor_n = */ NULL, - /* .get_tensor_n = */ NULL, - /* .cpy_tensor_n = */ NULL, -}; - -// -// buffer type -// - -static const char * ggml_backend_opencl_buffer_type_get_name(ggml_backend_buffer_type_t buffer_type) { - return "OpenCL"; - - GGML_UNUSED(buffer_type); -} - -static ggml_backend_buffer_t ggml_backend_opencl_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buffer_type, size_t size) { - ggml_backend_opencl_context *backend_ctx = ggml_cl_init(buffer_type->device); - - if (!backend_ctx->program_cache_initialized) { - backend_ctx->program_cache = cl_program_cache_init(backend_ctx->device); - backend_ctx->program_cache_initialized = true; - } - load_cl_kernels(backend_ctx); - - // clCreateBuffer returns -61 for size 0 - size = std::max(size, (size_t)1); - - cl_int err; - cl_mem mem = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size, NULL, &err); - // On Adreno X1-85 the device pool intermittently fails at hundreds of MB - // once the heap fragments (e.g. graph-allocator compute-buffer reserve - // after model load). Four-step retry: - // 1. normal alloc (fast path) - // 2. clFinish + retry (drains in-flight allocs) - // 3. cl_qcom_large_buffer (X2-class driver only, OpenCL 3.0 only) - // 4. ALLOC_HOST_PTR (host-pinned pool) — last-resort fallback. This - // buffer backs compute scratch read/written by every kernel in the - // graph, so kernel accesses fall to host memory and runtime perf - // degrades meaningfully. Better than failing to load, but the user - // should see the warning and consider -ngl reduction. - if (err != CL_SUCCESS) { - clFinish(backend_ctx->queue); - mem = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size, NULL, &err); - } -#if GGML_OPENCL_TARGET_VERSION >= 300 - // clCreateBufferWithProperties and cl_mem_properties are OpenCL 3.0. Drivers older than - // that do not export the symbol, so a build targeting them fails to link. The large - // buffer extension is only ever enabled on drivers that are well past 3.0, so this path - // is dead there anyway. - if (err != CL_SUCCESS && backend_ctx->adreno_use_large_buffer) { - cl_mem_properties props[] = { 0x41A6 /* CL_LARGE_BUFFER_QCOM */, 1, 0 }; - mem = clCreateBufferWithProperties(backend_ctx->context, props, CL_MEM_READ_WRITE, size, NULL, &err); - } -#endif - if (err != CL_SUCCESS) { - mem = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, size, NULL, &err); - if (err == CL_SUCCESS) { - GGML_LOG_WARN("%s: %.2f MiB allocated via CL_MEM_ALLOC_HOST_PTR fallback — " - "device pool exhausted; runtime perf will be degraded. " - "Consider lowering -ngl or context size.\n", - __func__, size / 1024.0 / 1024.0); - } - } - - if (err != CL_SUCCESS) { - GGML_LOG_ERROR("%s: failed to allocate %.2f MiB (err=%d). " - "Consider reducing -ngl, lowering -c / -ub, or using quantized KV cache.\n", - __func__, size / 1024.0 / 1024.0, err); - return nullptr; - } - - ggml_backend_opencl_buffer_context * ctx = new ggml_backend_opencl_buffer_context(mem); - - return ggml_backend_buffer_init(buffer_type, ggml_backend_opencl_buffer_interface, ctx, size); -} - -static size_t ggml_backend_opencl_buffer_type_get_alignment(ggml_backend_buffer_type_t buffer_type) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer_type->device->context; - return dev_ctx->backend_ctx->alignment; -} - -static size_t ggml_backend_opencl_buffer_type_get_max_size(ggml_backend_buffer_type_t buffer_type) { - static size_t max_size = -1; - if (max_size == (size_t)-1) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer_type->device->context; - max_size = dev_ctx->backend_ctx->max_alloc_size; - } - return max_size; -} - -static bool ggml_backend_opencl_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) { - return ggml_backend_is_opencl(backend); - - UNUSED(buft); -} - -static size_t ggml_backend_opencl_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) { - size_t size = ggml_nbytes(tensor); -#ifdef GGML_OPENCL_SOA_Q - // set_tensor carves quantized weights into per-component subbuffers (d/q, - // ql/qh/s/d, ...) whose origins are each rounded up to the device base - // alignment. When a component's size is not a multiple of the alignment - // (e.g. q6_K [1536,49155]: size_s = 49155*96 leaves a 96-byte gap at 128-byte - // alignment), the aligned carve extends past ggml_nbytes and the last - // subbuffer would overlap the next tensor in the pool. Reserve the worst-case - // carve slack: at most 5 components (q5_K), i.e. 4 aligned gaps. - if (ggml_is_quantized(tensor->type)) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buft->device->context; - size += 4 * dev_ctx->backend_ctx->alignment; - } -#endif // GGML_OPENCL_SOA_Q - return size; -} - -static ggml_backend_buffer_type_i ggml_backend_opencl_buffer_type_interface = { - /* .get_name = */ ggml_backend_opencl_buffer_type_get_name, - /* .alloc_buffer = */ ggml_backend_opencl_buffer_type_alloc_buffer, - /* .alloc_buffer_n = */ NULL, - /* .get_alignment = */ ggml_backend_opencl_buffer_type_get_alignment, - /* .get_max_size = */ ggml_backend_opencl_buffer_type_get_max_size, - /* .get_alloc_size = */ ggml_backend_opencl_buffer_type_get_alloc_size, - /* .get_alloc_size_n = */ NULL, - /* .is_host = */ NULL, -}; - -// -// backend device -// - -static const char * ggml_backend_opencl_device_get_name(ggml_backend_dev_t dev) { - return "GPUOpenCL"; - - GGML_UNUSED(dev); -} - -static const char * ggml_backend_opencl_device_get_description(ggml_backend_dev_t dev) { - ggml_backend_opencl_device_context *dev_ctx = (ggml_backend_opencl_device_context *) dev->context; - return dev_ctx->device_name.c_str(); -} - -static void ggml_backend_opencl_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) { - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; - - static const size_t opencl_extra_margin = 1024ull*1024ull*1024ull; - - // OpenCL does not provide reliable currently-free device memory. - // Use total/global memory as a best-effort upper bound. - // Improved safety: Reduce by a 1GiB extra margin for common --fit - *total = dev_ctx->global_mem_size; - *free = *total > opencl_extra_margin ? *total - opencl_extra_margin : 0; -} - -static enum ggml_backend_dev_type ggml_backend_opencl_device_get_type(ggml_backend_dev_t dev) { - return GGML_BACKEND_DEVICE_TYPE_GPU; - - GGML_UNUSED(dev); -} - -static void ggml_backend_opencl_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) { - props->name = ggml_backend_opencl_device_get_name(dev); - props->description = ggml_backend_opencl_device_get_description(dev); - props->type = ggml_backend_opencl_device_get_type(dev); - ggml_backend_opencl_device_get_memory(dev, &props->memory_free, &props->memory_total); - props->caps = ggml_backend_dev_caps { - /* .async = */ false, - /* .host_buffer = */ false, - /* .buffer_from_host_ptr = */ false, - /* .events = */ false, - /* .mmap_support = */ false, - /* .fast_async_host_input = */ false, - }; -} - -static ggml_backend_t ggml_backend_opencl_device_init(ggml_backend_dev_t dev, const char * params) { - ggml_backend_opencl_context * backend_ctx = ggml_cl_init(dev); - // Getting a new reference to the backend, increase ref_count - backend_ctx->ref_count++; - - ggml_backend_t backend = new ggml_backend { - /* .guid = */ ggml_backend_opencl_guid(), - /* .interface = */ ggml_backend_opencl_i, - /* .device = */ dev, - /* .context = */ backend_ctx, - }; - - ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; - ggml_opencl_print_backend_info(dev_ctx); - return backend; - - GGML_UNUSED(params); -} - -static ggml_backend_buffer_type_t ggml_backend_opencl_device_get_buffer_type(ggml_backend_dev_t dev) { - auto * dev_ctx = static_cast(dev->context); - - dev_ctx->buffer_type = ggml_backend_buffer_type{ - /* .iface = */ ggml_backend_opencl_buffer_type_interface, - /* .device = */ dev, - /* .context = */ nullptr, - }; - - return &dev_ctx->buffer_type; -} - -static ggml_backend_buffer_t ggml_backend_opencl_device_buffer_from_ptr(ggml_backend_dev_t dev, void * ptr, size_t size, size_t max_tensor_size) { - GGML_UNUSED(dev); - GGML_UNUSED(ptr); - GGML_UNUSED(size); - GGML_UNUSED(max_tensor_size); - return nullptr; -} - -static bool ggml_backend_opencl_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { - ggml_cl_init(dev); - return ggml_opencl_supports_op(dev, op); -} - -static bool ggml_backend_opencl_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) { - // Check 'dev' and 'buffer_type' are not objects belonging to this backend. - if (dev->iface.get_name != ggml_backend_opencl_device_get_name || - buft->iface.get_name != ggml_backend_opencl_buffer_type_get_name) { - return false; - } - - // Check cl_context is the same. clEnqueue* commands may not use - // buffers from another cl_context. - ggml_backend_opencl_context * backend_ctx0 = ggml_cl_init(dev); - ggml_backend_opencl_context * backend_ctx1 = ggml_cl_init(buft->device); - return backend_ctx0->context == backend_ctx1->context; -} - -namespace /* anonymous */ { -struct ggml_backend_device_i ggml_backend_opencl_device_i = { - /* .get_name = */ ggml_backend_opencl_device_get_name, - /* .get_description = */ ggml_backend_opencl_device_get_description, - /* .get_memory = */ ggml_backend_opencl_device_get_memory, - /* .get_type = */ ggml_backend_opencl_device_get_type, - /* .get_props = */ ggml_backend_opencl_device_get_props, - /* .init_backend = */ ggml_backend_opencl_device_init, - /* .get_buffer_type = */ ggml_backend_opencl_device_get_buffer_type, - /* .get_host_buffer_type = */ NULL, - /* .buffer_from_host_ptr = */ ggml_backend_opencl_device_buffer_from_ptr, - /* .supports_op = */ ggml_backend_opencl_device_supports_op, - /* .supports_buft = */ ggml_backend_opencl_device_supports_buft, - /* .offload_op = */ NULL, - /* .event_new = */ NULL, - /* .event_free = */ NULL, - /* .event_synchronize = */ NULL, -}; -} - -// Backend registry - -static const char * ggml_backend_opencl_reg_get_name(ggml_backend_reg_t reg) { - return "OpenCL"; - - GGML_UNUSED(reg); -} - -static size_t ggml_backend_opencl_reg_device_count(ggml_backend_reg_t reg) { - return g_ggml_backend_opencl_devices.size(); - - GGML_UNUSED(reg); -} - -static ggml_backend_dev_t ggml_backend_opencl_reg_device_get(ggml_backend_reg_t reg, size_t index) { - GGML_ASSERT(index < ggml_backend_opencl_reg_device_count(reg)); - - return &g_ggml_backend_opencl_devices[index]; - - GGML_UNUSED(reg); - GGML_UNUSED(index); -} - -static struct ggml_backend_reg_i ggml_backend_opencl_reg_i = { - /* .get_name = */ ggml_backend_opencl_reg_get_name, - /* .device_count = */ ggml_backend_opencl_reg_device_count, - /* .device_get = */ ggml_backend_opencl_reg_device_get, - /* .get_proc_address = */ NULL, -}; - -ggml_backend_reg_t ggml_backend_opencl_reg(void) { - static std::mutex mutex; - static ggml_backend_reg reg; - static bool initialized = false; - std::lock_guard lock(mutex); - - if (initialized) { - return ® - } - initialized = true; - - g_ggml_backend_opencl_devices = ggml_opencl_probe_devices(®); - - reg = ggml_backend_reg{ - /* .api_version = */ GGML_BACKEND_API_VERSION, - /* .iface = */ ggml_backend_opencl_reg_i, - /* .context = */ NULL, - }; - - return ® -} - -GGML_BACKEND_DL_IMPL(ggml_backend_opencl_reg) - -//------------------------------------------------------------------------------ -// Debugging utils -//------------------------------------------------------------------------------ -#if 0 -#define QK4_0 32 -typedef struct { - ggml_fp16_t d; // delta - uint8_t qs[QK4_0 / 2]; // nibbles / quants -} block_q4_0; -static_assert(sizeof(block_q4_0) == sizeof(ggml_fp16_t) + QK4_0 / 2, - "wrong q4_0 block size/padding"); - -#define QK_MXFP4 32 - -#include -#ifdef __cplusplus -#include "half.hpp" -#endif - -static void dump_tensor(ggml_backend_t backend, const struct ggml_tensor * tensor) { - void * buf = malloc(ggml_nbytes(tensor)); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - cl_command_queue queue = backend_ctx->queue; -#ifdef GGML_OPENCL_SOA_Q - void * buf_q; - void * buf_d; -#endif - - // Make sure everything is done. - CL_CHECK(clFinish(queue)); - -#ifdef GGML_OPENCL_SOA_Q - if (tensor->type == GGML_TYPE_Q4_0) { - ggml_tensor_extra_cl_q4_0 * extra = (ggml_tensor_extra_cl_q4_0 *) tensor->extra; - GGML_ASSERT(extra); - - size_t size_q = ggml_nelements(tensor)/QK4_0 * QK4_0/2; - size_t size_d = ggml_nelements(tensor)/QK4_0 * sizeof(ggml_fp16_t); - GGML_ASSERT(size_q + size_d == ggml_nbytes(tensor)); - buf_q = malloc(size_q); - buf_d = malloc(size_d); - - CL_CHECK(clEnqueueReadBuffer(queue, extra->q, CL_TRUE, 0, size_q, buf_q, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->d, CL_TRUE, 0, size_d, buf_d, 0, NULL, NULL)); - CL_CHECK(clFinish(queue)); - } else if (tensor->type == GGML_TYPE_MXFP4) { - ggml_tensor_extra_cl_mxfp4 * extra = (ggml_tensor_extra_cl_mxfp4 *) tensor->extra; - GGML_ASSERT(extra); - - size_t size_q = ggml_nelements(tensor)/QK_MXFP4 * QK_MXFP4/2; - size_t size_e = ggml_nelements(tensor)/QK_MXFP4 * sizeof(char); - GGML_ASSERT(size_q + size_e == ggml_nbytes(tensor)); - buf_q = malloc(size_q); - buf_d = malloc(size_e); - - CL_CHECK(clEnqueueReadBuffer(queue, extra->q, CL_TRUE, 0, size_q, buf_q, 0, NULL, NULL)); - CL_CHECK(clEnqueueReadBuffer(queue, extra->e, CL_TRUE, 0, size_e, buf_d, 0, NULL, NULL)); - CL_CHECK(clFinish(queue)); - } else { - // Read out the tensor from GPU memory. - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; - GGML_ASSERT(extra); - - CL_CHECK(clEnqueueReadBuffer(queue, extra->data_device, CL_TRUE, - extra->offset, ggml_nbytes(tensor), buf, 0, NULL, NULL)); - CL_CHECK(clFinish(queue)); - } -#else - // Read out the tensor from GPU memory. - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; - GGML_ASSERT(extra); - - CL_CHECK(clEnqueueReadBuffer(queue, extra->data_device, CL_TRUE, - extra->offset, ggml_nbytes(tensor), buf, 0, NULL, NULL)); - CL_CHECK(clFinish(queue)); -#endif // GGML_OPENCL_SOA_Q - - // Open file and dump. - char fname[512]; - snprintf(fname, sizeof(fname), "./tensor-dumps/%s.txt", tensor->name); - FILE * f = fopen(fname, "w"); - if (!f) { - printf("Failed to open %s\n", fname); - return; - } - - if (tensor->type == GGML_TYPE_F32) { - float * data = (float *) buf; - for (int i = 0; i < ggml_nelements(tensor); ++i) { - if (isnan(data[i])) { - printf("NaN found: %s\n", tensor->name); - break; - } - fprintf(f, "%f\n", data[i]); - } - } else if (tensor->type == GGML_TYPE_I32) { - int * data = (int *) buf; - for (int i = 0; i < ggml_nelements(tensor); ++i) { - if (isnan(data[i])) { - printf("NaN found: %s\n", tensor->name); - break; - } - fprintf(f, "%d\n", data[i]); - } - } else if (tensor->type == GGML_TYPE_F16) { -#ifdef __cplusplus - half_float::half * data = (half_float::half *) buf; - for (int i = 0; i < ggml_nelements(tensor); ++i) { - if (std::isnan(data[i])) { - printf("NaN found: %s\n", tensor->name); - break; - } - fprintf(f, "%f\n", float(data[i])); - } -#endif - } else if (tensor->type == GGML_TYPE_Q4_0) { -#ifdef GGML_OPENCL_SOA_Q - ggml_fp16_t * data_d = (ggml_fp16_t *)buf_d; - unsigned char * data_q = (unsigned char *)buf_q; - - for (int i = 0; i < ggml_nelements(tensor)/QK4_0; ++i) { - fprintf(f, "%04x, ", data_d[i]); - for (int k = 0; k < QK4_0/2; ++k) { - fprintf(f, "%02x, ", data_q[k]); - } - fprintf(f, "\n"); - data_q += QK4_0/2; - } - free(buf_d); - free(buf_q); -#else - block_q4_0 * data = (block_q4_0 *) buf; - for (int i = 0; i < ggml_nelements(tensor)/QK4_0; ++i) { - fprintf(f, "%04x, ", data[i].d); - for (int k = 0; k < QK4_0/2; ++k) { - fprintf(f, "%02x, ", data[i].qs[k]); - } - fprintf(f, "\n"); - } -#endif // GGML_OPENCL_SOA_Q - } - free(buf); - fflush(f); - fclose(f); -} -#else -#define dump_tensor(tensor) -#endif - -//------------------------------------------------------------------------------ -// Ops -//------------------------------------------------------------------------------ - -static bool ggml_cl_can_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) { - const int64_t ne10 = src1->ne[0]; - - const int64_t ne0 = dst->ne[0]; - const int64_t ne1 = dst->ne[1]; - - // TODO: find the optimal values for these - return (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) && - src1->type == GGML_TYPE_F32 && - dst->type == GGML_TYPE_F32 && - (ne0 >= 32 && ne1 >= 32 && ne10 >= 32); -} - -// Copy a noncontiguous tensor to contiguous tensor. ne[] remains the same but -// nb[] is recalculated such that tensor is contiguous. -static void ggml_cl_copy_to_contiguous(ggml_backend_t backend, const ggml_tensor * src, cl_mem dst, - cl_ulong &nb0, cl_ulong &nb1, cl_ulong &nb2, cl_ulong &nb3) { - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - const int tensor_type_size = ggml_type_size(src->type); - - const int ne00 = src->ne[0]; - const int ne01 = src->ne[1]; - const int ne02 = src->ne[2]; - const int ne03 = src->ne[3]; - - const cl_ulong nb00 = src->nb[0]; - const cl_ulong nb01 = src->nb[1]; - const cl_ulong nb02 = src->nb[2]; - const cl_ulong nb03 = src->nb[3]; - - const int ne0 = src->ne[0]; - const int ne1 = src->ne[1]; - const int ne2 = src->ne[2]; - const int ne3 = src->ne[3]; - - nb0 = tensor_type_size; - nb1 = tensor_type_size*ne00; - nb2 = tensor_type_size*ne00*ne01; - nb3 = tensor_type_size*ne00*ne01*ne02; - - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *)src->extra; - - cl_ulong offset0 = extra->offset + src->view_offs; - cl_ulong offsetd = 0; - - cl_kernel kernel; - - switch (src->type) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_cpy_f32_f32; - break; - case GGML_TYPE_F16: - case GGML_TYPE_BF16: // stored as f16 on device - kernel = backend_ctx->kernel_cpy_f16_f16; - break; - default: - GGML_ASSERT(false && "not implemented"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne3)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb3)); - - const int nth = MIN(64, ne00); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, src); -} - -static void ggml_cl_nop(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - UNUSED(backend); - UNUSED(src0); - UNUSED(src1); - UNUSED(dst); -} - -static void ggml_cl_get_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(int, ne1, src1, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); - GGML_TENSOR_LOCALS(int, ne, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - switch (src0->type) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_get_rows_f32; - break; - case GGML_TYPE_I32: - kernel = backend_ctx->kernel_get_rows_i32; - break; - case GGML_TYPE_F16: - kernel = backend_ctx->kernel_get_rows_f16; - break; - case GGML_TYPE_Q4_0: - kernel = backend_ctx->kernel_get_rows_q4_0; - break; - default: - GGML_ASSERT(false && "not implemented"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb3)); - - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - int nth = 1; - while (nth < ne00 && 2*nth <= max_workgroup_size) { - nth *= 2; - } - - int nchunks = 1; - if (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_I32) { - const int chunk_target = nth * 4; - nchunks = (ne00 + chunk_target - 1) / chunk_target; - nchunks = MAX(1, MIN(nchunks, 64)); - } - - size_t global_work_size[] = {(size_t)ne10*nth*nchunks, (size_t)ne11, (size_t)ne12}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -// check if a Q8_0 tensor has been SOA'ed in set_tensor -// we store SOA'ed tensors in a map in set_tensor, check against that map -static bool ggml_cl_is_q8_0_soa(const ggml_tensor * tensor) { - if (tensor == nullptr || tensor->type != GGML_TYPE_Q8_0 || tensor->buffer == nullptr) { - return false; - } - auto * ctx = (ggml_backend_opencl_buffer_context *) tensor->buffer->context; - if (ctx == nullptr) { - return false; - } - const ggml_tensor * key = tensor->view_src != nullptr ? tensor->view_src : tensor; - return ctx->q8_0_soa_tensors.count(key) > 0; -} - -// check if a Q4_0 tensor has been SOA'ed in set_tensor -// we store SOA'ed tensors in a map in set_tensor, check against that map -static bool ggml_cl_is_q4_0_soa(const ggml_tensor * tensor) { - if (tensor == nullptr || tensor->type != GGML_TYPE_Q4_0 || tensor->buffer == nullptr) { - return false; - } - auto * ctx = (ggml_backend_opencl_buffer_context *) tensor->buffer->context; - if (ctx == nullptr) { - return false; - } - const ggml_tensor * key = tensor->view_src != nullptr ? tensor->view_src : tensor; - return ctx->q4_0_soa_tensors.count(key) > 0; -} - -static void ggml_cl_set_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(src1->type == GGML_TYPE_I64 || src1->type == GGML_TYPE_I32); - - // ne0 = ne00 - // ne2 = ne02 - // ne3 = ne03 - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - - GGML_TENSOR_LOCALS(int, ne1, src1, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); - - GGML_TENSOR_LOCALS(int, ne, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - const int nblk0 = ne0/ggml_blck_size(dst->type); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - - const bool q8_0_soa = dst->type == GGML_TYPE_Q8_0 && ggml_cl_is_q8_0_soa(dst); - const bool q4_0_soa = dst->type == GGML_TYPE_Q4_0 && ggml_cl_is_q4_0_soa(dst); - const bool is_soa = q8_0_soa || q4_0_soa; - - cl_kernel kernel; - - if (q8_0_soa) { - kernel = (src1->type == GGML_TYPE_I64) - ? backend_ctx->kernel_set_rows_q8_0_soa_i64 - : backend_ctx->kernel_set_rows_q8_0_soa_i32; - } else if (q4_0_soa) { - kernel = (src1->type == GGML_TYPE_I64) - ? backend_ctx->kernel_set_rows_q4_0_soa_i64 - : backend_ctx->kernel_set_rows_q4_0_soa_i32; - } else { - switch (dst->type) { - case GGML_TYPE_F32: - kernel = (src1->type == GGML_TYPE_I64) - ? backend_ctx->kernel_set_rows_f32_i64 - : backend_ctx->kernel_set_rows_f32_i32; - break; - case GGML_TYPE_F16: - kernel = (src1->type == GGML_TYPE_I64) - ? backend_ctx->kernel_set_rows_f16_i64 - : backend_ctx->kernel_set_rows_f16_i32; - break; - case GGML_TYPE_Q8_0: - kernel = (src1->type == GGML_TYPE_I64) - ? backend_ctx->kernel_set_rows_q8_0_i64 - : backend_ctx->kernel_set_rows_q8_0_i32; - break; - case GGML_TYPE_Q4_0: - kernel = (src1->type == GGML_TYPE_I64) - ? backend_ctx->kernel_set_rows_q4_0_i64 - : backend_ctx->kernel_set_rows_q4_0_i32; - break; - default: - GGML_ABORT("not implemented"); - } - } - - fastdiv_vals ne11_ = init_fastdiv_values(ne11); - fastdiv_vals ne12_ = init_fastdiv_values(ne12); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - - if (is_soa) { - // The q/d subbuffers in q8_0/q4_0 extras are interchangeable here. - // For views (e.g. ggml_set_rows' `out`), follow view_src for the SoA extra. - const ggml_tensor * soa_src = dst->view_src != nullptr ? dst->view_src : dst; - cl_mem q_mem = nullptr; - cl_mem d_mem = nullptr; - if (q8_0_soa) { - ggml_tensor_extra_cl_q8_0 * e = (ggml_tensor_extra_cl_q8_0 *)soa_src->extra; - q_mem = e->q; - d_mem = e->d; - } else { - ggml_tensor_extra_cl_q4_0 * e = (ggml_tensor_extra_cl_q4_0 *)soa_src->extra; - q_mem = e->q; - d_mem = e->d; - } - cl_ulong offset_q = 0; - cl_ulong offset_d = 0; - const int ne1_dst = dst->ne[1]; - const int ne2_dst = dst->ne[2]; - const int ne3_dst = dst->ne[3]; - - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &q_mem)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset_q)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &d_mem)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset_d)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(fastdiv_vals), &ne11_)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(fastdiv_vals), &ne12_)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &nblk0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1_dst)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne2_dst)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne3_dst)); - } else { - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(fastdiv_vals), &ne11_)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(fastdiv_vals), &ne12_)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &nblk0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb3)); - } - - int nth0 = 64; - if (backend_ctx->gpu_family == INTEL) { - nth0 = 32; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - } - - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - while (nth0 < nblk0 && nth0 < max_workgroup_size) { - nth0 *= 2; - } - - int rows_per_workgroup = 1; - if (nth0 > nblk0) { - rows_per_workgroup = nth0 / nblk0; - nth0 = nblk0; - } - - size_t global_work_size[] = { - (size_t)(ne01 + rows_per_workgroup - 1)/rows_per_workgroup*nth0, - (size_t)ne02*rows_per_workgroup, - (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth0, (size_t)rows_per_workgroup, 1}; - - // ne01 == 0 makes global_work_size[0] zero here; enqueue_ndrange_kernel drops the empty range. - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_add(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne10 = src1->ne[0]; - const int ne11 = src1->ne[1]; - const int ne12 = src1->ne[2]; - const int ne13 = src1->ne[3]; - - const cl_ulong nb10 = src1->nb[0]; - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - const int ne2 = dst->ne[2]; - const int ne3 = dst->ne[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - const bool bcast_row = ggml_is_contiguous(src0) && ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0; - - if (bcast_row) { - GGML_ASSERT(ggml_is_contiguous(src0)); - GGML_ASSERT(ne11 == 1); - } - - if (dst->type == GGML_TYPE_F32) { - GGML_ASSERT(src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32); - if (bcast_row) { - kernel = backend_ctx->kernel_add_row; - const int ne = ne10 / 4; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); - } else { - kernel = backend_ctx->kernel_add; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne3)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb3)); - } - } else if (dst->type == GGML_TYPE_F16) { - GGML_ASSERT(src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_F32); - GGML_ASSERT(src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_F32); - const int type_src0 = (src0->type == GGML_TYPE_F32); - const int type_src1 = (src1->type == GGML_TYPE_F32); - if (bcast_row) { - kernel = backend_ctx->kernel_add_row_f16; - const int ne = ne10 / 4; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &type_src0)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &type_src1)); - } else { - kernel = backend_ctx->kernel_add_f16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne3)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 30, sizeof(int), &type_src0)); - CL_CHECK(clSetKernelArg(kernel, 31, sizeof(int), &type_src1)); - } - } else { - GGML_ASSERT(false && "unsupported data types for add"); - } - - if (bcast_row) { - int n = ggml_nelements(dst)/4; - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size_ptr, dst); - } else { - unsigned int nth = MIN(64, ne0); - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_add_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - const ggml_tensor * src2 = dst->src[2]; - GGML_ASSERT(src2); - GGML_ASSERT(src2->extra); - - GGML_ASSERT(src0->type == GGML_TYPE_F32); - GGML_ASSERT(src1->type == GGML_TYPE_F32); - GGML_ASSERT(src2->type == GGML_TYPE_I32); - GGML_ASSERT(dst->type == GGML_TYPE_F32); - - GGML_ASSERT(ggml_is_contiguous_rows(src0)); - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - - const cl_ulong nb11 = src1->nb[1]; - - const cl_ulong nb21 = src2->nb[1]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offset2 = extra2->offset + src2->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel = backend_ctx->kernel_add_id; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); - - int nth = MIN(ne00, (int) backend_ctx->get_kernel_workgroup_size(kernel)); - size_t global_work_size[] = { (size_t)ne01*nth, (size_t)ne02, 1 }; - size_t local_work_size[] = { (size_t)nth, 1, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_mul(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - GGML_ASSERT(src0->type == src1->type); - GGML_ASSERT(src0->type == dst->type); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne10 = src1->ne[0]; - const int ne11 = src1->ne[1]; - const int ne12 = src1->ne[2]; - const int ne13 = src1->ne[3]; UNUSED(ne13); - - const cl_ulong nb10 = src1->nb[0]; - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; UNUSED(nb13); - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - const int ne2 = dst->ne[2]; - const int ne3 = dst->ne[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - bool bcast_row = false; - cl_kernel kernel; - - if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) { - GGML_ASSERT(ggml_is_contiguous(src0)); - - // src1 is a row - GGML_ASSERT(ne11 == 1); - - bcast_row = true; - int ne = ne10 / 4; - - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_mul_row; - } else { - kernel = backend_ctx->kernel_mul_row_f16; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_mul; - } else { - kernel = backend_ctx->kernel_mul_f16; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne3)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb3)); - } - - if (bcast_row) { - int n = ggml_nelements(dst)/4; - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } else { - unsigned int nth = MIN(64, ne0); - size_t global_work_size[] = {ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_div(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - GGML_ASSERT(src0->type == src1->type); - GGML_ASSERT(src0->type == dst->type); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne10 = src1->ne[0]; - const int ne11 = src1->ne[1]; - const int ne12 = src1->ne[2]; - const int ne13 = src1->ne[3]; - - const cl_ulong nb10 = src1->nb[0]; - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const int ne0 = dst->ne[0]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - bool bcast_row = false; - cl_kernel kernel; - - if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) { - GGML_ASSERT(ggml_is_contiguous(src0)); - - // src1 is a row - GGML_ASSERT(ne11 == 1); - - bcast_row = true; - int ne = ne00 / 4; - - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_div_row; - } else { - kernel = backend_ctx->kernel_div_row_f16; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_div; - } else { - kernel = backend_ctx->kernel_div_f16; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); - } - - if (bcast_row) { - int n = ggml_nelements(dst)/4; - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - unsigned int nth = MIN(64, ne0); - size_t global_work_size[] = {ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_sub(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - GGML_ASSERT(src0->type == src1->type); - GGML_ASSERT(src0->type == dst->type); - GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne10 = src1->ne[0]; - const int ne11 = src1->ne[1]; - const int ne12 = src1->ne[2]; - const int ne13 = src1->ne[3]; - - const cl_ulong nb10 = src1->nb[0]; - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const int ne0 = dst->ne[0]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - bool bcast_row = false; - cl_kernel kernel; - - if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) { - GGML_ASSERT(ggml_is_contiguous(src0)); - - // src1 is a row - GGML_ASSERT(ne11 == 1); - - bcast_row = true; - int ne = ne00 / 4; - - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_sub_row; - } else { - kernel = backend_ctx->kernel_sub_row_f16; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_sub; - } else { - kernel = backend_ctx->kernel_sub_f16; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); - } - - if (bcast_row) { - int n = ggml_nelements(dst)/4; - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - unsigned int nth = MIN(64, ne0); - size_t global_work_size[] = {ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_sqr(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - // Currently assumes src0 is contiguous - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_sqr_cont_f32_4; - } else { - kernel = backend_ctx->kernel_sqr_cont_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_sqr_cont_f32; - } else { - kernel = backend_ctx->kernel_sqr_cont_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_sqrt(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - // Currently assumes src0 is contiguous - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_sqrt_cont_f32_4; - } else { - kernel = backend_ctx->kernel_sqrt_cont_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_sqrt_cont_f32; - } else { - kernel = backend_ctx->kernel_sqrt_cont_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_mean(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_UNUSED(src1); - - GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type)); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - cl_kernel kernel; - - const bool is_c4 = ne00 % 4 == 0; - if (is_c4) { - kernel = backend_ctx->kernel_mean_f32_4; - } else { - kernel = backend_ctx->kernel_mean_f32; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb3)); - - size_t global_work_size[] = {64 * (size_t)ne01, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_ssm_scan(ggml_backend_t backend, ggml_tensor * dst) { - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(dst->src[0]); - GGML_ASSERT(dst->src[0]->extra); - GGML_ASSERT(dst->src[1]); - GGML_ASSERT(dst->src[1]->extra); - GGML_ASSERT(dst->src[2]); - GGML_ASSERT(dst->src[2]->extra); - GGML_ASSERT(dst->src[3]); - GGML_ASSERT(dst->src[3]->extra); - GGML_ASSERT(dst->src[4]); - GGML_ASSERT(dst->src[4]->extra); - GGML_ASSERT(dst->src[5]); - GGML_ASSERT(dst->src[5]->extra); - GGML_ASSERT(dst->src[6]); - GGML_ASSERT(dst->src[6]->extra); - - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) dst->src[0]->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) dst->src[1]->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *) dst->src[2]->extra; - ggml_tensor_extra_cl * extra3 = (ggml_tensor_extra_cl *) dst->src[3]->extra; - ggml_tensor_extra_cl * extra4 = (ggml_tensor_extra_cl *) dst->src[4]->extra; - ggml_tensor_extra_cl * extra5 = (ggml_tensor_extra_cl *) dst->src[5]->extra; - ggml_tensor_extra_cl * extra6 = (ggml_tensor_extra_cl *) dst->src[6]->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset0 = extra0->offset + dst->src[0]->view_offs; - const cl_ulong offset1 = extra1->offset + dst->src[1]->view_offs; - const cl_ulong offset2 = extra2->offset + dst->src[2]->view_offs; - const cl_ulong offset3 = extra3->offset + dst->src[3]->view_offs; - const cl_ulong offset4 = extra4->offset + dst->src[4]->view_offs; - const cl_ulong offset5 = extra5->offset + dst->src[5]->view_offs; - const cl_ulong offset6 = extra6->offset + dst->src[6]->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - - const ggml_tensor * s = dst->src[0]; - const ggml_tensor * x = dst->src[1]; - const ggml_tensor * dt = dst->src[2]; - const ggml_tensor * A = dst->src[3]; - const ggml_tensor * B = dst->src[4]; - const ggml_tensor * C = dst->src[5]; - - const cl_ulong s_nb1 = s->nb[1]; - const cl_ulong s_nb2 = s->nb[2]; - const cl_ulong s_nb3 = s->nb[3]; - const cl_ulong x_nb1 = x->nb[1]; - const cl_ulong x_nb2 = x->nb[2]; - const cl_ulong x_nb3 = x->nb[3]; - const cl_ulong dt_nb1 = dt->nb[1]; - const cl_ulong dt_nb2 = dt->nb[2]; - const cl_ulong A_nb1 = A->nb[1]; - const cl_ulong B_nb1 = B->nb[1]; - const cl_ulong B_nb2 = B->nb[2]; - const cl_ulong B_nb3 = B->nb[3]; - const cl_ulong C_nb1 = C->nb[1]; - const cl_ulong C_nb2 = C->nb[2]; - const cl_ulong C_nb3 = C->nb[3]; - - const cl_uint A_ne0 = A->ne[0]; - const cl_uint d_state = s->ne[0]; - const cl_int head_dim = x->ne[0]; - const cl_int n_head = x->ne[1]; - const cl_int n_group = B->ne[1]; - const cl_int n_tokens = x->ne[2]; - const cl_uint n_seqs = x->ne[3]; - const cl_uint K = ggml_get_op_params_i32(dst, 0); - const cl_ulong s_off_bytes = (cl_ulong) ggml_nelements(x) * sizeof(float); - - cl_kernel kernel = backend_ctx->kernel_ssm_scan_f32; - size_t nth = d_state; - if (A_ne0 == 1 && K == 1) { - cl_kernel kernel_mamba2 = nullptr; - if (d_state == 128) { - kernel_mamba2 = backend_ctx->kernel_ssm_scan_f32_mamba2_d128; - } else if (d_state == 256) { - kernel_mamba2 = backend_ctx->kernel_ssm_scan_f32_mamba2_d256; - } - if (kernel_mamba2 != nullptr) { - kernel = kernel_mamba2; - nth = 64; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra3->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset3)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extra4->data_device)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offset4)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_mem), &extra5->data_device)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &offset5)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_mem), &extra6->data_device)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &offset6)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &s_nb2)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &s_nb3)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &x_nb2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &x_nb3)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &dt_nb1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &dt_nb2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &A_nb1)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &B_nb2)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &B_nb3)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(cl_ulong), &C_nb2)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &C_nb3)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &s_off_bytes)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_int), &head_dim)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_int), &n_head)); - CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_int), &n_group)); - CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_int), &n_tokens)); - - if (kernel == backend_ctx->kernel_ssm_scan_f32) { - CL_CHECK(clSetKernelArg(kernel, 32, sizeof(cl_ulong), &s_nb1)); - CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_ulong), &x_nb1)); - CL_CHECK(clSetKernelArg(kernel, 34, sizeof(cl_ulong), &B_nb1)); - CL_CHECK(clSetKernelArg(kernel, 35, sizeof(cl_ulong), &C_nb1)); - CL_CHECK(clSetKernelArg(kernel, 36, sizeof(cl_uint), &A_ne0)); - CL_CHECK(clSetKernelArg(kernel, 37, sizeof(cl_uint), &d_state)); - CL_CHECK(clSetKernelArg(kernel, 38, sizeof(cl_uint), &n_seqs)); - CL_CHECK(clSetKernelArg(kernel, 39, sizeof(cl_uint), &K)); - CL_CHECK(clSetKernelArg(kernel, 40, d_state * sizeof(float), nullptr)); - } - - size_t global_work_size[] = { - (size_t) head_dim * (size_t) n_head * nth, - (size_t) n_seqs, - }; - size_t local_work_size[] = { nth, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); -} - -static void ggml_cl_ssm_conv(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - int ne01 = src0->ne[1]; - cl_ulong nb00 = src0->nb[0]; - cl_ulong nb01 = src0->nb[1]; - cl_ulong nb02 = src0->nb[2]; - - int ne10 = src1->ne[0]; - cl_ulong nb11 = src1->nb[1]; - - int ne1 = dst->ne[1]; - int ne2 = dst->ne[2]; - cl_ulong nb0 = dst->nb[0]; - cl_ulong nb1 = dst->nb[1]; - cl_ulong nb2 = dst->nb[2]; - - cl_kernel kernel = backend_ctx->kernel_ssm_conv_f32_f32; - - if (ne10 % 4 == 0) { - kernel = backend_ctx->kernel_ssm_conv_f32_f32_4; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); - - size_t global_work_size[] = {(size_t)ne01, (size_t)ne1, (size_t)ne2}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (ne01 % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_gelu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - int n = ggml_nelements(dst); - - if (n % 4 == 0) { - kernel = backend_ctx->kernel_gelu_4; - n /= 4; - } else { - kernel = backend_ctx->kernel_gelu; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_gelu_erf(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - int n = ggml_nelements(dst); - - if (n % 4 == 0) { - kernel = backend_ctx->kernel_gelu_erf_4; - n /= 4; - } else { - kernel = backend_ctx->kernel_gelu_erf; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_gelu_quick(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel; - - int n = ggml_nelements(dst); - - if (n % 4 == 0) { - kernel = backend_ctx->kernel_gelu_quick_4; - n /= 4; - } else { - kernel = backend_ctx->kernel_gelu_quick; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_silu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) { - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - cl_kernel kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->kernel_silu_nc : backend_ctx->kernel_silu_f16_nc; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - size_t global_work_size[] = {(size_t)ne01 * 64, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - - cl_kernel kernel; - - int n = ggml_nelements(dst); - - if (n % 4 == 0) { - kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->kernel_silu_4 : backend_ctx->kernel_silu_f16_4; - n /= 4; - } else { - kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->kernel_silu : backend_ctx->kernel_silu_f16; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_relu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel = backend_ctx->kernel_relu; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - const int64_t n = ggml_nelements(dst); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_sigmoid(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) { - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - cl_kernel kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->kernel_sigmoid_f32_nc : backend_ctx->kernel_sigmoid_f16_nc; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - if (src0->type != GGML_TYPE_F32) { - const int is_bf16 = dst->type == GGML_TYPE_BF16; - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &is_bf16)); - } - - size_t global_work_size[] = {(size_t)ne01 * 64, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - - cl_kernel kernel; - if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_sigmoid_f32; - } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { - kernel = backend_ctx->kernel_sigmoid_f16; - } else if (src0->type == GGML_TYPE_BF16 && dst->type == GGML_TYPE_BF16) { - // bf16 converted to f16 - kernel = backend_ctx->kernel_sigmoid_f16; - } else { - GGML_ASSERT(false && "Unsupported data types for sigmoid (input and output must be both f32 or f16)"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - if (src0->type != GGML_TYPE_F32) { - const int is_bf16 = dst->type == GGML_TYPE_BF16; - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &is_bf16)); - } - - const int64_t n = ggml_nelements(dst); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_tri(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int tri_type = ggml_get_op_params_i32(dst, 0); - const int64_t n = ggml_nelements(dst); - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - - cl_kernel kernel = backend_ctx->kernel_tri; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &tri_type)); - - size_t local_work_size[1] = { 256 }; - size_t global_work_size[1] = { ((size_t)n + local_work_size[0] - 1) / local_work_size[0] * local_work_size[0] }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); -} - -static void ggml_cl_fill(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src0); - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - float v = 0.0f; - memcpy(&v, ((int32_t *) dst->op_params), sizeof(float)); - - const int64_t n = ggml_nelements(dst); - - cl_kernel kernel = backend_ctx->kernel_fill; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(float), &v)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(float), &n)); - - size_t local_work_size[1] = { 256 }; - size_t global_work_size[1] = { ((size_t)n + local_work_size[0] - 1) / local_work_size[0] * local_work_size[0] }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); -} - -static void ggml_cl_arange(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(dst->type == GGML_TYPE_F32); - - UNUSED(src0); - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - float start; - float step; - memcpy(&start, (float *) dst->op_params + 0, sizeof(float)); - memcpy(&step, (float *) dst->op_params + 2, sizeof(float)); - - const int n = dst->ne[0]; - - cl_kernel kernel = backend_ctx->kernel_arange; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(float), &start)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &step)); - - size_t local_work_size[1] = { 64 }; - size_t global_work_size[1] = { ((size_t)n + local_work_size[0] - 1) / local_work_size[0] * local_work_size[0] }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); -} - -static void ggml_cl_clamp(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - float min; - float max; - memcpy(&min, ((int32_t *) dst->op_params) + 0, sizeof(float)); - memcpy(&max, ((int32_t *) dst->op_params) + 1, sizeof(float)); - - if (!ggml_is_contiguous(src0)) { - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - cl_kernel kernel = backend_ctx->kernel_clamp_nc; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &min)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &max)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb3)); - - const int nth = 64; - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - - cl_kernel kernel = backend_ctx->kernel_clamp; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &min)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &max)); - - const int64_t n = ggml_nelements(dst); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - float eps; - memcpy(&eps, dst->op_params, sizeof(float)); - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - - int nth = 1; - while (nth < ne00 && nth < 64) { - nth *= 2; - } - - cl_kernel kernel = backend_ctx->kernel_norm; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float), &eps)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float)*nth, NULL)); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_rms_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - //ggml_backend_opencl_device_context * dev_ctx = - // (ggml_backend_opencl_device_context *)backend->device->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - float eps; - memcpy(&eps, dst->op_params, sizeof(float)); - - const int ne00 = src0 ? src0->ne[0] : 0; - const int ne01 = src0 ? src0->ne[1] : 0; - const int ne02 = src0 ? src0->ne[2] : 0; - const int ne03 = src0 ? src0->ne[3] : 0; - - const cl_ulong nb01 = src0 ? src0->nb[1] : 0; - const cl_ulong nb02 = src0 ? src0->nb[2] : 0; - const cl_ulong nb03 = src0 ? src0->nb[3] : 0; - - GGML_ASSERT(ne00 % 4 == 0); - - const int nth = 64; - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - cl_kernel kernel = backend_ctx->kernel_rms_norm; - - // Note, this kernel declares local memory in kernel args and the size - // depends on subgroup size. - // Note, this requires OpenCL 2.1 and above - // For now we use fixed subgroup size to simplify support for OpenCL 2.0. - size_t sgs; - //CL_CHECK(clGetKernelSubGroupInfo(kernel, dev_ctx->device, - // CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE, - // sizeof(local_work_size), local_work_size, - // sizeof(size_t), &sgs, NULL)); - if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - } else if (backend_ctx->gpu_family == INTEL) { - sgs = 32; - } else { - GGML_ASSERT(false && "Unsupported GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(float), &eps)); - // This is local memory - the size depends on subgroup size. - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float)*nth/sgs, NULL)); - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_opencl_op_rms_norm_fused(ggml_backend_t backend, ggml_tensor * rms_norm_tensor, ggml_tensor * mul_tensor) { - GGML_ASSERT(mul_tensor); - GGML_ASSERT(rms_norm_tensor); - - // src0 is the src of rms_norm, src1 is the other src of mul (one being rms_norm) - const ggml_tensor * src0 = rms_norm_tensor->src[0]; - const ggml_tensor * src1; - if (mul_tensor->src[0] == rms_norm_tensor) { - src1 = mul_tensor->src[1]; - } else if (mul_tensor->src[1] == rms_norm_tensor) { - src1 = mul_tensor->src[0]; - } else { - GGML_ASSERT(false && "Invalid args for rms_norm and mul"); - } - const ggml_tensor * dst = mul_tensor; - - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - float eps; - memcpy(&eps, rms_norm_tensor->op_params, sizeof(float)); - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne10 = src1->ne[0]; - const int ne11 = src1->ne[1]; - const int ne12 = src1->ne[2]; - const int ne13 = src1->ne[3]; - - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - GGML_ASSERT(ne00 % 4 == 0); - - size_t sgs; - if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - } else if (backend_ctx->gpu_family == INTEL) { - sgs = 32; - } else { - GGML_ASSERT(false && "Unsupported GPU"); - } - - cl_kernel kernel = backend_ctx->kernel_rms_norm_mul; - - int nth = sgs; - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - while (nth < ne00 && nth < max_workgroup_size) { - nth *= 2; - } - nth = MIN(nth, max_workgroup_size); - nth = MIN(nth, ne00); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(float), &eps)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float)*sgs, NULL)); - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_opencl_op_norm_fused(ggml_backend_t backend, ggml_tensor * norm_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor) { - GGML_ASSERT(norm_tensor && mul_tensor && add_tensor); - - const ggml_tensor * src0 = norm_tensor->src[0]; - const ggml_tensor * src1 = mul_tensor->src[0] == norm_tensor ? mul_tensor->src[1] : mul_tensor->src[0]; - const ggml_tensor * src2 = add_tensor->src[0] == mul_tensor ? add_tensor->src[1] : add_tensor->src[0]; - const ggml_tensor * dst = add_tensor; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offset2 = extra2->offset + src2->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - float eps; - memcpy(&eps, norm_tensor->op_params, sizeof(float)); - - const int ne00 = src0->ne[0], ne01 = src0->ne[1], ne02 = src0->ne[2], ne03 = src0->ne[3]; - const cl_ulong nb01 = src0->nb[1], nb02 = src0->nb[2], nb03 = src0->nb[3]; - const int ne10 = src1->ne[0], ne11 = src1->ne[1], ne12 = src1->ne[2], ne13 = src1->ne[3]; - const cl_ulong nb11 = src1->nb[1], nb12 = src1->nb[2], nb13 = src1->nb[3]; - const int ne20 = src2->ne[0], ne21 = src2->ne[1], ne22 = src2->ne[2], ne23 = src2->ne[3]; - const cl_ulong nb21 = src2->nb[1], nb22 = src2->nb[2], nb23 = src2->nb[3]; - const cl_ulong nbd1 = dst->nb[1], nbd2 = dst->nb[2], nbd3 = dst->nb[3]; - - size_t sgs; - if (backend_ctx->gpu_family == ADRENO) sgs = 64; - else if (backend_ctx->gpu_family == INTEL) sgs = 32; - else GGML_ASSERT(false && "Unsupported GPU"); - - cl_kernel kernel = backend_ctx->kernel_norm_mul_add; - - int nth = sgs; - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - while (nth < ne00/4 && nth < max_workgroup_size) nth *= 2; - nth = MIN(nth, max_workgroup_size); - nth = MIN(nth, ne00/4); - - size_t gws[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t lws[] = {(size_t)nth, 1, 1}; - size_t num_subgroups = (nth + sgs - 1) / sgs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne22)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne23)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb22)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb23)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nbd1)); - CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_ulong), &nbd2)); - CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_ulong), &nbd3)); - CL_CHECK(clSetKernelArg(kernel, 32, sizeof(float), &eps)); - CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_float2) * num_subgroups, NULL)); - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); -} - -static void ggml_opencl_op_group_norm_fused(ggml_backend_t backend, ggml_tensor * gn_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor) { - GGML_ASSERT(gn_tensor && mul_tensor && add_tensor); - - const ggml_tensor * src0 = gn_tensor->src[0]; - const ggml_tensor * src1 = mul_tensor->src[0] == gn_tensor ? mul_tensor->src[1] : mul_tensor->src[0]; - const ggml_tensor * src2 = add_tensor->src[0] == mul_tensor ? add_tensor->src[1] : add_tensor->src[0]; - const ggml_tensor * dst = add_tensor; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offset2 = extra2->offset + src2->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - int groups; - float eps; - memcpy(&groups, gn_tensor->op_params, sizeof(int)); - memcpy(&eps, (char *)gn_tensor->op_params + sizeof(int), sizeof(float)); - - cl_kernel kernel = backend_ctx->kernel_group_norm_mul_add; - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - int ne = ggml_nelements(src0); - int group_size = ne / groups; - - size_t lws[] = { (size_t)MIN(max_workgroup_size, group_size) }; - size_t gws[] = { (size_t)groups * lws[0] }; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &group_size)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(float), &eps)); - - backend_ctx->enqueue_ndrange_kernel(kernel, 1, gws, lws, dst); -} - -static void ggml_cl_group_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - int32_t n_groups = ((const int32_t *) dst->op_params)[0]; - int32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + n_groups - 1) / n_groups); - float eps = ((const float *) dst->op_params)[1]; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne = ne00*ne01*ne02; - - cl_kernel kernel = backend_ctx->kernel_group_norm; - - size_t sgs = 64; - if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - } else if (backend_ctx->gpu_family == INTEL) { - sgs = 32; - } else { - GGML_ASSERT(false && "Unsupported GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &group_size)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(float), &eps)); - - size_t global_work_size[] = {(size_t)n_groups*sgs, (size_t)src0->ne[3], 1}; - size_t local_work_size[] = {(size_t)sgs, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_l2_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - float eps; - memcpy(&eps, dst->op_params, sizeof(float)); - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - - size_t sgs; - if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - } else if (backend_ctx->gpu_family == INTEL) { - sgs = 32; - } else { - GGML_ASSERT(false && "Unsupported GPU"); - } - - cl_kernel kernel = backend_ctx->kernel_l2_norm_f32; - - int nth = sgs; - while (nth < ne00 && nth < (int)backend_ctx->get_kernel_workgroup_size(kernel)) { - nth *= 2; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(float), &eps)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float)*nth/sgs, NULL)); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_tanh(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - cl_kernel kernel; - - if (ggml_is_contiguous(src0)) { - // Handle contiguous input - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_tanh_f32_4; - } else { - kernel = backend_ctx->kernel_tanh_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_tanh_f32; - } else { - kernel = backend_ctx->kernel_tanh_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } else { - // Handle non-contiguous input - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_tanh_f32_nc; - } else { - kernel = backend_ctx->kernel_tanh_f16_nc; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_neg(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(int, ne, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - cl_kernel kernel; - - if (ggml_is_contiguous(src0)) { - // Handle contiguous input - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_neg_f32_4; - } else { - kernel = backend_ctx->kernel_neg_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_neg_f32; - } else { - kernel = backend_ctx->kernel_neg_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &n)); - - size_t global_work_size[] = {(size_t)CEIL_DIV(n, 64)*64, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - // Handle non-contiguous input - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_neg_f32_nc; - } else { - kernel = backend_ctx->kernel_neg_f16_nc; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_exp(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(int, ne, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - cl_kernel kernel; - - if (ggml_is_contiguous(src0)) { - // Handle contiguous input - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_exp_f32_4; - } else { - kernel = backend_ctx->kernel_exp_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_exp_f32; - } else { - kernel = backend_ctx->kernel_exp_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &n)); - - size_t global_work_size[] = {(size_t)CEIL_DIV(n, 64)*64, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - // Handle non-contiguous input - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_exp_f32_nc; - } else { - kernel = backend_ctx->kernel_exp_f16_nc; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_expm1(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - cl_kernel kernel; - - if (ggml_is_contiguous(src0)) { - // Handle contiguous input - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_expm1_f32_4; - } else { - kernel = backend_ctx->kernel_expm1_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_expm1_f32; - } else { - kernel = backend_ctx->kernel_expm1_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } else { - // Handle non-contiguous input - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_expm1_f32_nc; - } else { - kernel = backend_ctx->kernel_expm1_f16_nc; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_abs(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - cl_kernel kernel; - - if (ggml_is_contiguous(src0)) { - // Handle contiguous input - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_abs_f32_4; - } else { - kernel = backend_ctx->kernel_abs_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_abs_f32; - } else { - kernel = backend_ctx->kernel_abs_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } else { - // Handle non-contiguous input - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_abs_f32_nc; - } else { - kernel = backend_ctx->kernel_abs_f16_nc; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -// Shared driver for the extended unary ops (unary_ext.cl), same selection as -// ggml_cl_abs: contiguous picks the vec4 kernel when the element count is a -// multiple of 4 (else scalar); non-contiguous uses the stride-addressed kernel. -static void ggml_cl_unary_ext(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst, - cl_kernel k_f32, cl_kernel k_f32_4, cl_kernel k_f32_nc, - cl_kernel k_f16, cl_kernel k_f16_4, cl_kernel k_f16_nc) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0], ne01 = src0->ne[1], ne02 = src0->ne[2], ne03 = src0->ne[3]; - const cl_ulong nb00 = src0->nb[0], nb01 = src0->nb[1], nb02 = src0->nb[2], nb03 = src0->nb[3]; - const cl_ulong nb0 = dst->nb[0], nb1 = dst->nb[1], nb2 = dst->nb[2], nb3 = dst->nb[3]; - - const bool is_f16 = (src0->type == GGML_TYPE_F16); - cl_kernel kernel; - - if (ggml_is_contiguous(src0)) { - int n = ggml_nelements(dst); - if (n % 4 == 0) { - kernel = is_f16 ? k_f16_4 : k_f32_4; - n /= 4; - } else { - kernel = is_f16 ? k_f16 : k_f32; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } else { - kernel = is_f16 ? k_f16_nc : k_f32_nc; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - int nth = 64; - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -#define GGML_CL_UNARY_EXT_WRAP(FN, OP) \ -static void FN(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { \ - UNUSED(src1); \ - ggml_backend_opencl_context *c = (ggml_backend_opencl_context *)backend->context; \ - ggml_cl_unary_ext(backend, src0, dst, c->kernel_##OP##_f32, c->kernel_##OP##_f32_4, c->kernel_##OP##_f32_nc, \ - c->kernel_##OP##_f16, c->kernel_##OP##_f16_4, c->kernel_##OP##_f16_nc); \ -} - -GGML_CL_UNARY_EXT_WRAP(ggml_cl_sgn, sgn) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_step, step) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_elu, elu) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_hardswish, hardswish) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_hardsigmoid, hardsigmoid) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_floor, floor) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_ceil, ceil) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_round, round) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc) -GGML_CL_UNARY_EXT_WRAP(ggml_cl_log, log) - -#undef GGML_CL_UNARY_EXT_WRAP - -static void ggml_cl_xielu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - UNUSED(src1); - - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - cl_kernel kernel = src0->type == GGML_TYPE_F16 ? backend_ctx->kernel_xielu_f16 : backend_ctx->kernel_xielu_f32; - - const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; - const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset0 = extra0->offset + src0->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - const float alpha_n = ggml_get_op_params_f32(dst, 1); - const float alpha_p = ggml_get_op_params_f32(dst, 2); - const float beta = ggml_get_op_params_f32(dst, 3); - const float eps = ggml_get_op_params_f32(dst, 4); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha_n)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &alpha_p)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &beta)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &eps)); - - const size_t nth = 64; - size_t global[] = {(size_t) ne01*nth, (size_t) ne02, (size_t) ne03}; - size_t local[] = {nth, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); -} - -static void ggml_cl_softplus(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - cl_kernel kernel; - - if (ggml_is_contiguous(src0)) { - // Handle contiguous input - int n = ggml_nelements(dst); - if (n % 4 == 0) { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_softplus_f32_4; - } else { - kernel = backend_ctx->kernel_softplus_f16_4; - } - n /= 4; - } else { - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_softplus_f32; - } else { - kernel = backend_ctx->kernel_softplus_f16; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = {(size_t)n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } else { - // Handle non-contiguous input - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_softplus_f32_nc; - } else { - kernel = backend_ctx->kernel_softplus_f16_nc; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_repeat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1_shape_def, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(dst->type == src0->type); - - UNUSED(src1_shape_def); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - const int ne2 = dst->ne[2]; - const int ne3 = dst->ne[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - cl_kernel kernel; - switch (src0->type) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_repeat_f32; - break; - case GGML_TYPE_F16: - case GGML_TYPE_I16: - case GGML_TYPE_BF16: - kernel = backend_ctx->kernel_repeat_f16; - break; - case GGML_TYPE_I32: - kernel = backend_ctx->kernel_repeat_i32; - break; - default: - GGML_ABORT("unsupported type"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne1*nth, (size_t)ne2, (size_t)ne3}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_pad(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(src0->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_F32); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - if (backend_ctx->kernel_pad == nullptr) { - GGML_LOG_WARN("%s: pad kernel not available, skipping OpenCL execution.\n", __func__); - return; - } - - ggml_tensor_extra_cl * extra_src0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong off_src0 = extra_src0->offset + src0->view_offs; - cl_ulong off_dst = extra_dst->offset + dst->view_offs; - - const int s_ne0 = src0->ne[0]; - const int s_ne1 = src0->ne[1]; - const int s_ne2 = src0->ne[2]; - const int s_ne3 = src0->ne[3]; - - const int s_nb0 = src0->nb[0]; - const int s_nb1 = src0->nb[1]; - const int s_nb2 = src0->nb[2]; - const int s_nb3 = src0->nb[3]; - - const int d_ne0 = dst->ne[0]; - const int d_ne1 = dst->ne[1]; - const int d_ne2 = dst->ne[2]; - const int d_ne3 = dst->ne[3]; - - const int d_nb0 = dst->nb[0]; - const int d_nb1 = dst->nb[1]; - const int d_nb2 = dst->nb[2]; - const int d_nb3 = dst->nb[3]; - - const int lp0 = ((const int*)(dst->op_params))[0]; - const int rp0 = ((const int*)(dst->op_params))[1]; - const int lp1 = ((const int*)(dst->op_params))[2]; - const int rp1 = ((const int*)(dst->op_params))[3]; - const int lp2 = ((const int*)(dst->op_params))[4]; - const int rp2 = ((const int*)(dst->op_params))[5]; - const int lp3 = ((const int*)(dst->op_params))[6]; - const int rp3 = ((const int*)(dst->op_params))[7]; - - cl_kernel kernel = backend_ctx->kernel_pad; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &off_dst)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &s_ne0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &s_ne1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &s_ne2)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &s_ne3)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &s_nb0)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &s_nb1)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &s_nb2)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &s_nb3)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &d_ne0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &d_ne1)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &d_ne2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &d_ne3)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &d_nb0)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &d_nb1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &d_nb2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &d_nb3)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &lp0)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &rp0)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &lp1)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &rp1)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &lp2)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &rp2)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &lp3)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(int), &rp3)); - - size_t lws0 = 64; - size_t gws0 = (( (size_t)d_ne0 + lws0 - 1 ) / lws0) * lws0; - - size_t global_work_size[] = { gws0, (size_t)d_ne1, (size_t)d_ne2*d_ne3 }; - size_t local_work_size[] = { lws0, 1, 1 }; - - size_t * local_work_size_ptr = local_work_size; - if (d_ne0 % lws0 != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_upscale(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(src0->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_F32); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - const int mode_flags = (ggml_scale_mode) ggml_get_op_params_i32(dst, 0); - const ggml_scale_mode mode = (ggml_scale_mode) (mode_flags & 0xFF); - cl_kernel kernel = nullptr; - - if (mode == GGML_SCALE_MODE_NEAREST) { - kernel = backend_ctx->kernel_upscale; - if (kernel == nullptr) { - GGML_LOG_WARN("%s: nearest upscale kernel not available, skipping OpenCL execution.\n", __func__); - return; - } - } else if (mode == GGML_SCALE_MODE_BILINEAR) { - kernel = backend_ctx->kernel_upscale_bilinear; - if (kernel == nullptr) { - GGML_LOG_WARN("%s: bilinear upscale kernel not available, skipping OpenCL execution.\n", __func__); - return; - } - } else { - GGML_LOG_WARN("%s: unsupported upscale mode %d, skipping OpenCL execution.\n", __func__, mode); - return; - } - - ggml_tensor_extra_cl * extra_src0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong off_src0 = extra_src0->offset + src0->view_offs; - cl_ulong off_dst = extra_dst->offset + dst->view_offs; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - const int ne2 = dst->ne[2]; - const int ne3 = dst->ne[3]; - - float sf0 = (float)ne0 / ne00; - float sf1 = (float)ne1 / ne01; - float sf2 = (float)ne2 / ne02; - float sf3 = (float)ne3 / ne03; - - float pixel_offset = 0.5f; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &off_dst)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb03)); - - if (mode == GGML_SCALE_MODE_NEAREST) { - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne3)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float), &sf0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &sf1)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &sf2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &sf3)); - } else if (mode == GGML_SCALE_MODE_BILINEAR) { - if (mode_flags & GGML_SCALE_FLAG_ALIGN_CORNERS) { - sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0; - sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1; - pixel_offset = 0.0f; - } - - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne3)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &sf0)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &sf1)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &sf2)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(float), &sf3)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(float), &pixel_offset)); - } - - - size_t dst_total_elements = (size_t)ne0 * ne1 * ne2 * ne3; - if (dst_total_elements == 0) { - return; - } - size_t global_work_size[] = { dst_total_elements, 1, 1 }; - size_t local_work_size_pref = 256; - size_t local_work_size[] = { MIN(local_work_size_pref, dst_total_elements), 1, 1}; - - size_t * local_work_size_ptr = local_work_size; - if (dst_total_elements % local_work_size[0] != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); -} - -static void ggml_cl_concat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(src0->type == src1->type); - GGML_ASSERT(src0->type == dst->type); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const cl_ulong nb10 = src1->nb[0]; - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - const int ne2 = dst->ne[2]; - const int ne3 = dst->ne[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - const cl_int dim = ((const int32_t *) dst->op_params)[0]; - GGML_ASSERT(dim >= 0 && dim <= 3); - - int nth = MIN(64, ne0); - - const size_t ts = ggml_type_size(dst->type); - // the pack kernel copies 4-byte elements, so it is only valid for those. - const bool concat_pack = (dim == 0 && ne0 < 32 && ts == 4); - cl_kernel kernel; - if (concat_pack) { - kernel = backend_ctx->kernel_concat_b4_pack; - } else { - switch (ts) { - case 1: kernel = backend_ctx->kernel_concat_b1; break; - case 2: kernel = backend_ctx->kernel_concat_b2; break; - case 4: kernel = backend_ctx->kernel_concat_b4; break; - case 8: kernel = backend_ctx->kernel_concat_b8; break; - default: GGML_ABORT("unsupported concat element size: %zu", ts); - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_int), &dim)); - - if (concat_pack) { - // packed kernel needs the dst dims to unflatten its 1-D row index. - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &ne3)); - - const int maxwg = (int)backend_ctx->get_kernel_workgroup_size(kernel); - const int base = MIN(64, maxwg); - const int tpr = MIN(ne0, base); // threads per row - const int rpw = MAX(1, base / tpr); // rows per workgroup - const int lsz = tpr * rpw; - const int nrows = ne1*ne2*ne3; - const int nwg = (nrows + rpw - 1) / rpw; - size_t global_work_size[] = {(size_t)nwg*lsz, 1, 1}; - size_t local_work_size[] = {(size_t)lsz, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); - } else { - size_t global_work_size[] = {(size_t)ne1*nth, (size_t)ne2, (size_t)ne3}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_timestep_embedding(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_ASSERT(src0->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_F32); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - if (backend_ctx->kernel_timestep_embedding == nullptr) { - GGML_LOG_WARN("%s: timestep_embedding kernel not available, skipping OpenCL execution.\n", __func__); - return; - } - - ggml_tensor_extra_cl * extra_src0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong off_src0 = extra_src0->offset + src0->view_offs; - cl_ulong off_dst = extra_dst->offset + dst->view_offs; - - const int logical_dim = dst->op_params[0]; - const int max_period = dst->op_params[1]; - const int dst_nb1_bytes = dst->nb[1]; - - cl_kernel kernel = backend_ctx->kernel_timestep_embedding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &off_dst)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &dst_nb1_bytes)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &logical_dim)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &max_period)); - - size_t gws0 = (size_t)(((logical_dim + 1) / 2) + 1); - - size_t gws1 = (size_t)src0->ne[0]; - - size_t global_work_size[] = {gws0, gws1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, NULL, dst); -} - -struct ggml_cl_flash_attn_temp_buffer { - cl_mem data = nullptr; - - ~ggml_cl_flash_attn_temp_buffer() { - if (data != nullptr) { - CL_CHECK(clReleaseMemObject(data)); - data = nullptr; - } - } -}; - -// Resolve the source buffer + strides for an FA KV tensor: keep the -// caller-supplied AoS buffer if non-NULL, else fall back to tensor->extra. -static void ggml_cl_flash_attn_resolve_src( - const ggml_tensor * tensor, - cl_mem & buf, - cl_ulong & offset, - cl_ulong & nb1, - cl_ulong & nb2, - cl_ulong & nb3) { - if (buf != NULL) { - return; - } - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; - GGML_ASSERT(extra && extra->data_device); - buf = extra->data_device; - offset = extra->offset + tensor->view_offs; - nb1 = tensor->nb[1]; - nb2 = tensor->nb[2]; - nb3 = tensor->nb[3]; -} - -// Read a (possibly strided-view) tensor from device into a tight host buffer. -// dim 0 is always tight; a strided view is gathered row-by-row. -static void ggml_cl_flash_attn_read_tensor_host( - ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * tensor, - cl_mem src_buffer, cl_ulong src_offset, - cl_ulong src_nb1, cl_ulong src_nb2, cl_ulong src_nb3, - size_t row_bytes, void * dst, size_t total_bytes -) { - const bool contiguous_layout = - src_nb1 == row_bytes && - src_nb2 == row_bytes * (cl_ulong) tensor->ne[1] && - src_nb3 == src_nb2 * (cl_ulong) tensor->ne[2]; - - if (contiguous_layout) { - CL_CHECK(clEnqueueReadBuffer(backend_ctx->queue, src_buffer, CL_TRUE, - src_offset, total_bytes, dst, 0, NULL, NULL)); - return; - } - - size_t dst_off = 0; - for (int64_t i3 = 0; i3 < tensor->ne[3]; ++i3) { - for (int64_t i2 = 0; i2 < tensor->ne[2]; ++i2) { - for (int64_t i1 = 0; i1 < tensor->ne[1]; ++i1) { - const cl_ulong row_src_off = src_offset + - (cl_ulong) i3 * src_nb3 + - (cl_ulong) i2 * src_nb2 + - (cl_ulong) i1 * src_nb1; - CL_CHECK(clEnqueueReadBuffer(backend_ctx->queue, src_buffer, CL_TRUE, - row_src_off, row_bytes, - (uint8_t *) dst + dst_off, 0, NULL, NULL)); - dst_off += row_bytes; - } - } - } - GGML_ASSERT(dst_off == total_bytes); -} - -// forward decl: used by the FA decode dispatch (K-image variant) below. -static cl_mem ggml_cl_img_pool_get_or_create( - ggml_backend_opencl_context * backend_ctx, - std::map & pool, - cl_mem data_device, - cl_ulong offset0, - size_t required_bytes, - cl_channel_type channel_data_type); - -// Rebuild AoS q8_0/q4_0 bytes from a SoA tensor into a temp buffer. -// Returns false if the tensor is not SoA-quantised (already AoS). -static bool ggml_cl_flash_attn_reconstruct_aos( - ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * tensor, - ggml_cl_flash_attn_temp_buffer & temp, - cl_mem & out_buf, - cl_ulong & out_offset, - cl_ulong & out_nb1, - cl_ulong & out_nb2, - cl_ulong & out_nb3 -) { - if (tensor == nullptr) { - return false; - } - const bool is_q8_0 = tensor->type == GGML_TYPE_Q8_0 && ggml_cl_is_q8_0_soa(tensor); - const bool is_q4_0 = tensor->type == GGML_TYPE_Q4_0 && ggml_cl_is_q4_0_soa(tensor); - if (!is_q8_0 && !is_q4_0) { - return false; - } - - // For views, SoA extra is on view_src (view->extra is pre-SoA). - // Noshuffle layout only applies to 2D weights, as determined by `use_adreno_kernels`, - // where ne2 == 1 and ne3 == 1 -- these are never FA inputs. - // Therefore, we use `restore_block_qk_0` kernels, not `restore_block_qk_0_noshuffle`. - const ggml_tensor * soa_src = tensor->view_src ? tensor->view_src : tensor; - cl_mem extra_q = NULL; - cl_mem extra_d = NULL; - if (is_q8_0) { - auto * e = (ggml_tensor_extra_cl_q8_0 *) soa_src->extra; - GGML_ASSERT(e && e->q && e->d); - extra_q = e->q; - extra_d = e->d; - } else { - auto * e = (ggml_tensor_extra_cl_q4_0 *) soa_src->extra; - GGML_ASSERT(e && e->q && e->d); - extra_q = e->q; - extra_d = e->d; - } - - // Reconstruct the whole parent; view offsets then work naturally. - const size_t parent_nbytes = ggml_nbytes(soa_src); - cl_int err; - temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, parent_nbytes, NULL, &err); - CL_CHECK(err); - - cl_kernel kernel = is_q8_0 ? backend_ctx->kernel_restore_block_q8_0 - : backend_ctx->kernel_restore_block_q4_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra_d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &temp.data)); - - const size_t n_blocks = (size_t) ggml_nelements(soa_src) / ggml_blck_size(soa_src->type); - size_t global_work_size[] = { n_blocks, 1, 1 }; - size_t local_work_size[] = { 1, 1, 1 }; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, - global_work_size, local_work_size, 0, NULL, NULL)); - - out_buf = temp.data; - out_offset = tensor->view_offs; - out_nb1 = tensor->nb[1]; - out_nb2 = tensor->nb[2]; - out_nb3 = tensor->nb[3]; - return true; -} - -// GPU dequant of a contiguous q4_0/q8_0 KV tensor to f16/f32. Caller supplies -// src_buf when reconstructing from SoA. Returns false for non-contig layouts -// (the kernel indexes blocks tightly within ne[0]) so the caller can fall back -// to the host path. -static bool ggml_cl_flash_attn_dequant_kv_gpu( - ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * tensor, - ggml_type target_type, - cl_mem in_src_buf, - cl_ulong in_src_offset, - cl_ulong in_src_nb1, - cl_ulong in_src_nb2, - cl_ulong in_src_nb3, - ggml_cl_flash_attn_temp_buffer & temp, - cl_mem & out_buf, - cl_ulong & out_offset, - cl_ulong & out_nb1, - cl_ulong & out_nb2, - cl_ulong & out_nb3 -) { - GGML_ASSERT(tensor->type == GGML_TYPE_Q8_0 || tensor->type == GGML_TYPE_Q4_0); - GGML_ASSERT(target_type == GGML_TYPE_F16 || target_type == GGML_TYPE_F32); - - const bool is_q8_0 = tensor->type == GGML_TYPE_Q8_0; - - cl_mem src_buf = in_src_buf; - cl_ulong src_offset = in_src_offset; - cl_ulong src_nb1 = in_src_nb1; - cl_ulong src_nb2 = in_src_nb2; - cl_ulong src_nb3 = in_src_nb3; - ggml_cl_flash_attn_resolve_src(tensor, src_buf, src_offset, src_nb1, src_nb2, src_nb3); - - if (tensor->nb[0] != (cl_ulong) ggml_type_size(tensor->type)) { - return false; - } - - const size_t n_blocks = (size_t) ggml_nelements(tensor) / 32; // block size is 32 - const size_t elem_size = ggml_type_size(target_type); - const size_t out_bytes = n_blocks * 32 * elem_size; - const cl_int nblk0_arg = (cl_int) (tensor->ne[0] / 32); - const cl_int ne1_arg = (cl_int) tensor->ne[1]; - const cl_int ne2_arg = (cl_int) tensor->ne[2]; - const cl_int ne3_arg = (cl_int) tensor->ne[3]; - - cl_int err; - temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, out_bytes, NULL, &err); - CL_CHECK(err); - - cl_kernel kernel; - if (target_type == GGML_TYPE_F16) { - kernel = is_q8_0 ? backend_ctx->kernel_dequant_q8_0_f16_view_aos - : backend_ctx->kernel_dequant_q4_0_f16_view_aos; - } else { - kernel = is_q8_0 ? backend_ctx->kernel_dequant_q8_0_f32_view_aos - : backend_ctx->kernel_dequant_q4_0_f32_view_aos; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &src_offset)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &src_nb1)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &src_nb2)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &src_nb3)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &nblk0_arg)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne1_arg)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne2_arg)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne3_arg)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_mem), &temp.data)); - - size_t global_ws[3] = { (size_t) nblk0_arg, (size_t) ne1_arg, (size_t) ne2_arg * (size_t) ne3_arg }; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, - global_ws, NULL, 0, NULL, NULL)); - - out_buf = temp.data; - out_offset = 0; - out_nb1 = (cl_ulong) tensor->ne[0] * elem_size; - out_nb2 = out_nb1 * (cl_ulong) tensor->ne[1]; - out_nb3 = out_nb2 * (cl_ulong) tensor->ne[2]; - return true; -} - -static bool ggml_cl_flash_attn_prepare_quantized_tensor( - ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * tensor, - ggml_type target_type, - ggml_cl_flash_attn_temp_buffer & temp, - cl_mem & data_device, - cl_ulong & offset, - cl_ulong & nb1, - cl_ulong & nb2, - cl_ulong & nb3 -) { - if (!ggml_is_quantized(tensor->type)) { - return false; - } - - // Caller-supplied AoS buffer wins over tensor->extra when present. - cl_mem src_buffer = data_device; - cl_ulong src_offset = offset; - cl_ulong src_nb1 = nb1; - cl_ulong src_nb2 = nb2; - cl_ulong src_nb3 = nb3; - ggml_cl_flash_attn_resolve_src(tensor, src_buffer, src_offset, src_nb1, src_nb2, src_nb3); - - const int64_t n = ggml_nelements(tensor); - const size_t row_bytes = (size_t) (tensor->ne[0] / ggml_blck_size(tensor->type)) * ggml_type_size(tensor->type); - // tight-packed byte count (ggml_nbytes includes stride gaps). - const size_t total_bytes = (size_t) (n / ggml_blck_size(tensor->type)) * ggml_type_size(tensor->type); - std::vector host_quant(total_bytes); - - sync_with_other_backends(backend_ctx); - ggml_cl_flash_attn_read_tensor_host(backend_ctx, tensor, src_buffer, src_offset, - src_nb1, src_nb2, src_nb3, - row_bytes, host_quant.data(), total_bytes); - - std::vector host_f32(n); - ggml_get_type_traits(tensor->type)->to_float(host_quant.data(), host_f32.data(), n); - - const size_t bytes_per_elem = ggml_type_size(target_type); - const size_t buffer_size = (size_t) n * bytes_per_elem; - - std::vector host_linear(buffer_size); - if (target_type == GGML_TYPE_F32) { - memcpy(host_linear.data(), host_f32.data(), buffer_size); - } else { - GGML_ASSERT(target_type == GGML_TYPE_F16); - ggml_fp32_to_fp16_row(host_f32.data(), (ggml_fp16_t *) host_linear.data(), n); - } - - cl_int err; - temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, buffer_size, NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer(backend_ctx->queue, temp.data, CL_TRUE, 0, buffer_size, host_linear.data(), 0, NULL, NULL)); - - data_device = temp.data; - offset = 0; - nb1 = (cl_ulong) (tensor->ne[0] * bytes_per_elem); - nb2 = (cl_ulong) (tensor->ne[1] * nb1); - nb3 = (cl_ulong) (tensor->ne[2] * nb2); - - static bool warned = false; - if (!warned) { - GGML_LOG_WARN("ggml_opencl: OpenCL flash attention dequantizes GPU-resident quantized KV cache into temporary linear buffers; performance may be poor\n"); - warned = true; - } - - return true; -} - -// Host-side F16 -> F32 for the asymmetric-KV F32 fallback path. -static bool ggml_cl_flash_attn_convert_f16_to_f32( - ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * tensor, - ggml_cl_flash_attn_temp_buffer & temp, - cl_mem & data_device, - cl_ulong & offset, - cl_ulong & nb1, - cl_ulong & nb2, - cl_ulong & nb3 -) { - if (tensor->type != GGML_TYPE_F16) { - return false; - } - - cl_mem src_buffer = data_device; - cl_ulong src_offset = offset; - cl_ulong src_nb1 = nb1; - cl_ulong src_nb2 = nb2; - cl_ulong src_nb3 = nb3; - ggml_cl_flash_attn_resolve_src(tensor, src_buffer, src_offset, src_nb1, src_nb2, src_nb3); - - const int64_t n = ggml_nelements(tensor); - const size_t row_bytes = (size_t) tensor->ne[0] * sizeof(ggml_fp16_t); - const size_t total_bytes = (size_t) n * sizeof(ggml_fp16_t); - std::vector host_f16(total_bytes); - - sync_with_other_backends(backend_ctx); - ggml_cl_flash_attn_read_tensor_host(backend_ctx, tensor, src_buffer, src_offset, - src_nb1, src_nb2, src_nb3, - row_bytes, host_f16.data(), total_bytes); - - std::vector host_f32(n); - ggml_fp16_to_fp32_row((const ggml_fp16_t *) host_f16.data(), host_f32.data(), n); - - const size_t f32_bytes = (size_t) n * sizeof(float); - cl_int err; - temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, f32_bytes, NULL, &err); - CL_CHECK(err); - CL_CHECK(clEnqueueWriteBuffer(backend_ctx->queue, temp.data, CL_TRUE, 0, - f32_bytes, host_f32.data(), 0, NULL, NULL)); - - data_device = temp.data; - offset = 0; - nb1 = (cl_ulong) (tensor->ne[0] * sizeof(float)); - nb2 = (cl_ulong) (tensor->ne[1] * nb1); - nb3 = (cl_ulong) (tensor->ne[2] * nb2); - - static bool warned = false; - if (!warned) { - GGML_LOG_WARN("ggml_opencl: OpenCL flash attention asymmetric KV converts an F16 cache to F32 host-side; performance may be poor\n"); - warned = true; - } - - return true; -} - -// Flash-Decoding (K-split) dispatch thresholds. FD fires for non-causal -// attention with n_kv >= FD_MIN_N_KV and d_head <= FD_MAX_DK; the KV range is -// split into ~n_kv/FD_KV_PER_SPLIT partials, clamped to [FD_MIN_SPLITS, -// FD_MAX_SPLITS]. Multi-query FD is restricted to small heads -// (d_head <= FD_MAX_DK_MULTI) and capped at FD_MAX_N_Q_MULTI queries. -static constexpr int FD_MIN_N_KV = 2048; -static constexpr int FD_KV_PER_SPLIT = 2048; -// f16 KV decode wants more splits than the 2048 default; quantized KV keeps 2048. -static constexpr int FD_KV_PER_SPLIT_F16 = 512; -static constexpr int FD_MIN_SPLITS = 2; -static constexpr int FD_MAX_SPLITS = 16; -static constexpr int FD_MAX_DK = 128; -static constexpr int FD_MAX_DK_MULTI = 64; -static constexpr int FD_MAX_N_Q_MULTI = 8; -// MQ FD split-groups have few subgroups (MQ_NSG_SPLIT), so use a smaller -// kv_per_split to keep the softmax recurrence short; non-MQ keeps FD_KV_PER_SPLIT. -static constexpr int FD_MQ_KV_PER_SPLIT = 256; -static constexpr int FD_MQ_MAX_SPLITS = 128; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -struct ggml_cl_adreno_xmem_attn_schedule { - int qk_lws0 = 256; - int qk_lws2 = 1; - int softmax_reduce_lws0 = 256; - int softmax_apply_lws0 = 64; - int softmax_apply_lws2 = 4; - int pv_lws0 = 64; - int pv_lws2 = 4; -}; - -static inline size_t ggml_cl_round_up(size_t x, size_t a) { - return ((x + a - 1) / a) * a; -} - -static inline int ggml_cl_round_up_div(int x, int y) { - return (x + y - 1) / y; -} - -static inline void ggml_cl_set_arg_int4(cl_kernel kernel, cl_uint index, int x, int y, int z, int w) { - struct { int x, y, z, w; } value { x, y, z, w }; - CL_CHECK(clSetKernelArg(kernel, index, sizeof(value), &value)); -} - -static cl_mem ggml_cl_make_image2d_half4(cl_context context, cl_mem_flags flags, size_t width, size_t height) { - cl_int err = CL_SUCCESS; - cl_image_format format = { CL_RGBA, CL_HALF_FLOAT }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE2D; - desc.image_width = width; - desc.image_height = height; - cl_mem image = clCreateImage(context, flags, &format, &desc, nullptr, &err); - CL_CHECK(err); - return image; -} - -static cl_mem ggml_cl_make_image1d_buffer_half4(cl_context context, cl_mem_flags flags, size_t width, cl_mem backing_buffer) { - cl_int err = CL_SUCCESS; - cl_image_format format = { CL_RGBA, CL_HALF_FLOAT }; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = width; - desc.buffer = backing_buffer; - cl_mem image = clCreateImage(context, flags, &format, &desc, nullptr, &err); - CL_CHECK(err); - return image; -} - -static void ggml_cl_release_mem(cl_mem & mem) { - if (mem != nullptr) { - CL_CHECK(clReleaseMemObject(mem)); - mem = nullptr; - } -} - -static void ggml_cl_adreno_xmem_attn_release_scratch(ggml_backend_opencl_context * backend_ctx) { - auto & s = backend_ctx->adreno_xmem_attn.scratch; - ggml_cl_release_mem(s.q_img); - ggml_cl_release_mem(s.k_img); - ggml_cl_release_mem(s.v_img); - ggml_cl_release_mem(s.out_img); - ggml_cl_release_mem(s.k_transpose_img1d); - ggml_cl_release_mem(s.k_transpose_buf); - ggml_cl_release_mem(s.k_packed_buf); - ggml_cl_release_mem(s.v_packed_buf); - ggml_cl_release_mem(s.score_img1d); - ggml_cl_release_mem(s.prob_img1d); - ggml_cl_release_mem(s.score_buf); - ggml_cl_release_mem(s.prob_buf); - ggml_cl_release_mem(s.softmax_stats_img2d); - ggml_cl_release_mem(s.xmem_qk); - ggml_cl_release_mem(s.xmem_pv); - s = {}; -} - -static ggml_cl_adreno_xmem_attn_schedule ggml_cl_adreno_xmem_attn_select_schedule( - const ggml_backend_opencl_context * backend_ctx, - int n_q, - int n_kv, - int heads_total, - int q_width, - int gqa_ratio) { - const bool big_h = heads_total >= 8; - ggml_cl_adreno_xmem_attn_schedule sched; - - if (gqa_ratio == 1) { - if (n_q >= 512) { sched.qk_lws0 = 512; } - else if (n_q >= 256) { sched.qk_lws0 = 128; } - else { sched.qk_lws0 = 64; } - sched.qk_lws2 = (big_h && n_q >= 512) ? 2 : 1; - } else { - if (q_width >= 2048) { sched.qk_lws0 = 512; } - else if (q_width >= 256) { sched.qk_lws0 = 128; } - else { sched.qk_lws0 = 64; } - sched.qk_lws2 = MIN(8, (int) backend_ctx->max_workgroup_size / sched.qk_lws0); - } - - if (n_kv >= 2048) { sched.softmax_reduce_lws0 = 1024; } - else if (n_kv >= 512) { sched.softmax_reduce_lws0 = big_h ? 256 : 512; } - else { sched.softmax_reduce_lws0 = 256; } - - if (n_kv < 256) { sched.softmax_apply_lws0 = 64; } - else { sched.softmax_apply_lws0 = big_h ? 128 : 64; } - sched.softmax_apply_lws2 = n_kv >= 512 ? 8 : 4; - - if (n_q < 256) { sched.pv_lws0 = 64; } - else { sched.pv_lws0 = big_h ? 128 : 64; } - sched.pv_lws2 = big_h ? 8 : (n_q <= 256 ? 8 : 4); - - const int max_wg = (int) backend_ctx->max_workgroup_size; - auto fix = [&](int & l0, int & l2) { - while (l0 * l2 > max_wg) { - if (l2 > 1) { l2 /= 2; } - else if (l0 > 32) { l0 /= 2; } - else { break; } - } - }; - fix(sched.qk_lws0, sched.qk_lws2); - fix(sched.softmax_apply_lws0, sched.softmax_apply_lws2); - fix(sched.pv_lws0, sched.pv_lws2); - while (sched.softmax_reduce_lws0 > max_wg) { - sched.softmax_reduce_lws0 /= 2; - } - - return sched; -} - -static bool ggml_cl_adreno_xmem_attn_prepare( - ggml_backend_opencl_context * backend_ctx, - int n_q, - int n_kv, - int d_head_q, - int d_head_v, - int n_head, - int n_head_kv, - int n_batch) { - auto & s = backend_ctx->adreno_xmem_attn.scratch; - const int gqa_ratio = n_head / n_head_kv; - const int q_width = n_q * gqa_ratio; - const int kv_heads_total = n_head_kv * n_batch; - const int n_kv_padded = (int) ggml_cl_round_up((size_t) n_kv, 32); - if (s.q_img != nullptr && - s.n_q == n_q && - s.n_kv == n_kv && - s.n_kv_padded == n_kv_padded && - s.d_head_q == d_head_q && - s.d_head_v == d_head_v && - s.q_width == q_width && - s.kv_heads_total == kv_heads_total) { - return true; - } - - ggml_cl_adreno_xmem_attn_release_scratch(backend_ctx); - - const int qpack = d_head_q / 4; - const int vpack = d_head_v / 4; - const int npack = n_kv_padded / 4; - const size_t q_img_h = (size_t) kv_heads_total * qpack; - const size_t v_img_h = (size_t) kv_heads_total * vpack; - - s.q_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) q_width, q_img_h); - s.k_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) n_kv_padded, q_img_h); - s.v_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) n_kv_padded, v_img_h); - s.out_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) q_width, v_img_h); - - const size_t k_transpose_half4_elems = (size_t) npack * kv_heads_total * d_head_q; - s.k_transpose_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, k_transpose_half4_elems * sizeof(uint16_t) * 4, nullptr, nullptr); - GGML_ASSERT(s.k_transpose_buf != nullptr); - s.k_transpose_img1d = ggml_cl_make_image1d_buffer_half4(backend_ctx->context, CL_MEM_READ_ONLY, k_transpose_half4_elems, s.k_transpose_buf); - - const size_t k_groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_q, 16); - const size_t v_groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_v, 16); - const size_t k_packed_half4_elems = (size_t) n_kv_padded * k_groups16 * 4; - const size_t v_packed_half4_elems = (size_t) n_kv_padded * v_groups16 * 4; - s.k_packed_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, k_packed_half4_elems * sizeof(uint16_t) * 4, nullptr, nullptr); - s.v_packed_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, v_packed_half4_elems * sizeof(uint16_t) * 4, nullptr, nullptr); - GGML_ASSERT(s.k_packed_buf != nullptr && s.v_packed_buf != nullptr); - - const size_t score_half4_elems = (size_t) npack * kv_heads_total * q_width; - const size_t score_bytes = score_half4_elems * sizeof(uint16_t) * 4; - s.score_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, score_bytes, nullptr, nullptr); - s.prob_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, score_bytes, nullptr, nullptr); - GGML_ASSERT(s.score_buf != nullptr && s.prob_buf != nullptr); - s.score_img1d = ggml_cl_make_image1d_buffer_half4(backend_ctx->context, CL_MEM_READ_ONLY, score_half4_elems, s.score_buf); - s.prob_img1d = ggml_cl_make_image1d_buffer_half4(backend_ctx->context, CL_MEM_READ_ONLY, score_half4_elems, s.prob_buf); - s.softmax_stats_img2d = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, - (size_t) q_width, (size_t) kv_heads_total); - s.xmem_qk = clCreateBuffer(backend_ctx->context, CL_MEM_READ_ONLY, 6144, nullptr, nullptr); - s.xmem_pv = clCreateBuffer(backend_ctx->context, CL_MEM_READ_ONLY, 6144, nullptr, nullptr); - GGML_ASSERT(s.softmax_stats_img2d != nullptr && s.xmem_qk != nullptr && s.xmem_pv != nullptr); - - s.n_q = n_q; - s.n_kv = n_kv; - s.n_kv_padded = n_kv_padded; - s.d_head_q = d_head_q; - s.d_head_v = d_head_v; - s.q_width = q_width; - s.kv_heads_total = kv_heads_total; - return true; -} - -static bool ggml_cl_adreno_xmem_attn_can_use( - const ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * q, - const ggml_tensor * k, - const ggml_tensor * dst) { - static const char * xmem_sdpa_env = getenv("GGML_OPENCL_XMEM_SDPA"); - if (xmem_sdpa_env == nullptr || xmem_sdpa_env[0] == '0') { - return false; - } - - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; - - if (!backend_ctx->adreno_xmem_attn.compiled || backend_ctx->gpu_family != GPU_FAMILY::ADRENO) { - return false; - } - if (q->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || - (k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_F32) || - (v->type != GGML_TYPE_F16 && v->type != GGML_TYPE_F32)) { - return false; - } - if (sinks != nullptr) { - return false; - } - if (q->nb[0] != ggml_type_size(q->type) || k->nb[0] != ggml_type_size(k->type) || - v->nb[0] != ggml_type_size(v->type) || dst->nb[0] != ggml_type_size(dst->type)) { - return false; - } - if (mask != nullptr && (mask->type != GGML_TYPE_F16 || mask->nb[0] != sizeof(ggml_fp16_t))) { - return false; - } - - const int n_q = q->ne[1]; - const int n_kv = k->ne[1]; - const int d_head_q = q->ne[0]; - const int d_head_v = v->ne[0]; - const int n_head = q->ne[2]; - const int n_head_kv = k->ne[2]; - const int n_batch = q->ne[3]; - - if (n_q <= 1 || n_kv <= 0 || n_kv > 8192) { - return false; - } - if (d_head_q != k->ne[0] || d_head_v != v->ne[0] || k->ne[1] != v->ne[1] || k->ne[3] != v->ne[3]) { - return false; - } - if (q->ne[3] != k->ne[3]) { - return false; - } - if (n_head_kv <= 0 || n_head % n_head_kv != 0 || k->ne[2] != v->ne[2]) { - return false; - } - if (dst->ne[0] != d_head_v || dst->ne[1] != n_head || dst->ne[2] != n_q || dst->ne[3] != n_batch) { - return false; - } - if ((d_head_q % 8) != 0 || (d_head_v % 32) != 0) { - return false; - } - if (mask != nullptr && - (mask->ne[0] < n_kv || mask->ne[1] < n_q || mask->ne[2] <= 0 || mask->ne[3] <= 0)) { - return false; - } - - float params[3]; - memcpy(params, dst->op_params, sizeof(params)); - if (params[1] != 0.0f || params[2] != 0.0f) { - return false; - } - - const int gqa_ratio = n_head / n_head_kv; - const int q_width = n_q * gqa_ratio; - const int kv_heads_total = n_head_kv * n_batch; - const int n_kv_padded = (int) ggml_cl_round_up((size_t) n_kv, 32); - const int qpack = d_head_q / 4; - const int vpack = d_head_v / 4; - const int npack = n_kv_padded / 4; - - if ((size_t) q_width > backend_ctx->image2d_max_width || - (size_t) n_kv_padded > backend_ctx->image2d_max_width) { - return false; - } - if ((size_t) kv_heads_total * (size_t) qpack > backend_ctx->image2d_max_height || - (size_t) kv_heads_total * (size_t) vpack > backend_ctx->image2d_max_height) { - return false; - } - if ((size_t) npack * (size_t) kv_heads_total * (size_t) d_head_q > backend_ctx->image_max_buffer_size || - (size_t) npack * (size_t) kv_heads_total * (size_t) q_width > backend_ctx->image_max_buffer_size) { - return false; - } - - return true; -} - -static void ggml_cl_adreno_xmem_attn_run( - ggml_backend_t backend, - const ggml_tensor * q, - const ggml_tensor * k, - ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - auto & xstate = backend_ctx->adreno_xmem_attn; - auto & s = xstate.scratch; - if (!xstate.logged) { - GGML_LOG_INFO("ggml_opencl: using Adreno xmem attention path\n"); - xstate.logged = true; - } - - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - - ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *) q->extra; - ggml_tensor_extra_cl * extra_k = (ggml_tensor_extra_cl *) k->extra; - ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *) v->extra; - ggml_tensor_extra_cl * extra_o = (ggml_tensor_extra_cl *) dst->extra; - ggml_tensor_extra_cl * extra_mask = mask ? (ggml_tensor_extra_cl *) mask->extra : nullptr; - - const cl_ulong offset_q = extra_q->offset + q->view_offs; - const cl_ulong offset_k = extra_k->offset + k->view_offs; - const cl_ulong offset_v = extra_v->offset + v->view_offs; - const cl_ulong offset_o = extra_o->offset + dst->view_offs; - const cl_ulong offset_mask = extra_mask ? extra_mask->offset + mask->view_offs : 0; - - const int n_q = q->ne[1]; - const int n_kv = k->ne[1]; - const int d_head_q = q->ne[0]; - const int d_head_v = v->ne[0]; - const int n_head = q->ne[2]; - const int n_head_kv = k->ne[2]; - const int n_batch = q->ne[3]; - const int heads_total = n_head * n_batch; - const int gqa_ratio = n_head / n_head_kv; - const int q_width = n_q * gqa_ratio; - const int kv_heads_total = n_head_kv * n_batch; - const int n_kv_padded = (int) ggml_cl_round_up((size_t) n_kv, 32); - const int qpack = d_head_q / 4; - const int opack = d_head_v / 4; - const int npack = n_kv_padded / 4; - const float scale = ((const float *) dst->op_params)[0]; - - GGML_ASSERT(ggml_cl_adreno_xmem_attn_prepare( - backend_ctx, n_q, n_kv, d_head_q, d_head_v, n_head, n_head_kv, n_batch)); - const ggml_cl_adreno_xmem_attn_schedule sched = - ggml_cl_adreno_xmem_attn_select_schedule( - backend_ctx, n_q, n_kv_padded, heads_total, q_width, gqa_ratio); - - { - size_t gws[3] = {ggml_cl_round_up((size_t) n_q, 8), (size_t) heads_total, (size_t) qpack}; - size_t lws[3] = {8, 1, (size_t) ((qpack <= 32) ? qpack : 1)}; - cl_kernel kernel = xstate.kernel_q_f32_to_img_scaled; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_q->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.q_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &d_head_q)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &n_batch)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &q->nb[1])); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &q->nb[2])); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &q->nb[3])); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - { - size_t gws[3] = {(size_t) n_kv_padded, (size_t) kv_heads_total, (size_t) qpack}; - size_t lws[3] = {8, 1, (size_t) ((qpack <= 32) ? qpack : 1)}; - cl_kernel kernel = k->type == GGML_TYPE_F16 ? - xstate.kernel_kv_f16_to_img_gqa : xstate.kernel_kv_f32_to_img_gqa; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_k->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_k)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.k_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &d_head_q)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_kv_padded)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_batch)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &k->nb[1])); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &k->nb[2])); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &k->nb[3])); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - { - size_t gws[3] = {(size_t) n_kv_padded, (size_t) kv_heads_total, (size_t) opack}; - size_t lws[3] = {8, 1, (size_t) ((opack <= 32) ? opack : 1)}; - cl_kernel kernel = v->type == GGML_TYPE_F16 ? - xstate.kernel_kv_f16_to_img_gqa : xstate.kernel_kv_f32_to_img_gqa; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_v->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_v)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.v_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &d_head_v)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_kv_padded)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_batch)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &v->nb[1])); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &v->nb[2])); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &v->nb[3])); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - { - size_t gws[3] = {(size_t) d_head_q, (size_t) kv_heads_total, (size_t) npack}; - size_t lws[3] = {(size_t) MIN(64, d_head_q), (size_t) (kv_heads_total >= 2 ? 2 : 1), (size_t) MIN(8, npack)}; - if (lws[0] * lws[1] * lws[2] > backend_ctx->max_workgroup_size) { - lws[1] = 1; - } - cl_kernel kernel = xstate.kernel_k_gather; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.k_transpose_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.k_img)); - ggml_cl_set_arg_int4(kernel, 2, n_kv_padded, kv_heads_total, npack, d_head_q); - ggml_cl_set_arg_int4(kernel, 3, qpack, 0, 0, 0); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - { - const size_t groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_q, 16); - const size_t packed_linear = (size_t) n_kv_padded * groups16; - const size_t lws0 = MIN((size_t) 1024, backend_ctx->max_workgroup_size); - size_t gws[3] = {ggml_cl_round_up(packed_linear, lws0), 1, 1}; - size_t lws[3] = {lws0, 1, 1}; - cl_kernel kernel = xstate.kernel_pack_k; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.k_packed_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.k_transpose_img1d)); - ggml_cl_set_arg_int4(kernel, 2, 8, (int) packed_linear, qpack, d_head_q); - ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, kv_heads_total, kv_heads_total, npack); - ggml_cl_set_arg_int4(kernel, 4, d_head_q, 0, 0, 0); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - { - size_t lws[3] = {(size_t) sched.qk_lws0, 1, (size_t) sched.qk_lws2}; - const int slices_per_group = sched.qk_lws2 * 8; - const size_t groups_z = (size_t) ggml_cl_round_up_div(npack, slices_per_group); - const size_t groups_x = (size_t) ggml_cl_round_up_div(q_width, sched.qk_lws0); - size_t gws[3] = { - lws[0] * groups_z, - groups_x, - (size_t) kv_heads_total * lws[2], - }; - - cl_kernel kernel = xstate.kernel_qk_gemm; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.score_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.k_packed_buf)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.xmem_qk)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &s.q_img)); - ggml_cl_set_arg_int4(kernel, 4, kv_heads_total, npack, q_width, 32); - ggml_cl_set_arg_int4(kernel, 5, qpack, 0, 0, kv_heads_total); - ggml_cl_set_arg_int4(kernel, 6, qpack, 1, 1, 0); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - cl_mem softmax_input_img = s.score_img1d; - cl_mem softmax_output_buf = s.prob_buf; - cl_mem pv_prob_img = s.prob_img1d; - - if (mask != nullptr) { - const cl_ulong mask_nb1 = mask->nb[1]; - const cl_ulong mask_nb2 = mask->nb[2]; - const cl_ulong mask_nb3 = mask->nb[3]; - const int mask_ne2 = mask->ne[2]; - const int mask_ne3 = mask->ne[3]; - size_t lws[3] = {(size_t) sched.softmax_apply_lws0, 1, (size_t) sched.softmax_apply_lws2}; - size_t gws[3] = { - ggml_cl_round_up((size_t) q_width, lws[0]), - (size_t) kv_heads_total, - ggml_cl_round_up((size_t) npack, lws[2]), - }; - cl_kernel kernel = xstate.kernel_mask_scores; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.prob_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.score_img1d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_mask->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_mask)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &q_width)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_kv_padded)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &kv_heads_total)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &mask_nb2)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &mask_nb3)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &mask_ne2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &mask_ne3)); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - - softmax_input_img = s.prob_img1d; - softmax_output_buf = s.score_buf; - pv_prob_img = s.score_img1d; - } - - { - size_t lws[3] = {(size_t) sched.softmax_reduce_lws0, 1, 1}; - size_t gws[3] = {ggml_cl_round_up((size_t) q_width, lws[0]), (size_t) kv_heads_total, 1}; - cl_kernel kernel = xstate.kernel_softmax_reduce_basic; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &softmax_input_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.softmax_stats_img2d)); - ggml_cl_set_arg_int4(kernel, 2, kv_heads_total, 1, q_width, n_kv); - ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, q_width, 0, 0); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - { - size_t lws[3] = {(size_t) sched.softmax_apply_lws0, 1, (size_t) sched.softmax_apply_lws2}; - size_t gws[3] = { - ggml_cl_round_up((size_t) q_width, lws[0]), - (size_t) kv_heads_total, - ggml_cl_round_up((size_t) npack, lws[2]), - }; - cl_kernel kernel = xstate.kernel_softmax_apply_basic; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &softmax_output_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &softmax_input_img)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.softmax_stats_img2d)); - ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, npack, q_width, 1); - ggml_cl_set_arg_int4(kernel, 4, kv_heads_total, q_width, n_kv, 0); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - { - const size_t groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_v, 16); - const size_t packed_linear = (size_t) n_kv_padded * groups16; - const size_t lws0 = MIN((size_t) 1024, backend_ctx->max_workgroup_size); - size_t gws[3] = {ggml_cl_round_up(packed_linear, lws0), 1, 1}; - size_t lws[3] = {lws0, 1, 1}; - cl_kernel kernel = xstate.kernel_pack_v; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.v_packed_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.v_img)); - ggml_cl_set_arg_int4(kernel, 2, 8, (int) packed_linear, npack, n_kv_padded); - ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, kv_heads_total, opack, 0); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - { - size_t lws[3] = {(size_t) sched.pv_lws0, 1, (size_t) sched.pv_lws2}; - const int blocks = ggml_cl_round_up_div(opack, 8); - const size_t groups_z = (size_t) ggml_cl_round_up_div(blocks, sched.pv_lws2); - const size_t groups_x = (size_t) ggml_cl_round_up_div(q_width, sched.pv_lws0); - size_t gws[3] = { - lws[0] * groups_z, - groups_x, - (size_t) kv_heads_total * lws[2], - }; - - cl_kernel kernel = xstate.kernel_pv_gemm; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.v_packed_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.xmem_pv)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &pv_prob_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &s.out_img)); - ggml_cl_set_arg_int4(kernel, 4, kv_heads_total, opack, q_width, 32); - ggml_cl_set_arg_int4(kernel, 5, npack, 0, 0, kv_heads_total); - ggml_cl_set_arg_int4(kernel, 6, kv_heads_total * q_width, npack, q_width, 1); - ggml_cl_set_arg_int4(kernel, 7, 1, 0, 0, 0); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - { - size_t gws[3] = {ggml_cl_round_up((size_t) n_q, 8), (size_t) heads_total, (size_t) opack}; - size_t lws[3] = {8, 1, (size_t) ((opack <= 32) ? opack : 1)}; - cl_kernel kernel = xstate.kernel_img_to_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_o->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_o)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.out_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &d_head_v)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_batch)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &dst->nb[1])); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &dst->nb[2])); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &dst->nb[3])); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } -} - -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static void ggml_cl_flash_attn_prefill_bin(ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst) { - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; - GGML_ASSERT(q->extra); - GGML_ASSERT(k->extra); - GGML_ASSERT(v->extra); - GGML_ASSERT(dst->extra); - if (mask) { - GGML_ASSERT(mask->extra); - } - if (sinks) { - GGML_ASSERT(sinks->extra); - } - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - cl_context context = backend_ctx->context; - - const int n_q = q->ne[1]; - const int n_kv = k->ne[1]; - const int d_head_q = q->ne[0]; - const int d_head_v = v->ne[0]; - const int n_head = q->ne[2]; - const int n_head_kv = k->ne[2]; - const int n_batch = q->ne[3]; - - const std::pair dk_dv = {d_head_q, d_head_v}; - cl_kernel kernel = backend_ctx->fa.kernel_flash_attn_f32_f16_bin; - GGML_ASSERT(kernel != NULL); - - ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *)q->extra; - ggml_tensor_extra_cl * extra_k = (ggml_tensor_extra_cl *)k->extra; - ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; - ggml_tensor_extra_cl * extra_o = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl * extra_mask = mask ? (ggml_tensor_extra_cl *)mask->extra : NULL; - ggml_tensor_extra_cl * extra_sinks = sinks ? (ggml_tensor_extra_cl *)sinks->extra : NULL; - - cl_ulong offset_q = extra_q->offset + q->view_offs; - cl_ulong offset_o = extra_o->offset + dst->view_offs; - - cl_mem mask_buffer = extra_mask ? extra_mask->data_device : NULL; - cl_ulong offset_mask = extra_mask ? extra_mask->offset + mask->view_offs : 0; - cl_mem sinks_buffer = extra_sinks ? extra_sinks->data_device : NULL; - cl_ulong offset_sinks = extra_sinks ? extra_sinks->offset + sinks->view_offs : 0; - - const cl_ulong q_nb1 = q->nb[1]; - const cl_ulong q_nb2 = q->nb[2]; - const cl_ulong q_nb3 = q->nb[3]; - - cl_mem k_data_device = extra_k->data_device; - cl_ulong offset_k = extra_k->offset + k->view_offs; - cl_ulong k_nb1 = k->nb[1]; - cl_ulong k_nb2 = k->nb[2]; - cl_ulong k_nb3 = k->nb[3]; - - cl_mem v_data_device = extra_v->data_device; - cl_ulong offset_v = extra_v->offset + v->view_offs; - cl_ulong v_nb1 = v->nb[1]; - cl_ulong v_nb2 = v->nb[2]; - cl_ulong v_nb3 = v->nb[3]; - - const cl_ulong o_nb1 = dst->nb[1]; - const cl_ulong o_nb2 = dst->nb[2]; - const cl_ulong o_nb3 = dst->nb[3]; - - const cl_ulong mask_nb1 = mask ? mask->nb[1] : 0; - const cl_ulong mask_nb2 = mask ? mask->nb[2] : 0; - const cl_ulong mask_nb3 = mask ? mask->nb[3] : 0; - const int mask_ne2 = mask ? mask->ne[2] : 0; - const int mask_ne3 = mask ? mask->ne[3] : 0; - - float * params = (float *)dst->op_params; - float scale = params[0]; - float max_bias = params[1]; - float logit_softcap = params[2]; - - const int is_causal = (mask == NULL && n_q > 1 && n_q == n_kv); // redundant n_q > 1 check ? - - const int n_head_log2_val = n_head > 0 ? 1u << (int)floorf(log2f((float)n_head)) : 0; - const float n_head_log2_f = n_head_log2_val > 0 ? (float)n_head_log2_val : 1.0f; - const float m0 = powf(2.0f, -(max_bias) / n_head_log2_f); - const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2_f); - - const bool is_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0; - - ggml_cl_flash_attn_temp_buffer temp_k; - ggml_cl_flash_attn_temp_buffer temp_v; - ggml_cl_flash_attn_temp_buffer temp_k_aos; - ggml_cl_flash_attn_temp_buffer temp_v_aos; - - if (is_q8_0) { - ggml_cl_flash_attn_reconstruct_aos( - backend_ctx, k, temp_k_aos, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); - - ggml_cl_flash_attn_reconstruct_aos( - backend_ctx, v, temp_v_aos, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); - - bool k_done = ggml_cl_flash_attn_dequant_kv_gpu( - backend_ctx, k, GGML_TYPE_F16, k_data_device, offset_k, k_nb1, k_nb2, k_nb3, - temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); - - bool v_done = ggml_cl_flash_attn_dequant_kv_gpu( - backend_ctx, v, GGML_TYPE_F16, v_data_device, offset_v, v_nb1, v_nb2, v_nb3, - temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); - - GGML_ASSERT(k_done && v_done); - } - - // Allocate input/output memory buffers - cl_mem mem_matrixQ; - cl_mem mem_matrixK; - cl_mem mem_matrixV; - cl_mem mem_matrixO; - cl_buffer_region region; - cl_int err; - - region.origin = offset_q; - region.size = ggml_nbytes(q); - mem_matrixQ = clCreateSubBuffer(extra_q->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - region.origin = offset_k; - region.size = is_q8_0 ? (size_t) k_nb3 * (size_t) k->ne[3] : ggml_nbytes(k); - mem_matrixK = clCreateSubBuffer(k_data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - region.origin = offset_v; - region.size = is_q8_0 ? (size_t) v_nb3 * (size_t) v->ne[3] : ggml_nbytes(v); - mem_matrixV = clCreateSubBuffer(v_data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - region.origin = offset_o; - region.size = ggml_nbytes(dst); - mem_matrixO = clCreateSubBuffer(extra_o->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt_1d = { CL_RGBA, CL_FLOAT}; - cl_image_desc img_desc_1d; - - // use image 1d buffer used as fallback when on mask is applied - cl_mem mem_tex_mask_fallback_1dbuf; - img_fmt_1d = { CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc_1d, 0, sizeof(img_desc_1d)); - img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc_1d.image_width = 1; - img_desc_1d.buffer = mem_matrixK; - mem_tex_mask_fallback_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &err); - CL_CHECK(err); - - cl_mem mem_tex_matrixO_1dbuf; - img_fmt_1d = { CL_RGBA, CL_FLOAT}; - memset(&img_desc_1d, 0, sizeof(img_desc_1d)); - img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc_1d.image_width = ggml_nbytes(dst) / 4 / 4; - img_desc_1d.buffer = mem_matrixO; - mem_tex_matrixO_1dbuf = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &err); - CL_CHECK(err); - - // The bin kernel requires 2d (or 3d) buffers packed for data loading/multiplication. - // These repack kernels launch across all buffers to ensure compatibility - cl_mem mem_tex_matrixMask_1dbuf = NULL; - cl_mem mem_matrixMask = NULL; - cl_mem mem_matrixMask_padded = NULL; - cl_ulong mask_nb1_padded = mask_nb1, mask_nb2_padded = mask_nb2, mask_nb3_padded = mask_nb3; - if (extra_mask) { - // allocate mem_matrixMask w/ new padded size - size_t n_kv_padded = GGML_PAD(n_kv, 4); - size_t mask_nb_padded = n_kv_padded * sizeof(cl_half) * mask->ne[1] * mask->ne[2] * mask->ne[3]; - - // apply offset and create subBuffer for mask - region.origin = offset_mask; - region.size = ggml_nbytes(mask); - mem_matrixMask = clCreateSubBuffer(extra_mask->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - { - // create padded mask to contain all data - mem_matrixMask_padded = clCreateBuffer(context, CL_MEM_ALLOC_HOST_PTR, mask_nb_padded, NULL, &err); - CL_CHECK(err); - - // pass extra_mask->data_device, mem_matrixMask to kernel for copying/padding - mask_nb1_padded = (cl_ulong)n_kv_padded * sizeof(cl_half); - mask_nb2_padded = mask_nb1_padded * (cl_ulong)mask->ne[1]; - mask_nb3_padded = mask_nb2_padded * (cl_ulong)mask->ne[2]; - - cl_kernel repack_mask = backend_ctx->fa.kernel_repack_mask_for_wmm; - CL_CHECK(clSetKernelArg(repack_mask, 0, sizeof(cl_mem), &mem_matrixMask)); - CL_CHECK(clSetKernelArg(repack_mask, 1, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(repack_mask, 2, sizeof(cl_ulong), &mask_nb2)); - CL_CHECK(clSetKernelArg(repack_mask, 3, sizeof(cl_ulong), &mask_nb3)); - CL_CHECK(clSetKernelArg(repack_mask, 4, sizeof(int), &mask_ne2)); - CL_CHECK(clSetKernelArg(repack_mask, 5, sizeof(cl_mem), &mem_matrixMask_padded)); - CL_CHECK(clSetKernelArg(repack_mask, 6, sizeof(cl_ulong), &mask_nb1_padded)); - CL_CHECK(clSetKernelArg(repack_mask, 7, sizeof(cl_ulong), &mask_nb2_padded)); - CL_CHECK(clSetKernelArg(repack_mask, 8, sizeof(cl_ulong), &mask_nb3_padded)); - - size_t repack_mask_gws[3] = {(size_t)n_kv, (size_t)mask->ne[1], (size_t)mask_ne2 * (size_t)mask->ne[3]}; - backend_ctx->enqueue_ndrange_kernel(repack_mask, 3, repack_mask_gws, NULL, dst); - } - - // use image 1d buffer for matrix Mask (padded row stride) - cl_image_format img_fmt_mask_1d = { CL_RGBA, CL_HALF_FLOAT}; - cl_image_desc img_desc_mask_1d; - memset(&img_desc_mask_1d, 0, sizeof(img_desc_mask_1d)); - img_desc_mask_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc_mask_1d.image_width = mask_nb_padded / 2 / 4; - img_desc_mask_1d.buffer = mem_matrixMask_padded; - mem_tex_matrixMask_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_mask_1d, &img_desc_mask_1d, NULL, &err); - CL_CHECK(err); - } - - // WMM QK uses repacked 3D images. - // Q image: rows, heads, packed depth. - cl_image_format img_fmt_3d = { CL_RGBA, CL_HALF_FLOAT }; - cl_image_desc img_desc_3d; - - memset(&img_desc_3d, 0, sizeof(img_desc_3d)); - img_desc_3d.image_type = CL_MEM_OBJECT_IMAGE3D; - img_desc_3d.image_width = (size_t)n_q; - img_desc_3d.image_height = (size_t)n_batch * (size_t)n_head; - img_desc_3d.image_depth = (size_t)d_head_q / 4; - cl_mem img_q_wmm = NULL; - img_q_wmm = clCreateImage(context, CL_MEM_READ_WRITE, &img_fmt_3d, &img_desc_3d, NULL, &err); - CL_CHECK(err); - - { - cl_kernel repack_q = backend_ctx->fa.kernel_repack_q_for_wmm; - CL_CHECK(clSetKernelArg(repack_q, 0, sizeof(cl_mem), &mem_matrixQ)); - CL_CHECK(clSetKernelArg(repack_q, 1, sizeof(cl_ulong), &q_nb1)); - CL_CHECK(clSetKernelArg(repack_q, 2, sizeof(cl_ulong), &q_nb2)); - CL_CHECK(clSetKernelArg(repack_q, 3, sizeof(cl_ulong), &q_nb3)); - CL_CHECK(clSetKernelArg(repack_q, 4, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(repack_q, 5, sizeof(cl_mem), &img_q_wmm)); - - size_t repack_q_gws[3] = {(size_t)d_head_q / 4, (size_t)n_q, (size_t)n_batch * (size_t)n_head}; - backend_ctx->enqueue_ndrange_kernel(repack_q, 3, repack_q_gws, NULL, dst); - } - - // K image: columns, row groups, KV heads. - const size_t n_kv_row4 = ((size_t)n_kv + 3) / 4; - - memset(&img_desc_3d, 0, sizeof(img_desc_3d)); - img_desc_3d.image_type = CL_MEM_OBJECT_IMAGE3D; - img_desc_3d.image_width = (size_t)d_head_q; - img_desc_3d.image_height = n_kv_row4; - img_desc_3d.image_depth = (size_t)n_batch * (size_t)n_head_kv; - cl_mem img_k_wmm = NULL; - img_k_wmm = clCreateImage(context, CL_MEM_READ_WRITE, &img_fmt_3d, &img_desc_3d, NULL, &err); - CL_CHECK(err); - - { - cl_kernel repack_k = backend_ctx->fa.kernel_repack_k_for_wmm; - CL_CHECK(clSetKernelArg(repack_k, 0, sizeof(cl_mem), &mem_matrixK)); - CL_CHECK(clSetKernelArg(repack_k, 1, sizeof(cl_ulong), &k_nb1)); - CL_CHECK(clSetKernelArg(repack_k, 2, sizeof(cl_ulong), &k_nb2)); - CL_CHECK(clSetKernelArg(repack_k, 3, sizeof(cl_ulong), &k_nb3)); - CL_CHECK(clSetKernelArg(repack_k, 4, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(repack_k, 5, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(repack_k, 6, sizeof(cl_mem), &img_k_wmm)); - - size_t repack_k_gws[3] = {(size_t)d_head_q, n_kv_row4, (size_t)n_batch * (size_t)n_head_kv}; - backend_ctx->enqueue_ndrange_kernel(repack_k, 3, repack_k_gws, NULL, dst); - } - - // V image: kv-rows (contracted), packed head-dim groups, KV heads. - memset(&img_desc_3d, 0, sizeof(img_desc_3d)); - img_desc_3d.image_type = CL_MEM_OBJECT_IMAGE3D; - img_desc_3d.image_width = (size_t)n_kv; - img_desc_3d.image_height = (size_t)d_head_v / 4; - img_desc_3d.image_depth = (size_t)n_batch * (size_t)n_head_kv; - cl_mem img_v_wmm = NULL; - img_v_wmm = clCreateImage(context, CL_MEM_READ_WRITE, &img_fmt_3d, &img_desc_3d, NULL, &err); - CL_CHECK(err); - - { - cl_kernel repack_v = backend_ctx->fa.kernel_repack_v_for_wmm; - CL_CHECK(clSetKernelArg(repack_v, 0, sizeof(cl_mem), &mem_matrixV)); - CL_CHECK(clSetKernelArg(repack_v, 1, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(repack_v, 2, sizeof(cl_ulong), &v_nb2)); - CL_CHECK(clSetKernelArg(repack_v, 3, sizeof(cl_ulong), &v_nb3)); - CL_CHECK(clSetKernelArg(repack_v, 4, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(repack_v, 5, sizeof(cl_mem), &img_v_wmm)); - - size_t repack_v_gws[3] = {(size_t)d_head_v / 4, (size_t)n_kv, (size_t)n_batch * (size_t)n_head_kv}; - backend_ctx->enqueue_ndrange_kernel(repack_v, 3, repack_v_gws, NULL, dst); - } - - cl_int enable_mask = (extra_mask) ? 1 : 0; - mask_buffer = extra_mask ? mem_tex_matrixMask_1dbuf : mem_tex_mask_fallback_1dbuf; - - cl_mem mem_sinksBuf = NULL; - cl_mem mem_tex_sinks_1dbuf = NULL; - cl_int enable_sinks = (sinks_buffer != NULL) ? 1 : 0; - if (enable_sinks) { - region.origin = offset_sinks; - region.size = ggml_nbytes(sinks); - mem_sinksBuf = clCreateSubBuffer(extra_sinks->data_device, CL_MEM_READ_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt_sinks_1d = { CL_R, CL_FLOAT }; - cl_image_desc img_desc_sinks_1d; - memset(&img_desc_sinks_1d, 0, sizeof(img_desc_sinks_1d)); - img_desc_sinks_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc_sinks_1d.image_width = (size_t)n_head; - img_desc_sinks_1d.buffer = mem_sinksBuf; - mem_tex_sinks_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_sinks_1d, &img_desc_sinks_1d, NULL, &err); - CL_CHECK(err); - } else { - // The image obj cannot be null so we back with buffer of size 1 and use matrixK to back because it always exists - cl_image_format img_fmt_sinks_fallback = { CL_R, CL_FLOAT }; - cl_image_desc img_desc_sinks_fallback; - memset(&img_desc_sinks_fallback, 0, sizeof(img_desc_sinks_fallback)); - img_desc_sinks_fallback.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc_sinks_fallback.image_width = 1; - img_desc_sinks_fallback.buffer = mem_matrixK; - mem_tex_sinks_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_sinks_fallback, &img_desc_sinks_fallback, NULL, &err); - CL_CHECK(err); - } - - cl_uint arg = 0; - - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &mem_tex_matrixO_1dbuf)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &is_causal)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &q_nb1)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &q_nb2)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &q_nb3)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &k_nb1)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &k_nb2)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &k_nb3)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &v_nb2)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &v_nb3)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &o_nb1)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &o_nb2)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &o_nb3)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_head_log2_val)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &logit_softcap)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &mask_buffer)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &enable_mask)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &mask_nb1_padded)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &mask_nb2_padded)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &mask_nb3_padded)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &mask_ne2)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &mask_ne3)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &mem_tex_sinks_1dbuf)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &enable_sinks)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &img_q_wmm)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &img_k_wmm)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &img_v_wmm)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &d_head_q)); - - size_t global_work_size[3], local_work_size[3]; - - const int n_waves_v = d_head_q / 64; - - local_work_size[0] = 64; - local_work_size[1] = n_waves_v; - local_work_size[2] = 1; - - global_work_size[0] = 64; - global_work_size[1] = ((n_q + 64 - 1) / 64) * n_waves_v; - global_work_size[2] = n_batch * n_head; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(mem_tex_matrixO_1dbuf)); - CL_CHECK(clReleaseMemObject(mem_tex_mask_fallback_1dbuf)); - CL_CHECK(clReleaseMemObject(img_q_wmm)); - CL_CHECK(clReleaseMemObject(img_k_wmm)); - CL_CHECK(clReleaseMemObject(img_v_wmm)); - - if (mem_tex_matrixMask_1dbuf) { - CL_CHECK(clReleaseMemObject(mem_tex_matrixMask_1dbuf)); - } - if (mem_matrixMask) { - CL_CHECK(clReleaseMemObject(mem_matrixMask)); - } - if (mem_matrixMask_padded) { - CL_CHECK(clReleaseMemObject(mem_matrixMask_padded)); - } - if (mem_tex_sinks_1dbuf) { - CL_CHECK(clReleaseMemObject(mem_tex_sinks_1dbuf)); - } - if (mem_sinksBuf) { - CL_CHECK(clReleaseMemObject(mem_sinksBuf)); - } - CL_CHECK(clReleaseMemObject(mem_matrixQ)); - CL_CHECK(clReleaseMemObject(mem_matrixK)); - CL_CHECK(clReleaseMemObject(mem_matrixV)); - CL_CHECK(clReleaseMemObject(mem_matrixO)); -} -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -static void ggml_cl_fa_q8_rows( - ggml_backend_t backend, const ggml_tensor * src, const ggml_tensor * dst, - cl_mem values, cl_mem scales, int64_t row0, int nrow -) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - auto * extra = (ggml_tensor_extra_cl *) (src->view_src ? src->view_src->extra : src->extra); - const cl_ulong offset = extra->offset + src->view_offs + row0 * src->nb[1]; - const cl_ulong nb1 = src->nb[1]; - const cl_ulong nb2 = src->nb[2]; - const int dk = src->ne[0]; - const int nhead = src->ne[2]; - cl_kernel kernel; - switch (src->type) { - case GGML_TYPE_F16: kernel = backend_ctx->kernel_fa_q8_rows_f16; break; - case GGML_TYPE_F32: kernel = backend_ctx->kernel_fa_q8_rows_f32; break; - default: GGML_ABORT("unsupported int8 KQ input type"); - } - cl_uint a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &values)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &scales)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dk)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nrow)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhead)); - const size_t blocks = (size_t) (dk / 32) * nrow * nhead; - size_t gws[3] = {(blocks + 63) / 64 * 64, 1, 1}; - size_t lws[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); -} - -static void ggml_cl_fa_kq_int8_prepare(ggml_backend_t backend, const ggml_tensor * dst, int64_t n_q_chunk) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const ggml_tensor * q = dst->src[0]; - const ggml_tensor * k = dst->src[1]; - const size_t k_bytes = (size_t) k->ne[0] * k->ne[1] * k->ne[2]; - const size_t q_bytes = (size_t) q->ne[0] * n_q_chunk * q->ne[2]; - backend_ctx->prealloc_fa_k8.allocate(backend_ctx->context, k_bytes); - backend_ctx->prealloc_fa_k8_scale.allocate(backend_ctx->context, k_bytes / 32 * sizeof(cl_half)); - backend_ctx->prealloc_fa_q8.allocate(backend_ctx->context, q_bytes); - backend_ctx->prealloc_fa_q8_scale.allocate(backend_ctx->context, q_bytes / 32 * sizeof(cl_half)); - ggml_cl_fa_q8_rows(backend, k, dst, backend_ctx->prealloc_fa_k8.buffer, backend_ctx->prealloc_fa_k8_scale.buffer, 0, k->ne[1]); -} - -static void ggml_cl_fa_kq_p8_dispatch( - ggml_backend_t backend, - const ggml_tensor * q, const ggml_tensor * k, - const ggml_tensor * mask, const ggml_tensor * sinks, - const ggml_tensor * dst, - int64_t q0, int nqc, float scale, float max_bias, int p_pitch, bool kq_int8 -) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - auto * extra_k = (ggml_tensor_extra_cl *) (k->view_src ? k->view_src->extra : k->extra); - auto * extra_q = (ggml_tensor_extra_cl *) q->extra; - auto * extra_m = (ggml_tensor_extra_cl *) mask->extra; - - const int M = k->ne[1]; - const int K = k->ne[0]; - const int N = nqc; - const int D_A = k->ne[2]; - const int D_B = q->ne[2]; - - const cl_ulong off_mask = extra_m->offset + mask->view_offs + q0 * mask->nb[1]; - const cl_ulong mask_nb1 = mask->nb[1]; - const int n_head_log2 = 1u << (unsigned) floorf(log2f((float) D_B)); - const float m0 = powf(2.0f, -max_bias / n_head_log2); - const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); - - cl_kernel kernel; - cl_uint a = 0; - - if (kq_int8) { - ggml_cl_fa_q8_rows(backend, q, dst, backend_ctx->prealloc_fa_q8.buffer, backend_ctx->prealloc_fa_q8_scale.buffer, q0, nqc); - kernel = K <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8_scale.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8_scale.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); - size_t gws[3] = {64 * (((size_t) N + 31) / 32) * (D_B / D_A), ((size_t) M + 511) / 512, (size_t) D_A}; - size_t lws[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } else { - cl_int err; - - cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; - cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format fmt = {CL_RGBA, CL_FLOAT}; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = region.size / 16; - desc.buffer = k_sub; - cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); - CL_CHECK(err); - - region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; - region.size = (size_t) K * N * D_B * sizeof(float); - cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - kernel = backend_ctx->kernel_mul_mm_f16_f32_kq_p8; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); - - // Pack query heads of each KV group into a short batch's tile. - static const bool fold_enabled = [] { - const char * e = getenv("GGML_OPENCL_FA_KQ_P8_FOLD"); - return !e || e[0] != '0'; - }(); - const int gqa = D_B / D_A; - const int fold = fold_enabled && gqa > 1 && N < 32 && gqa <= INT_MAX / N ? gqa : 1; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &fold)); - - const size_t n_tiles = ((size_t) N * fold + 31) / 32; - size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * (fold > 1 ? D_A : D_B)}; - - const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; - size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - CL_CHECK(clReleaseMemObject(k_img)); - CL_CHECK(clReleaseMemObject(k_sub)); - CL_CHECK(clReleaseMemObject(q_sub)); - } - - cl_mem sinks_buf = extra_q->data_device; - cl_ulong sinks_off = 0; - const int has_sinks = sinks != nullptr; - - if (sinks) { - auto * extra_s = (ggml_tensor_extra_cl *) sinks->extra; - sinks_buf = extra_s->data_device; - sinks_off = extra_s->offset + sinks->view_offs; - } - - const int nblk = M / 32; - const int row_blk = p_pitch / 32; - - kernel = backend_ctx->kernel_fa_p8_fixup; - - a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_sums.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &sinks_buf)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &sinks_off)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &has_sinks)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nblk)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &row_blk)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); - - size_t gws_fixup[3] = {(size_t) 64 * N, (size_t) D_B, 1}; - size_t lws_fixup[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws_fixup, lws_fixup, dst); -} - -static void ggml_cl_fa_decompose_scratch_tensor( - ggml_tensor & t, ggml_tensor_extra_cl & extra, cl_mem buffer, ggml_type type, - int64_t ne0, int64_t ne1, int64_t ne2 -) { - memset(&t, 0, sizeof(t)); - t.type = type; - t.ne[0] = ne0; t.ne[1] = ne1; t.ne[2] = ne2; t.ne[3] = 1; - t.nb[0] = ggml_type_size(type); - t.nb[1] = t.nb[0]*ne0; - t.nb[2] = t.nb[1]*ne1; - t.nb[3] = t.nb[2]*ne2; - - extra.reset(); - extra.data_device = buffer; - t.extra = &extra; -} - -static void ggml_cl_fa_decompose_write_chunk( - ggml_backend_t backend, const ggml_tensor & kqv, int64_t q0, ggml_tensor * dst -) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const int64_t dv = kqv.ne[0]; - const int64_t nqc = kqv.ne[1]; - const int64_t n_head = kqv.ne[2]; - - // apply the deferred 1/sum to the KQV rows - { - cl_kernel kernel = backend_ctx->kernel_fa_decompose_scale_rows_f32; - const cl_ulong offset_kqv = 0; - const cl_ulong offset_sums = 0; - const int dv_i = (int) dv; - const int nqc_i = (int) nqc; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_kqv)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &backend_ctx->prealloc_fa_sums.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_sums)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &dv_i)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &nqc_i)); - - size_t gws[3] = { (size_t) 64 * nqc, (size_t) n_head, 1 }; - size_t lws[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - // permute into dst: [dv, nqc, n_head] -> dst[dv, n_head, q0 .. q0+nqc) - { - ggml_tensor kqv_perm = kqv; - kqv_perm.ne[1] = n_head; - kqv_perm.ne[2] = nqc; - kqv_perm.nb[1] = kqv.nb[2]; - kqv_perm.nb[2] = kqv.nb[1]; - - ggml_tensor dst_chunk = *dst; - dst_chunk.ne[2] = nqc; - dst_chunk.view_offs = dst->view_offs + (size_t) q0 * dst->nb[2]; - - ggml_cl_cpy(backend, &kqv_perm, &dst_chunk, nullptr); - } -} - -static void ggml_cl_flash_attn_decompose( - ggml_backend_t backend, - const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst, - int64_t n_q_chunk, float scale, float max_bias -) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; - const int64_t n_q = q->ne[1]; - const int64_t n_kv = k->ne[1]; - const int64_t dv = v->ne[0]; - const int64_t n_head = q->ne[2]; - const int64_t n_head_kv = k->ne[2]; - - const std::pair dk_dv = {(int) q->ne[0], (int) dv}; - - // The image GEMMs work in 64 x 32 tiles and can touch past the exact extent, - // so size each scratch by the padded shape plus one extra head. - auto pad_up = [](int64_t x, int64_t a) { return ((x + a - 1) / a) * a; }; - const int64_t kq_m = pad_up(n_kv, 64); - const int64_t kqv_m = pad_up(dv, 64); - const int64_t tile_n = pad_up(n_q_chunk, 32); - - backend_ctx->prealloc_fa_vt.allocate(backend_ctx->context, (size_t)(n_kv * kqv_m * (n_head_kv + 1)) * sizeof(ggml_fp16_t)); - backend_ctx->prealloc_fa_kq.allocate(backend_ctx->context, (size_t)(kq_m * tile_n * (n_head + 1)) * sizeof(float)); - backend_ctx->prealloc_fa_kqv.allocate(backend_ctx->context, (size_t)(kqv_m * tile_n * (n_head + 1)) * sizeof(float)); - backend_ctx->prealloc_fa_sums.allocate(backend_ctx->context, (size_t)(n_q_chunk * n_head) * sizeof(float)); - - // V^T once per call: [dv, n_kv, n_head_kv] -> [n_kv, dv, n_head_kv] - { - ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; - cl_kernel kernel = backend_ctx->fa.v_transpose_f16.at(dk_dv); - - const cl_ulong offset_v = extra_v->offset + v->view_offs; - const cl_ulong v_nb1 = v->nb[1]; - const cl_ulong v_nb2 = v->nb[2]; - const int n_kv_i = (int) n_kv; - const int dv_i = (int) dv; - const int n_head_kv_i = (int) n_head_kv; - - cl_uint a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset_v)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vt.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_kv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_kv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); - - size_t gws[3] = { (size_t)((dv + 31) / 32) * 32, (size_t)((n_kv + 31) / 32) * 8, (size_t) n_head_kv }; - size_t lws[3] = { 32, 8, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - ggml_tensor_extra_cl extra_vt; - ggml_tensor_extra_cl extra_kq; - ggml_tensor_extra_cl extra_kqv; - ggml_tensor vt; - ggml_tensor kq; - ggml_tensor kqv; - ggml_cl_fa_decompose_scratch_tensor(vt, extra_vt, backend_ctx->prealloc_fa_vt.buffer, GGML_TYPE_F16, n_kv, dv, n_head_kv); - - for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { - const int64_t nqc = MIN(n_q_chunk, n_q - q0); - - // KQ: [dk, n_kv, n_head_kv] x [dk, nqc, n_head] -> [n_kv, nqc, n_head] - ggml_cl_fa_decompose_scratch_tensor(kq, extra_kq, backend_ctx->prealloc_fa_kq.buffer, GGML_TYPE_F32, n_kv, nqc, n_head); - - { - ggml_tensor q_chunk = *q; - q_chunk.ne[1] = nqc; - q_chunk.view_offs = q->view_offs + (size_t) q0 * q->nb[1]; - ggml_cl_mul_mat(backend, k, &q_chunk, &kq); - } - - // softmax in place, the row sums go to prealloc_fa_sums - { - memcpy((float *) kq.op_params + 0, &scale, sizeof(float)); - memcpy((float *) kq.op_params + 1, &max_bias, sizeof(float)); - - ggml_tensor mask_chunk = *mask; - mask_chunk.ne[1] = nqc; - mask_chunk.view_offs = mask->view_offs + (size_t) q0 * mask->nb[1]; - - ggml_cl_fa_decompose_soft_max(backend, &kq, &mask_chunk, sinks, &kq, backend_ctx->prealloc_fa_sums.buffer); - } - - // KQV: [n_kv, dv, n_head_kv] x [n_kv, nqc, n_head] -> [dv, nqc, n_head] - // V^T is contiguous, so mul_mat would not pick the KQV image kernel; call it here. - ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (backend_ctx->kernel_mul_mm_f16_f32_kqv != nullptr && - (dv % 64) == 0 && (n_kv % 16) == 0 && nqc >= 32 && - ((size_t)(vt.nb[2] * n_head_kv / 4) / 4 <= backend_ctx->image_max_buffer_size) && - ((size_t)(dv * nqc * n_head) <= backend_ctx->image_max_buffer_size)) { - ggml_cl_mul_mat_kq_kqv_adreno(backend, &vt, &kq, &kqv, /*is_kq =*/ false); - } else -#endif - { - ggml_cl_mul_mat(backend, &vt, &kq, &kqv); - } - - ggml_cl_fa_decompose_write_chunk(backend, kqv, q0, dst); - } -} - -static void ggml_cl_fa_pv_direct(ggml_backend_t backend, ggml_tensor * dst, int kv_pitch) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const ggml_tensor * q = dst->src[0]; - const ggml_tensor * v = dst->src[2]; - auto * extra_v = (ggml_tensor_extra_cl *) v->extra; - - const int dv = v->ne[0]; - const int n_q = q->ne[1]; - const int n_head = q->ne[2]; - const int n_head_kv = v->ne[2]; - const int gqa = n_head / n_head_kv; - const int nblk = v->ne[1] / 32; - const int d_blocks = dv / 128; - // Split the KV range to give a small query batch about 256 workgroups. - const int want = MAX(1, 256 / (d_blocks * n_head_kv)); - const int blocks_per_split = (nblk + want - 1) / want; - const int n_split = (nblk + blocks_per_split - 1) / blocks_per_split; - const int n_elem = n_head * n_q * dv; - backend_ctx->prealloc_fa_kq.allocate(backend_ctx->context, (size_t) n_split * n_elem * sizeof(float)); - - const cl_ulong off_v = extra_v->offset + v->view_offs; - const cl_ulong v_nb1 = v->nb[1]; - const cl_ulong v_nb2 = v->nb[2]; - { - cl_kernel kernel = backend_ctx->kernel_fa_kqv_direct_f16; - cl_uint a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_v)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &gqa)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nblk)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &blocks_per_split)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); - size_t gws[3] = {(size_t) d_blocks * 64, (size_t) n_head_kv, (size_t) n_split}; - size_t lws[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - { - cl_kernel kernel = backend_ctx->kernel_fa_kqv_direct_reduce; - cl_uint a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_elem)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_split)); - size_t gws[3] = {((size_t) n_elem + 63) / 64 * 64, 1, 1}; - size_t lws[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } -} - -static void ggml_cl_flash_attn_decompose_kq_p8( - ggml_backend_t backend, - const ggml_tensor * q, const ggml_tensor * k, - ggml_tensor * dst, - int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct, bool kq_int8 -) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; - const int64_t n_q = q->ne[1]; - const int64_t n_kv = k->ne[1]; - const int64_t dv = v->ne[0]; - const int64_t n_head = q->ne[2]; - const int64_t n_head_kv = k->ne[2]; - - auto pad_up = [](int64_t x, int64_t a) { return ((x + a - 1) / a) * a; }; - const int64_t kqv_m = pad_up(dv, 64); - const int64_t tile_n = pad_up(n_q_chunk, 32); - - static const int64_t kv_pitch_round = [] { - const char * e = getenv("GGML_OPENCL_FA_KV_PITCH_ROUND"); - const int64_t v = (e && e[0]) ? strtoll(e, nullptr, 10) : 32768; - return v > 0 && v <= INT_MAX && (v & (v - 1)) == 0 ? v : (int64_t) 0; - }(); - static const int64_t kv_pitch_round_min = [] { - const char * e = getenv("GGML_OPENCL_FA_KV_PITCH_ROUND_MIN"); - return (e && e[0]) ? strtoll(e, nullptr, 10) : (int64_t) 16384; - }(); - static const int64_t kv_pitch_round_max_dv = [] { - const char * e = getenv("GGML_OPENCL_FA_KV_PITCH_ROUND_MAX_DV"); - return (e && e[0]) ? strtoll(e, nullptr, 10) : (int64_t) 256; - }(); - - // Round long P and V^T rows to reduce cache conflicts, then add one cache line. - int64_t kv_pitch_value = n_kv + 64; - if (kv_pitch_round > 0 && n_kv > kv_pitch_round_min && dv <= kv_pitch_round_max_dv) { - const int64_t rounded_pitch = pad_up(n_kv, kv_pitch_round) + 64; - if (rounded_pitch <= INT_MAX && - (size_t) rounded_pitch <= SIZE_MAX / n_q_chunk / n_head && - (size_t) rounded_pitch <= SIZE_MAX / dv / n_head_kv) { - kv_pitch_value = rounded_pitch; - } - } - const int kv_pitch = (int) kv_pitch_value; - const size_t nblk = (size_t) kv_pitch / 32; - - backend_ctx->prealloc_fa_pq.allocate(backend_ctx->context, (size_t) kv_pitch * n_q_chunk * n_head); - backend_ctx->prealloc_fa_pd.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); - backend_ctx->prealloc_fa_bmax.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); - backend_ctx->prealloc_fa_bsum.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); - backend_ctx->prealloc_fa_kqv.allocate(backend_ctx->context, (size_t)(kqv_m * tile_n * (n_head + 1)) * sizeof(float)); - backend_ctx->prealloc_fa_sums.allocate(backend_ctx->context, (size_t)(n_q_chunk * n_head) * sizeof(float)); - - // Direct PV reads the original V cache and needs no transposed copy. - if (!kqv_direct) { - backend_ctx->prealloc_fa_vtq.allocate(backend_ctx->context, (size_t) kv_pitch * dv * n_head_kv); - backend_ctx->prealloc_fa_vtd.allocate(backend_ctx->context, nblk * dv * n_head_kv * sizeof(cl_half)); - - ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; - cl_kernel kernel = backend_ctx->kernel_fa_v_transpose_q8; - - const cl_ulong offset_v = extra_v->offset + v->view_offs; - const cl_ulong v_nb1 = v->nb[1]; - const cl_ulong v_nb2 = v->nb[2]; - const cl_ulong v_nb3 = v->nb[3]; - const int n_kv_i = (int) n_kv; - const int dv_i = (int) dv; - const int n_head_kv_i = (int) n_head_kv; - - cl_uint a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset_v)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtd.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_kv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_kv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb3)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); - - size_t gws[3] = { (size_t)((dv + 31) / 32) * 32, (size_t)((n_kv + 31) / 32) * 8, (size_t) n_head_kv }; - size_t lws[3] = { 32, 8, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - if (kq_int8) { - ggml_cl_fa_kq_int8_prepare(backend, dst, n_q_chunk); - } - - ggml_tensor_extra_cl extra_kqv; - ggml_tensor kqv; - - for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { - const int64_t nqc = MIN(n_q_chunk, n_q - q0); - - ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch, kq_int8); - - ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); - - if (kqv_direct) { - GGML_ASSERT(q0 == 0 && nqc == n_q); - ggml_cl_fa_pv_direct(backend, dst, kv_pitch); - } else { - const cl_ulong zero = 0; - const int dv_i = dv; - const int nkv_i = n_kv; - const int nqc_i = nqc; - const int nh_i = n_head; - const int nhkv_i = n_head_kv; - - cl_kernel kernel = backend_ctx->kernel_mul_mm_q8_f32_kqv; - - cl_uint a = 0; - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtd.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nkv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nqc_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nh_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhkv_i)); - CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); - size_t gws[3] = {(size_t)(dv / 64) * 64, (size_t)(n_head / n_head_kv) * ((nqc + 31) / 32), (size_t) n_head_kv}; - size_t lws[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); - } - - ggml_cl_fa_decompose_write_chunk(backend, kqv, q0, dst); - } -} - -// Decomposed flash attention prefill. -// -// On Adreno the fused prefill tile is slow at large head sizes, while the -// KQ / KQV image GEMMs are fast. -fa 0 uses those GEMMs, but it keeps KQ for -// the whole ubatch in the graph. Here the FLASH_ATTN_EXT node stays, and the -// queries are split into chunks. For each chunk: KQ -> softmax -> KQV into -// backend scratch, so the scratch size depends on the chunk and not on the -// ubatch, and the KV cache keeps the flash attention layout. -// -// Returns false when the shape is not supported, then the fused tile runs. -// GGML_OPENCL_FA_DECOMPOSE=0 disables it, =1 enables it for any Adreno GPU and -// head size. GGML_OPENCL_FA_DECOMPOSE_MB sets the KQ scratch budget (default 256). -// GGML_OPENCL_FA_KQ_P8=0 disables U8 probabilities and int8 KQV. -// GGML_OPENCL_FA_KQV_DIRECT=0 disables direct PV for small query batches. -// GGML_OPENCL_FA_KQ_INT8=0 keeps F16 KQ; =1 enables int8 KQ for supported shapes. -static bool ggml_cl_flash_attn_decompose_dispatch( - ggml_backend_t backend, - const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst -) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - - if (backend_ctx->gpu_family != ADRENO) { - return false; - } - - static const int env = []{ - const char * e = getenv("GGML_OPENCL_FA_DECOMPOSE"); - return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; - }(); - - if (env == 0) { - return false; - } - - const int64_t n_q = q->ne[1]; - const int64_t n_kv = k->ne[1]; - const int64_t dk = q->ne[0]; - const int64_t dv = v->ne[0]; - const int64_t n_head = q->ne[2]; - const int64_t n_head_kv = k->ne[2]; - - const bool measured_gen = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E; - - if (n_q < 2) { - return false; - } - if (q->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || - k->type != GGML_TYPE_F16 || v->type != GGML_TYPE_F16) { - return false; - } - if (q->ne[3] != 1 || k->ne[3] != 1 || v->ne[3] != 1 || dst->ne[3] != 1) { - return false; - } - if (n_head_kv <= 0 || n_head < n_head_kv || n_head % n_head_kv != 0) { - return false; - } - if (k->nb[0] != ggml_type_size(k->type) || v->nb[0] != ggml_type_size(v->type)) { - return false; - } - // K and Q must be packed [dk, head, row], as the KV cache and the permuted Q - // are. mul_mat sends the KQ to the image KQ kernel only for this layout; - // other K views can reach the KQV image kernel there and give wrong results. - if (k->nb[2] != (size_t) dk * sizeof(ggml_fp16_t) || k->nb[1] != (size_t) dk * n_head_kv * sizeof(ggml_fp16_t) || - q->nb[0] != sizeof(float) || q->nb[2] != (size_t) dk * sizeof(float) || q->nb[1] != (size_t) dk * n_head * sizeof(float)) { - return false; - } - - // soft_max applies scale, mask, ALiBi and sinks, but not the softcap. - float scale; - float max_bias; - float logit_softcap; - memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float)); - memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); - memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float)); - if (logit_softcap != 0.0f) { - return false; - } - - // The deferred softmax kernel needs an f16 mask and rows that divide by 4. - if (mask == nullptr || mask->type != GGML_TYPE_F16 || mask->ne[0] < n_kv || (n_kv % 4) != 0) { - return false; - } - - const std::pair dk_dv = {(int) dk, (int) dv}; - if (backend_ctx->fa.v_transpose_f16.count(dk_dv) == 0) { - return false; - } - - static const char * p8_env = getenv("GGML_OPENCL_FA_KQ_P8"); - const bool kq_p8 = (!p8_env || p8_env[0] != '0') && measured_gen && - backend_ctx->kernel_mul_mm_f16_f32_kq_p8 != nullptr && - backend_ctx->kernel_mul_mm_q8_f32_kqv != nullptr && - backend_ctx->kernel_fa_v_transpose_q8 != nullptr && - n_kv <= INT_MAX - 64 && k->nb[1] <= INT_MAX && - (n_kv % 64) == 0 && (dk % 16) == 0 && (dv % 64) == 0 && - mask->ne[2] == 1 && mask->ne[3] == 1 && mask->nb[0] == sizeof(ggml_fp16_t) && - (mask->nb[1] % sizeof(ggml_fp16_t)) == 0 && - k->nb[1] * n_kv / 16 <= backend_ctx->image_max_buffer_size; - - // Keep DK64 with attention sinks opt-in until its accuracy is validated. - const bool dk64_ok = kq_p8 && dst->src[4] == nullptr && n_head / n_head_kv >= 2 && - n_kv >= 1024 && n_q <= n_kv / 2; - const int min_dk = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? (dk64_ok ? 64 : 128) : 256; - if (env != 1 && !(measured_gen && dk >= min_dk)) { - return false; - } - - static const char * direct_env = getenv("GGML_OPENCL_FA_KQV_DIRECT"); - const bool kqv_direct = (!direct_env || direct_env[0] != '0') && kq_p8 && - backend_ctx->kernel_fa_kqv_direct_f16 != nullptr && backend_ctx->kernel_fa_kqv_direct_reduce != nullptr && - v->ne[1] == n_kv && v->ne[2] == n_head_kv && - n_q <= 32 / (n_head / n_head_kv) && dv >= 128 && dv <= INT_MAX && (dv % 128) == 0 && - n_head <= INT_MAX / (n_q * dv) && (v->nb[1] % 4) == 0 && (v->nb[2] % 4) == 0; - const bool small_p8 = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && - kq_p8 && dk >= 128 && n_kv >= 1024; - // Small batches without direct PV need P8 and a long KV cache on X2E. - if (n_q < 32 && !kqv_direct && !small_p8) { - return false; - } - - // Chunk size: a byte budget for KQ, at least 8 tiles of 32 queries so the - // GEMMs get usable shapes, and below the image1d_buffer limit of the KQ dst. - static const size_t budget_bytes = []{ - const char * e = getenv("GGML_OPENCL_FA_DECOMPOSE_MB"); - const int mb = (e && e[0]) ? atoi(e) : 256; - return (size_t)(mb > 0 ? mb : 256) * 1024 * 1024; - }(); - - const size_t kq_row_bytes = (size_t) n_kv * n_head * sizeof(float); - int64_t n_q_chunk = MIN((int64_t)(budget_bytes / kq_row_bytes), n_q); - n_q_chunk = MAX(n_q_chunk, MIN((int64_t) 8 * 32, n_q)); - - if (!kq_p8) { - n_q_chunk = MIN(n_q_chunk, (int64_t)(backend_ctx->image_max_buffer_size / (n_kv * n_head))); - } - if (n_q_chunk < 32 && n_q_chunk < n_q) { - return false; - } - - static const int kq_int8_env = [] { - const char * e = getenv("GGML_OPENCL_FA_KQ_INT8"); - return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; - }(); - static const int dk512_env = [] { - const char * e = getenv("GGML_OPENCL_FA_KQ_DK512_F16"); - return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; - }(); - const bool dk512 = dk > 256 && dk <= 512 && n_q >= 32 && - (dk512_env == 1 || (dk512_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E)); - const bool kq_int8_possible = kq_p8 && (dk <= 256 || dk512) && dk % 32 == 0 && - backend_ctx->kernel_fa_q8_rows_f16 != nullptr && backend_ctx->kernel_fa_q8_rows_f32 != nullptr && - n_head <= INT_MAX && n_head_kv <= INT_MAX && - n_q <= INT_MAX / n_head / (dk / 32) && n_kv <= INT_MAX / n_head_kv / (dk / 32) && - (dst->src[4] == nullptr || dk > 64) && - (kq_int8_env == 1 || (kq_int8_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && n_kv >= 2048)) && - backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f16) >= 64 && - backend_ctx->get_kernel_workgroup_size(backend_ctx->kernel_fa_q8_rows_f32) >= 64; - cl_kernel kq_int8_kernel = nullptr; - if (kq_int8_possible) { - kq_int8_kernel = dk <= 256 ? backend_ctx->kernel_mul_mm_q8_kq_p8 : backend_ctx->kernel_mul_mm_q8_kq_p8_dk512; - } - const bool kq_int8 = kq_int8_kernel != nullptr && backend_ctx->get_kernel_workgroup_size(kq_int8_kernel) >= 64; - - // Fewer query tiles per KV block reduce cache pressure in the int8 KQ kernel. - static const int64_t kq_int8_max_chunk = [] { - const char * e = getenv("GGML_OPENCL_FA_KQ_INT8_MAX_CHUNK"); - const int v = (e && e[0]) ? atoi(e) : 96; - return (int64_t) (v >= 32 ? (v / 32) * 32 : 96); - }(); - if (kq_int8) { - n_q_chunk = MIN(n_q_chunk, kq_int8_max_chunk); - } - - // even out the chunks, then align to the 32-wide n-tile - const int64_t n_chunks = (n_q + n_q_chunk - 1) / n_q_chunk; - n_q_chunk = MIN(n_q_chunk, ((n_q + n_chunks - 1) / n_chunks + 31) & ~(int64_t) 31); - - if (kq_p8) { - ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct, kq_int8); - } else { - ggml_cl_flash_attn_decompose(backend, q, k, dst, n_q_chunk, scale, max_bias); - } - return true; -} - -static void ggml_cl_flash_attn(ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst) { - const ggml_tensor * v = dst->src[2]; - const ggml_tensor * mask = dst->src[3]; - const ggml_tensor * sinks = dst->src[4]; - - GGML_ASSERT(q->extra); - GGML_ASSERT(k->extra); - GGML_ASSERT(v->extra); - GGML_ASSERT(dst->extra); - - if (mask) { - GGML_ASSERT(mask->extra); - } - if (sinks) { - GGML_ASSERT(sinks->extra); - } - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - const int n_q = q->ne[1]; - const int n_kv = k->ne[1]; - const int d_head_q = q->ne[0]; - const int d_head_v = v->ne[0]; - const int n_head = q->ne[2]; - const int n_head_kv = k->ne[2]; - const int n_batch = q->ne[3]; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (ggml_cl_adreno_xmem_attn_can_use(backend_ctx, q, k, dst)) { - ggml_cl_adreno_xmem_attn_run(backend, q, k, dst); - return; - } -#endif - - // Compile DK512 decode separately from the prefill programs. - const bool fa_decode_only_512 = (d_head_q == 512); - - // per-variant lazy compile for this (dk, dv) - // DK=512 decode (n_q==1) needs no prepass - // DK=512 prefill (n_q>1) does, so compile it only when needed - if (!fa_decode_only_512 || n_q > 1) { - ggml_opencl_ensure_fa_pre_kernels(backend_ctx, d_head_q, d_head_v); - } - - cl_kernel kernel = NULL; - bool use_prefill_k_img = false; // K is image1d_buffer_t for DK=512 prefill - - const bool is_f16 = q->type == GGML_TYPE_F16; - const bool is_mixed = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16; - const bool is_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0; - const bool is_q4_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q4_0 && v->type == GGML_TYPE_Q4_0; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_fa_bin_kernels_prefill(backend_ctx, q, k, v)) { - // We support the prefill path of flash attn with a specialized d_head = 64/128/256 - ggml_cl_flash_attn_prefill_bin(backend, q, k, dst); - return; - } -#endif - - if (is_f16) { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F16); - } else if (is_mixed) { - if (fa_decode_only_512 && n_q == 1) { - GGML_ASSERT(ggml_opencl_ensure_fa_f32_f16_vec_512(backend_ctx)); - } else { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F32_F16); - } - if (fa_decode_only_512) { - // DK=512: the BM-tile prefill kernels are specifically compiled from - // FA_PREFILL_ONLY - if (n_q > 1) { - ggml_opencl_ensure_fa_f32_f16_prefill_512(backend_ctx, /*split=*/false); - ggml_opencl_ensure_fa_f32_f16_prefill_512(backend_ctx, /*split=*/true); - } - } else { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F32_F16_SPLIT); - } - } else if (is_q8_0) { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q8_0); - if (d_head_q == 96 && d_head_v == 96) { - ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 96, 96, /*quant_bm=*/16, /*quant_n_split=*/3, /*is_q8_0=*/true); - } else if (d_head_q == 256 && d_head_v == 256) { - ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 256, 256, /*quant_bm=*/16, /*quant_n_split=*/8, /*is_q8_0=*/true); - } else { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q8_0_SPLIT); - } - } else if (is_q4_0) { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q4_0); - if (d_head_q == 96 && d_head_v == 96) { - ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 96, 96, /*quant_bm=*/16, /*quant_n_split=*/3, /*is_q8_0=*/false); - } else if (d_head_q == 256 && d_head_v == 256) { - ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 256, 256, /*quant_bm=*/16, /*quant_n_split=*/8, /*is_q8_0=*/false); - } else { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q4_0_SPLIT); - } - } else { - ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F32); - } - - const std::pair dk_dv = {d_head_q, d_head_v}; - const int mq_gqa = n_head_kv > 0 ? n_head / n_head_kv : 0; - const std::tuple mq_decode_key = {d_head_q, d_head_v, mq_gqa}; - // X2E also takes GQA 2 and 6 at head size 256 (gemma-4 SWA layers, Qwen3.5-27B), - // GQA 16 at 512 and 128 (gemma-4-12b global layers, muse-glimmer) and GQA 2 at 512 (gemma-4-E4B MTP drafter) - const bool mq_decode_x2e = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && - ((d_head_q == 256 && (mq_gqa == 2 || mq_gqa == 6)) || - (d_head_q == 512 && (mq_gqa == 2 || mq_gqa == 16)) || - (d_head_q == 128 && mq_gqa == 16 && backend_ctx->has_subgroup_shuffle)); - const bool mq_decode_kernel = backend_ctx->gpu_family == ADRENO && is_mixed && - d_head_q == d_head_v && n_head_kv > 0 && n_head % n_head_kv == 0 && - ((((d_head_q == 64 && mq_gqa == 8) || (d_head_q == 128 && mq_gqa == 4)) && - backend_ctx->has_subgroup_shuffle) || - ((d_head_q == 256 || d_head_q == 512) && (mq_gqa == 4 || mq_gqa == 8)) || - mq_decode_x2e); - const bool mq_decode_shape = mq_decode_kernel && n_q == 1; - // compile on the first call for this shape (the warmup is a prefill), not on the first decode - if (mq_decode_kernel) { - ggml_opencl_ensure_fa_f32_f16_mq_decode(backend_ctx, d_head_q, d_head_v, mq_gqa); - } - - // after all lazy compiles, so the decode kernels are built during warmup as on the fused path - if (n_q > 1 && ggml_cl_flash_attn_decompose_dispatch(backend, q, k, dst)) { - return; - } - - const bool use_native_q8_0_q1 = is_q8_0 && n_q == 1 && - backend_ctx->fa.f32_q8_0_q1.count(dk_dv) > 0; - // Native q8_0 prefill — reads q8_0 directly, wg_size = cfg->bm. - const bool use_native_q8_0 = is_q8_0 && n_q > 1 && - backend_ctx->fa.f32_q8_0.count(dk_dv) > 0; - const bool use_native_q4_0_q1 = is_q4_0 && n_q == 1 && - backend_ctx->fa.f32_q4_0_q1.count(dk_dv) > 0; - const bool use_native_q4_0 = is_q4_0 && n_q > 1 && - backend_ctx->fa.f32_q4_0.count(dk_dv) > 0; - const int block_m = n_q > 1 - ? (is_mixed ? backend_ctx->fa.f32_f16_bm.at(dk_dv) : backend_ctx->fa.bm.at(dk_dv)) - : 0; - // block_n is only used by the n_q > 1 prefill path; its map is not - // populated for DK=512 decode, so do not read it for decode. - const int block_n = (n_q > 1) - ? (is_mixed ? backend_ctx->fa.f32_f16_bn.at(dk_dv) - : backend_ctx->fa.bn.at(dk_dv)) - : 0; - // Pick split variant only when n_kv crosses the per-(dk,dv) threshold. - // the N_SPLIT>1 prefill tile reduces DK partials via subgroup shuffle, - // on Intel it uses the non-split BM tile and does not depend on subgroup size - const bool use_split_kernel = (n_q > 1 && is_mixed && - backend_ctx->gpu_family != INTEL && - backend_ctx->fa.f32_f16_split.count(dk_dv) > 0 && - n_kv >= backend_ctx->fa.f32_f16_split_nkv_threshold.at(dk_dv)); - const bool use_split_q8_0 = (use_native_q8_0 && backend_ctx->gpu_family != INTEL && - backend_ctx->fa.f32_q8_0_split.count(dk_dv) > 0 && - n_kv >= backend_ctx->fa.f32_q8_0_split_nkv_threshold.at(dk_dv)); - const bool use_split_q4_0 = (use_native_q4_0 && backend_ctx->gpu_family != INTEL && - backend_ctx->fa.f32_q4_0_split.count(dk_dv) > 0 && - n_kv >= backend_ctx->fa.f32_q4_0_split_nkv_threshold.at(dk_dv)); - const int wg_size_fa = (n_q > 1 && is_mixed) - ? (use_split_kernel - ? backend_ctx->fa.f32_f16_split_wg_size.at(dk_dv) - : backend_ctx->fa.f32_f16_wg_size.at(dk_dv)) - : block_m; - - ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *)q->extra; - ggml_tensor_extra_cl * extra_o = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl * extra_mask = mask ? (ggml_tensor_extra_cl *)mask->extra : NULL; - ggml_tensor_extra_cl * extra_sinks = sinks ? (ggml_tensor_extra_cl *)sinks->extra : NULL; - - // SoA q8_0/q4_0 K/V: data_device aliases the `q` subbuffer; reconstruct - // AoS into a temp buffer below. AoS tensors use extra_k/v->data_device. - const bool k_soa = ggml_cl_is_q8_0_soa(k) || ggml_cl_is_q4_0_soa(k); - const bool v_soa = ggml_cl_is_q8_0_soa(v) || ggml_cl_is_q4_0_soa(v); - ggml_tensor_extra_cl * extra_k = k_soa ? nullptr : (ggml_tensor_extra_cl *)k->extra; - ggml_tensor_extra_cl * extra_v = v_soa ? nullptr : (ggml_tensor_extra_cl *)v->extra; - - cl_ulong offset_q = extra_q->offset + q->view_offs; - cl_ulong offset_k = k_soa ? 0 : extra_k->offset + k->view_offs; - cl_ulong offset_v = v_soa ? 0 : extra_v->offset + v->view_offs; - cl_ulong offset_o = extra_o->offset + dst->view_offs; - cl_mem mask_buffer = extra_mask ? extra_mask->data_device : NULL; - cl_ulong offset_mask = extra_mask ? extra_mask->offset + mask->view_offs : 0; - cl_mem sinks_buffer = extra_sinks ? extra_sinks->data_device : NULL; - cl_ulong offset_sinks = extra_sinks ? extra_sinks->offset + sinks->view_offs : 0; - - const cl_ulong q_nb1 = q->nb[1]; - const cl_ulong q_nb2 = q->nb[2]; - const cl_ulong q_nb3 = q->nb[3]; - - cl_ulong k_nb1 = k->nb[1]; - cl_ulong k_nb2 = k->nb[2]; - cl_ulong k_nb3 = k->nb[3]; - - cl_ulong v_nb1 = v->nb[1]; - cl_ulong v_nb2 = v->nb[2]; - cl_ulong v_nb3 = v->nb[3]; - - const cl_ulong o_nb1 = dst->nb[1]; - const cl_ulong o_nb2 = dst->nb[2]; - const cl_ulong o_nb3 = dst->nb[3]; - - const cl_ulong mask_nb1 = mask ? mask->nb[1] : 0; - const cl_ulong mask_nb2 = mask ? mask->nb[2] : 0; - const cl_ulong mask_nb3 = mask ? mask->nb[3] : 0; - const int mask_ne2 = mask ? mask->ne[2] : 0; - const int mask_ne3 = mask ? mask->ne[3] : 0; - - float scale; - float max_bias; - float logit_softcap; - - const float * params = (const float *)dst->op_params; - scale = params[0]; - max_bias = params[1]; - logit_softcap = params[2]; - - bool use_q1_vec = false; - bool use_q1_vec_mq = false; - bool use_local_tile = false; - // KV-head-coalesced gate: gqa_ratio == compile-time MQ_GQA - // restricts to DK=DV=256 for now due to local memory size - const int gqa_ratio_dispatch = n_head_kv > 0 ? (n_head / n_head_kv) : 0; - if (n_q == 1) { - if (use_native_q8_0_q1) { - if (d_head_v >= 256 && - backend_ctx->fa.f32_q8_0_q1_vec.count(dk_dv) > 0) { - kernel = backend_ctx->fa.f32_q8_0_q1_vec.at(dk_dv); - use_q1_vec = true; - } else { - kernel = backend_ctx->fa.f32_q8_0_q1.at(dk_dv); - } - } else if (use_native_q4_0_q1) { - // q4_0 vec kernel uses per-lane dp4a (cl_khr_integer_dot_product) - const char * q4vec_env = getenv("GGML_OPENCL_FA_Q4_VEC"); - const bool q4vec_off = (q4vec_env != NULL) && (q4vec_env[0] == '0'); - if (!q4vec_off && d_head_v >= 256 && - backend_ctx->fa.f32_q4_0_q1_vec.count(dk_dv) > 0) { - kernel = backend_ctx->fa.f32_q4_0_q1_vec.at(dk_dv); - use_q1_vec = true; - } else { - kernel = backend_ctx->fa.f32_q4_0_q1.at(dk_dv); - } - } else if (is_mixed) { - static const char * lt_env = getenv("GGML_OPENCL_FA_LOCAL_TILE"); - static const bool lt_on = (lt_env != NULL) && (lt_env[0] != '0'); - if (lt_on && d_head_q == 128 && d_head_v == 128 && - backend_ctx->fa.f32_f16_q1_local_tile.count(dk_dv) > 0) { - kernel = backend_ctx->fa.f32_f16_q1_local_tile.at(dk_dv); - use_local_tile = true; - } else { - static const char * f16_vec_dk128_env = getenv("GGML_OPENCL_FA_F16_VEC_DK128"); - static const bool f16_vec_dk128_off = (f16_vec_dk128_env != NULL) && (f16_vec_dk128_env[0] == '0'); - const int dv_gate = f16_vec_dk128_off ? 256 : 128; - if (d_head_v >= dv_gate && - backend_ctx->fa.f32_f16_q1_vec.count(dk_dv) > 0) { - kernel = backend_ctx->fa.f32_f16_q1_vec.at(dk_dv); - use_q1_vec = true; - } else { - kernel = backend_ctx->fa.f32_f16_q1.at(dk_dv); - } - } - } else if (is_f16) { - kernel = backend_ctx->fa.f16_q1.at(dk_dv); - } else { - kernel = backend_ctx->fa.f32_q1.at(dk_dv); - } - } else { - if (use_native_q8_0) { - kernel = use_split_q8_0 - ? backend_ctx->fa.f32_q8_0_split.at(dk_dv) - : backend_ctx->fa.f32_q8_0.at(dk_dv); - } else if (use_native_q4_0) { - kernel = use_split_q4_0 - ? backend_ctx->fa.f32_q4_0_split.at(dk_dv) - : backend_ctx->fa.f32_q4_0.at(dk_dv); - } else if (is_mixed) { - if (use_split_kernel) { - // DK=512 prefill: opt-in texture-cache K reads (image1d_buffer_t). - static const char * pkimg_env = getenv("GGML_OPENCL_FA_PREFILL_K_IMG"); - const bool pkimg_on = (pkimg_env != NULL) && (pkimg_env[0] != '0'); - if (d_head_q == 512 && pkimg_on && - backend_ctx->fa.f32_f16_split_k_img.count(dk_dv) > 0) { - kernel = backend_ctx->fa.f32_f16_split_k_img.at(dk_dv); - use_prefill_k_img = true; - } else { - kernel = backend_ctx->fa.f32_f16_split.at(dk_dv); - } - } else { - kernel = backend_ctx->fa.f32_f16.at(dk_dv); - } - } else if (is_f16) { - kernel = backend_ctx->fa.f16.at(dk_dv); - } else { - kernel = backend_ctx->fa.f32.at(dk_dv); - } - } - - // Intel goes to the basic q1 kernel - if (backend_ctx->gpu_family == INTEL && n_q == 1) { - use_q1_vec = use_q1_vec_mq = use_local_tile = false; - if (is_mixed && backend_ctx->fa.f32_f16_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_f16_q1.at(dk_dv); } - else if (is_f16 && backend_ctx->fa.f16_q1.count(dk_dv)) { kernel = backend_ctx->fa.f16_q1.at(dk_dv); } - else if (is_q8_0 && backend_ctx->fa.f32_q8_0_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_q8_0_q1.at(dk_dv); } - else if (is_q4_0 && backend_ctx->fa.f32_q4_0_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_q4_0_q1.at(dk_dv); } - else if (backend_ctx->fa.f32_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_q1.at(dk_dv); } - } - GGML_ASSERT(kernel != NULL); - - ggml_cl_flash_attn_temp_buffer temp_k; - ggml_cl_flash_attn_temp_buffer temp_v; - ggml_cl_flash_attn_temp_buffer temp_k_pad; - ggml_cl_flash_attn_temp_buffer temp_v_pad; - ggml_cl_flash_attn_temp_buffer temp_mask_pad; - ggml_cl_flash_attn_temp_buffer temp_blk; - const ggml_type kv_target_type = is_f16 ? GGML_TYPE_F16 : GGML_TYPE_F32; - - cl_mem k_data_device = k_soa ? NULL : extra_k->data_device; - cl_mem v_data_device = v_soa ? NULL : extra_v->data_device; - - // SoA q8_0/q4_0 -> reconstruct AoS for downstream kernels that expect - // tight records (no-op when k/v is already AoS). - ggml_cl_flash_attn_temp_buffer temp_k_aos; - ggml_cl_flash_attn_temp_buffer temp_v_aos; - ggml_cl_flash_attn_reconstruct_aos(backend_ctx, k, temp_k_aos, - k_data_device, offset_k, k_nb1, k_nb2, k_nb3); - ggml_cl_flash_attn_reconstruct_aos(backend_ctx, v, temp_v_aos, - v_data_device, offset_v, v_nb1, v_nb2, v_nb3); - - // currently FA kernels support KV cache with f16, f32, q4_0 and q8_0. - // there two cases that these kernels cannot cover, - // 1. KV cache types are q4_0 or q8_0, but the FA kernels fail to compile - // 2. KV cache types not currently supported by an FA kernel, e.g., q4_1 - // these two cases are supported here by dequantizing to f32/f16 and this - // causes performance degradation. - // For q4_0 or q8_0 cases that fail kernel compilation, dequant happens in GPU; - // for types that do not have FA kernels, dequant happens on host. - if (!use_native_q8_0_q1 && !use_native_q8_0 && - !use_native_q4_0_q1 && !use_native_q4_0) { - // for q4_0, q8_0 FA kernels that fail to compile - bool k_done = false; - bool v_done = false; - if (k->type == GGML_TYPE_Q8_0 || k->type == GGML_TYPE_Q4_0) { - k_done = ggml_cl_flash_attn_dequant_kv_gpu( - backend_ctx, k, kv_target_type, k_data_device, offset_k, k_nb1, k_nb2, k_nb3, - temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); - } - if (v->type == GGML_TYPE_Q8_0 || v->type == GGML_TYPE_Q4_0) { - v_done = ggml_cl_flash_attn_dequant_kv_gpu( - backend_ctx, v, kv_target_type, v_data_device, offset_v, v_nb1, v_nb2, v_nb3, - temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); - } - if (!k_done) { - ggml_cl_flash_attn_prepare_quantized_tensor( - backend_ctx, k, kv_target_type, temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); - } - if (!v_done) { - ggml_cl_flash_attn_prepare_quantized_tensor( - backend_ctx, v, kv_target_type, temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); - } - // Asymmetric KV on the F32 fallback path: convert the F16 side to F32 - // too. (Symmetric F16 / mixed paths handle F16 directly.) - if (kv_target_type == GGML_TYPE_F32 && !is_mixed && !is_f16) { - ggml_cl_flash_attn_convert_f16_to_f32(backend_ctx, k, temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); - ggml_cl_flash_attn_convert_f16_to_f32(backend_ctx, v, temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); - } - } - - cl_mem k_pad_buffer = NULL; - cl_mem v_pad_buffer = NULL; - cl_mem mask_pad_buffer = NULL; - cl_mem blk_buffer = NULL; - cl_ulong mask_pad_nb1 = 0; - cl_ulong mask_pad_nb2 = 0; - cl_ulong mask_pad_nb3 = 0; - - // Flash-Decoding K-split decision. Resolved here, before the prefill - // prepass, because KV-pad and blk prepass are pure overhead when FD fires. - // Do not infer causality from tensor shapes: a NULL mask means full - // (bidirectional) attention, e.g. ViT encoders, where n_q == n_kv as well. - // Causal attention in llama.cpp always comes with an explicit KQ mask. - // Inferring is_causal here corrupted mmproj output on OpenCL (see #23800). - const int is_causal = 0; - const int fd_max_n_q = (d_head_q <= FD_MAX_DK_MULTI) ? FD_MAX_N_Q_MULTI : 1; - cl_kernel fd_k_split = NULL; - bool use_fd_mq = false; - bool use_fd_mq_decode = false; - int fd_head_sub = 1; - size_t fd_mq_wg = 256; // MQ_GQA=4 kernel: Q1_WG_SIZE(64) * MQ_NSG_SPLIT(4) - bool use_fa_k_img = false; // K bound as image1d_buffer_t instead of (buf, offset) - - { - const char * mq_env = getenv("GGML_OPENCL_FA_MQ"); - const bool mq_enabled = (mq_env == NULL) ? true : (mq_env[0] != '0'); - const bool mq_kv_ok = is_mixed || is_q8_0 || is_q4_0; - - const char * lmq_env = getenv("GGML_OPENCL_FA_LOCAL_MQ_SPLIT"); - const bool lmq_on = (lmq_env != NULL) && (lmq_env[0] != '0'); - - static const char * vec_nq_env = getenv("GGML_OPENCL_FA_VEC_NQ"); - static const int N_MAX_VEC_NQ = (vec_nq_env != NULL && vec_nq_env[0] != '\0') - ? atoi(vec_nq_env) : 1; - - const bool nq_in_vec_range = (n_q >= 1) && (n_q <= N_MAX_VEC_NQ); - const bool nq1_only = (n_q == 1); - - // Cluster-parallel decode default on for Adreno X2E/X1E - static const int c8_env_state = []{ - const char * e = getenv("GGML_OPENCL_FA_C8"); - if (e == NULL || e[0] == '\0') { return -1; } - return (e[0] != '0') ? 1 : 0; - }(); - const bool c8_default_on = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || - backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E; - const bool c8_f16_on = (c8_env_state >= 0) ? (c8_env_state == 1) : c8_default_on; - // Quant-KV (q4_0/q8_0) GQA4 c8: default-on X2E + X1E - const bool c8_quant_on = (c8_env_state >= 0) ? (c8_env_state == 1) : c8_default_on; - if (mq_enabled && mq_kv_ok && nq_in_vec_range && !is_causal && - backend_ctx->gpu_family != INTEL && - !use_local_tile && - n_kv >= (mq_decode_shape ? 32 : FD_MIN_N_KV) && - backend_ctx->fa.f32_merge.count(dk_dv) > 0) { - if (mq_decode_shape && backend_ctx->fa.f32_f16_mq_decode.count(mq_decode_key) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_mq_decode.at(mq_decode_key); - fd_mq_wg = backend_ctx->fa.f32_f16_mq_decode_wg.at(mq_decode_key); - fd_head_sub = backend_ctx->fa.f32_f16_mq_decode_hs.at(mq_decode_key); - use_fd_mq = true; - use_fd_mq_decode = true; - } else if (nq1_only && lmq_on && is_mixed && d_head_q == 128 && d_head_v == 128 && - gqa_ratio_dispatch == 8 && - backend_ctx->fa.f32_f16_q1_local_mq_split_g8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_local_mq_split_g8.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 64; - } else if (nq1_only && lmq_on && is_mixed && d_head_q == 128 && d_head_v == 128 && - gqa_ratio_dispatch == 4 && - backend_ctx->fa.f32_f16_q1_local_mq_split.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_local_mq_split.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 64; - } else if (nq1_only && is_mixed && gqa_ratio_dispatch == 4 && - ((d_head_q == 256 && d_head_v == 256) || - (d_head_q == 128 && d_head_v == 128)) && - backend_ctx->fa.f32_f16_q1_vec_mq_split.count(dk_dv) > 0) { - const bool k_img_on = d_head_q == 128 && d_head_v == 128 && - getenv("GGML_OPENCL_FA_K_IMG") != NULL && - getenv("GGML_OPENCL_FA_K_IMG")[0] != '0' && - backend_ctx->fa.f32_f16_q1_vec_mq_split_k_img.count(dk_dv) > 0; - // Cluster-parallel decode - const bool c8_env = d_head_q == 128 && d_head_v == 128 && c8_f16_on; - if (c8_env && backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.at(dk_dv); - use_fd_mq = true; - } else if (c8_env && backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 128; - } else if (k_img_on) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_k_img.at(dk_dv); - use_fd_mq = true; - use_fa_k_img = true; - } else { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split.at(dk_dv); - use_fd_mq = true; - } - // Cluster-parallel decode, DK=DV=256 GQA=8 - } else if (nq1_only && is_mixed && gqa_ratio_dispatch == 8 && - d_head_q == 256 && d_head_v == 256 && - c8_env_state == 1 && - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c32.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c32.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 128; - // Cluster-parallel decode for the g8 - } else if (is_mixed && gqa_ratio_dispatch == 8 && - d_head_q == 128 && d_head_v == 128 && - c8_f16_on && - (backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.count(dk_dv) > 0 || - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8_ns2.count(dk_dv) > 0)) { - if (backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.at(dk_dv); - fd_mq_wg = 192; - } else { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8_ns2.at(dk_dv); - fd_mq_wg = 128; - } - use_fd_mq = true; - } else if (is_mixed && gqa_ratio_dispatch == 8 && - d_head_q == 128 && d_head_v == 128 && - getenv("GGML_OPENCL_FA_K_IMG") != NULL && - getenv("GGML_OPENCL_FA_K_IMG")[0] != '0' && - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_k_img.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_k_img.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 192; - use_fa_k_img = true; - } else if (is_mixed && gqa_ratio_dispatch == 8 && - d_head_q == 128 && d_head_v == 128 && - backend_ctx->fa.f32_f16_q1_vec_mq_split_g8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 192; - } else if (nq1_only && is_q8_0 && gqa_ratio_dispatch == 8 && - d_head_q == 128 && d_head_v == 128 && - backend_ctx->fa.f32_q8_0_q1_vec_mq_split_g8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_q8_0_q1_vec_mq_split_g8.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 192; - } else if (nq1_only && is_q8_0 && gqa_ratio_dispatch == 4 && - d_head_q == 128 && d_head_v == 128 && - backend_ctx->fa.f32_q8_0_q1_vec_mq_split.count(dk_dv) > 0) { - // Cluster-parallel q8_0 GQA4 - if (c8_quant_on && - backend_ctx->fa.f32_q8_0_q1_vec_mq_split_c8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_q8_0_q1_vec_mq_split_c8.at(dk_dv); - fd_mq_wg = 128; - } else { - fd_k_split = backend_ctx->fa.f32_q8_0_q1_vec_mq_split.at(dk_dv); - } - use_fd_mq = true; - } else if (nq1_only && is_q4_0) { - const char * q4_mq_env = getenv("GGML_OPENCL_FA_Q4_MQ"); - const bool q4_mq_on = (q4_mq_env != NULL) && (q4_mq_env[0] != '0'); - // Cluster-parallel q4_0 - const bool q4_c8_on = c8_env_state == 1 && - backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8_c8.count(dk_dv) > 0; - if (q4_c8_on && gqa_ratio_dispatch == 8 && - d_head_q == 64 && d_head_v == 64) { - fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8_c8.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 128; - } else if (q4_mq_on && gqa_ratio_dispatch == 8 && - d_head_q == 128 && d_head_v == 128 && - backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 192; - } else if (gqa_ratio_dispatch == 4 && - d_head_q == 128 && d_head_v == 128 && - backend_ctx->fa.f32_q4_0_q1_vec_mq_split.count(dk_dv) > 0) { - // Cluster-parallel q4_0 GQA4 - if (c8_quant_on && - backend_ctx->fa.f32_q4_0_q1_vec_mq_split_c8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split_c8.at(dk_dv); - fd_mq_wg = 128; - } else { - fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split.at(dk_dv); - } - use_fd_mq = true; - } - } - } - } - // Intel cluster-parallel decode FA - if (fd_k_split == NULL && backend_ctx->gpu_family == INTEL && n_q == 1 && !is_causal && - is_mixed && gqa_ratio_dispatch == 4 && d_head_q == 128 && d_head_v == 128 && - n_kv >= FD_MIN_N_KV && - getenv("GGML_OPENCL_FA_C8") != NULL && getenv("GGML_OPENCL_FA_C8")[0] != '0' && - backend_ctx->fa.f32_merge.count(dk_dv) > 0) { - if (backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 128; - } else if (backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.at(dk_dv); - use_fd_mq = true; - fd_mq_wg = 64; - } - } - if (fd_k_split == NULL && - n_q >= 1 && n_q <= fd_max_n_q && n_kv >= FD_MIN_N_KV && !is_causal && - d_head_q <= FD_MAX_DK && - backend_ctx->fa.f32_merge.count(dk_dv) > 0) { - if (is_mixed && backend_ctx->fa.f32_f16_q1_split.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_f16_q1_split.at(dk_dv); - } else if (is_q8_0 && backend_ctx->fa.f32_q8_0_q1_split.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_q8_0_q1_split.at(dk_dv); - } else if (is_q4_0 && backend_ctx->fa.f32_q4_0_q1_split.count(dk_dv) > 0) { - fd_k_split = backend_ctx->fa.f32_q4_0_q1_split.at(dk_dv); - } - } - const bool use_fd = (fd_k_split != NULL); - - const int n_q_blocks = n_q > 1 ? (n_q + block_m - 1) / block_m : 0; - const int n_kv_blocks = (n_kv > 0 && block_n > 0) ? (n_kv + block_n - 1) / block_n : 0; - // KV pad + blk prepass are pure overhead when FD will fire — skip them. - const bool use_mixed_prepass = is_mixed && n_q > 1 && !use_fd; - // make sure prepass kernels are compiled - const bool have_kv_pad = backend_ctx->fa.kv_pad_f16.count(dk_dv) > 0; - const bool have_blk = backend_ctx->fa.blk_f16.count(dk_dv) > 0; - const bool use_kv_pad = use_mixed_prepass && (n_kv % block_n != 0) && have_kv_pad; - // blk prepass: per-KV-tile mask class (0=masked, 1=mixed, 2=unmasked). - // Consumed identically by f32_f16, q8_0 and q4_0 prefill kernels. - const bool use_quant_prepass = (use_native_q8_0 || use_native_q4_0) && !use_fd; - const bool use_blk_mask = (use_mixed_prepass || use_quant_prepass) && mask_buffer != NULL && have_blk; - - if (use_kv_pad) { - cl_int err; - - const size_t k_pad_size = (size_t) k_nb1 * (size_t) block_n * (size_t) n_head_kv * (size_t) n_batch; - temp_k_pad.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, k_pad_size, NULL, &err); - CL_CHECK(err); - k_pad_buffer = temp_k_pad.data; - - const size_t v_pad_size = (size_t) v_nb1 * (size_t) block_n * (size_t) n_head_kv * (size_t) n_batch; - temp_v_pad.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, v_pad_size, NULL, &err); - CL_CHECK(err); - v_pad_buffer = temp_v_pad.data; - - cl_kernel kernel_kv_pad = backend_ctx->fa.kv_pad_f16.at(dk_dv); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 0, sizeof(cl_mem), &k_data_device)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 1, sizeof(cl_ulong), &offset_k)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 2, sizeof(cl_mem), &v_data_device)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 3, sizeof(cl_ulong), &offset_v)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 4, sizeof(cl_mem), &k_pad_buffer)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 5, sizeof(cl_mem), &v_pad_buffer)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 6, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 7, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 8, sizeof(int), &n_batch)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 9, sizeof(cl_ulong), &k_nb1)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 10, sizeof(cl_ulong), &k_nb2)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 11, sizeof(cl_ulong), &k_nb3)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 12, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 13, sizeof(cl_ulong), &v_nb2)); - CL_CHECK(clSetKernelArg(kernel_kv_pad, 14, sizeof(cl_ulong), &v_nb3)); - - size_t global_work_size[] = { (size_t) block_n, (size_t) n_head_kv, (size_t) n_batch }; - backend_ctx->enqueue_ndrange_kernel(kernel_kv_pad, 3, global_work_size, NULL, dst); - - if (mask_buffer != NULL) { - mask_pad_nb1 = (cl_ulong) block_n * (cl_ulong) sizeof(ggml_fp16_t); - mask_pad_nb2 = (cl_ulong) n_q * mask_pad_nb1; - mask_pad_nb3 = (cl_ulong) mask_ne2 * mask_pad_nb2; - - const size_t mask_pad_size = (size_t) mask_ne3 * (size_t) mask_pad_nb3; - temp_mask_pad.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, mask_pad_size, NULL, &err); - CL_CHECK(err); - mask_pad_buffer = temp_mask_pad.data; - - cl_kernel kernel_mask_pad = backend_ctx->fa.mask_pad_f16.at(dk_dv); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 0, sizeof(cl_mem), &mask_buffer)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 1, sizeof(cl_ulong), &offset_mask)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 2, sizeof(cl_mem), &mask_pad_buffer)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 3, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 4, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 5, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 6, sizeof(cl_ulong), &mask_nb2)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 7, sizeof(cl_ulong), &mask_nb3)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 8, sizeof(int), &mask_ne2)); - CL_CHECK(clSetKernelArg(kernel_mask_pad, 9, sizeof(int), &mask_ne3)); - - size_t global_work_size_mask[] = { (size_t) block_n, (size_t) n_q, (size_t) (mask_ne2 * mask_ne3) }; - backend_ctx->enqueue_ndrange_kernel(kernel_mask_pad, 3, global_work_size_mask, NULL, dst); - } - } - - if (use_blk_mask) { - cl_int err; - const size_t blk_size = (size_t) n_kv_blocks * (size_t) n_q_blocks * (size_t) mask_ne2 * (size_t) mask_ne3; - temp_blk.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, blk_size, NULL, &err); - if (err != CL_SUCCESS) { - // Flush before retry — reclaim deferred driver deallocations. - CL_CHECK(clFinish(backend_ctx->queue)); - temp_blk.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, blk_size, NULL, &err); - } - CL_CHECK(err); - blk_buffer = temp_blk.data; - - cl_kernel kernel_blk = backend_ctx->fa.blk_f16.at(dk_dv); - CL_CHECK(clSetKernelArg(kernel_blk, 0, sizeof(cl_mem), &mask_buffer)); - CL_CHECK(clSetKernelArg(kernel_blk, 1, sizeof(cl_ulong), &offset_mask)); - CL_CHECK(clSetKernelArg(kernel_blk, 2, sizeof(cl_mem), &blk_buffer)); - CL_CHECK(clSetKernelArg(kernel_blk, 3, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel_blk, 4, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel_blk, 5, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel_blk, 6, sizeof(cl_ulong), &mask_nb2)); - CL_CHECK(clSetKernelArg(kernel_blk, 7, sizeof(cl_ulong), &mask_nb3)); - CL_CHECK(clSetKernelArg(kernel_blk, 8, sizeof(int), &mask_ne2)); - CL_CHECK(clSetKernelArg(kernel_blk, 9, sizeof(int), &mask_ne3)); - - size_t global_work_size_blk[] = { (size_t) n_kv_blocks, (size_t) n_q_blocks, (size_t) (mask_ne2 * mask_ne3) }; - backend_ctx->enqueue_ndrange_kernel(kernel_blk, 3, global_work_size_blk, NULL, dst); - } - - const int n_head_log2_val = n_head > 0 ? 1u << (int)floorf(log2f((float)n_head)) : 0; - const float n_head_log2_f = n_head_log2_val > 0 ? (float)n_head_log2_val : 1.0f; - const float m0 = powf(2.0f, -(max_bias) / n_head_log2_f); - const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2_f); - - if (use_fd) { - static const int fd_env_kv_per_split = []{ - const char * e = getenv("GGML_OPENCL_FD_KV_PER_SPLIT"); - return (e && e[0]) ? atoi(e) : 0; - }(); - static const int fd_env_max_splits = []{ - const char * e = getenv("GGML_OPENCL_FD_MAX_SPLITS"); - return (e && e[0]) ? atoi(e) : 0; - }(); - - int fd_kv_per_split = use_fd_mq ? FD_MQ_KV_PER_SPLIT - : (is_mixed ? FD_KV_PER_SPLIT_F16 : FD_KV_PER_SPLIT); - int fd_max_splits = use_fd_mq ? FD_MQ_MAX_SPLITS : FD_MAX_SPLITS; - if (fd_env_kv_per_split > 0) { fd_kv_per_split = fd_env_kv_per_split; } - if (fd_env_max_splits > 0) { fd_max_splits = fd_env_max_splits; } - int n_splits = (n_kv + fd_kv_per_split - 1) / fd_kv_per_split; - if (n_splits < FD_MIN_SPLITS) { n_splits = FD_MIN_SPLITS; } - if (n_splits > fd_max_splits) { n_splits = fd_max_splits; } - if (use_fd_mq_decode) { - const size_t wg_per_split = (size_t) n_head_kv * n_batch; - const size_t wg_target = 4 * (size_t) backend_ctx->fa.compute_units; - while (wg_per_split * n_splits < wg_target && n_splits < fd_max_splits && - n_kv / (n_splits + 1) >= 32) { - n_splits++; - } - } - const int kv_per_split = (n_kv + n_splits - 1) / n_splits; - - const int fa_partial_floats = 2 + d_head_v; - const size_t partial_size_bytes = - (size_t) n_batch * n_head * n_q * n_splits * fa_partial_floats * sizeof(float); - - ggml_cl_flash_attn_temp_buffer temp_partial; - cl_mem partial_buffer; - cl_int err; - if (use_fd_mq_decode) { - auto & pool = backend_ctx->fa.fd_partial; - if (partial_size_bytes > pool.size) { - CL_CHECK(clFinish(backend_ctx->queue)); - pool.allocate(backend_ctx->context, partial_size_bytes); - } - partial_buffer = pool.buffer; - } else { - temp_partial.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, - partial_size_bytes, NULL, &err); - if (err != CL_SUCCESS) { - CL_CHECK(clFinish(backend_ctx->queue)); - temp_partial.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, - partial_size_bytes, NULL, &err); - } - CL_CHECK(err); - partial_buffer = temp_partial.data; - } - - cl_kernel k_split = fd_k_split; - int argi = 0; - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &extra_q->data_device)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_q)); - if (use_fa_k_img) { - const size_t nb00_bytes = sizeof(uint16_t); - const size_t k_bytes_span = - (size_t)(n_kv > 0 ? n_kv - 1 : 0) * (size_t)k_nb1 + - (size_t)(n_head_kv > 0 ? n_head_kv - 1 : 0) * (size_t)k_nb2 + - (size_t)(n_batch > 0 ? n_batch - 1 : 0) * (size_t)k_nb3 + - (size_t)d_head_q * nb00_bytes; - const size_t k_bytes = (k_bytes_span + 7) & ~(size_t)7; - const size_t k_pixels = k_bytes >> 3; - cl_mem k_img = nullptr; - if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { - k_img = ggml_cl_img_pool_get_or_create( - backend_ctx, backend_ctx->kq_img_pool, - k_data_device, offset_k, k_bytes, CL_HALF_FLOAT); - } - - // if image creation fails, fallback to buffer based kernels - if (k_img == nullptr) { - if (gqa_ratio_dispatch == 4 && - backend_ctx->fa.f32_f16_q1_vec_mq_split.count(dk_dv) > 0) { - k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split.at(dk_dv); - } else { - k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8.at(dk_dv); - } - use_fa_k_img = false; - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &k_data_device)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_k)); - } else { - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &k_img)); - } - } else { - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &k_data_device)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_k)); - } - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &v_data_device)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_v)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &q_nb1)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &q_nb2)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &q_nb3)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &k_nb1)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &k_nb2)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &k_nb3)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &v_nb2)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &v_nb3)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_head_log2_val)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &logit_softcap)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &mask_buffer)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_mask)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &mask_nb2)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &mask_nb3)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &mask_ne2)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &mask_ne3)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &partial_buffer)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_splits)); - CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &kv_per_split)); - - // MQ split kernel uses MQ_NSG_SPLIT subgroups and one WG per (kv_head, batch, split) - // matches Q1_WG_SIZE * NSG (MQ_GQA=4 -> 256; MQ_GQA=8 -> 192) - const size_t fd_wg = use_fd_mq ? fd_mq_wg : 64; - const size_t fd_head_dim = use_fd_mq - ? (size_t)(n_head_kv * fd_head_sub * n_batch) - : (size_t)(n_head * n_batch); - size_t fd_lws[3] = { fd_wg, 1, 1 }; - // gid(2) packs q_idx * n_splits + split_idx. - size_t fd_gws[3] = { fd_wg, fd_head_dim, (size_t)(n_splits * n_q) }; - backend_ctx->enqueue_ndrange_kernel(k_split, 3, fd_gws, fd_lws, dst); - - cl_kernel k_merge = backend_ctx->fa.f32_merge.at(dk_dv); - argi = 0; - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_mem), &partial_buffer)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_mem), &extra_o->data_device)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &offset_o)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(int), &n_splits)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &o_nb1)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &o_nb2)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &o_nb3)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_mem), &sinks_buffer)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &offset_sinks)); - CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(int), &n_q)); - - const size_t merge_wg = (size_t) (d_head_v / 4); // one lane per float4 - size_t merge_lws[3] = { merge_wg, 1, 1 }; - size_t merge_gws[3] = { merge_wg, (size_t)(n_head * n_batch), (size_t) n_q }; - backend_ctx->enqueue_ndrange_kernel(k_merge, 3, merge_gws, merge_lws, dst); - return; - } - - cl_mem prefill_k_img = nullptr; - if (use_prefill_k_img) { - const size_t nb00_bytes = sizeof(uint16_t); - const size_t k_bytes_span = - (size_t)(n_kv > 0 ? n_kv - 1 : 0) * (size_t)k_nb1 + - (size_t)(n_head_kv > 0 ? n_head_kv - 1 : 0) * (size_t)k_nb2 + - (size_t)(n_batch > 0 ? n_batch - 1 : 0) * (size_t)k_nb3 + - (size_t)d_head_q * nb00_bytes; - const size_t k_bytes = (k_bytes_span + 7) & ~(size_t)7; - const size_t k_pixels = k_bytes >> 3; - if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { - prefill_k_img = ggml_cl_img_pool_get_or_create( - backend_ctx, backend_ctx->kq_img_pool, - k_data_device, offset_k, k_bytes, CL_HALF_FLOAT); - } - if (prefill_k_img == nullptr) { - kernel = backend_ctx->fa.f32_f16_split.at(dk_dv); - use_prefill_k_img = false; - } - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_q->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_q)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), use_prefill_k_img ? &prefill_k_img : &k_data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_k)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &v_data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset_v)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra_o->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset_o)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n_q)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n_kv)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &is_causal)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &n_head)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &q_nb1)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &q_nb2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &q_nb3)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &k_nb1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &k_nb2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &k_nb3)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &v_nb1)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &v_nb2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &v_nb3)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &o_nb1)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &o_nb2)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &o_nb3)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(int), &n_head_log2_val)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(float), &logit_softcap)); - CL_CHECK(clSetKernelArg(kernel, 30, sizeof(int), &n_head_kv)); - CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_mem), &mask_buffer)); - CL_CHECK(clSetKernelArg(kernel, 32, sizeof(cl_ulong), &offset_mask)); - CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_ulong), &mask_nb1)); - CL_CHECK(clSetKernelArg(kernel, 34, sizeof(cl_ulong), &mask_nb2)); - CL_CHECK(clSetKernelArg(kernel, 35, sizeof(cl_ulong), &mask_nb3)); - CL_CHECK(clSetKernelArg(kernel, 36, sizeof(int), &mask_ne2)); - CL_CHECK(clSetKernelArg(kernel, 37, sizeof(int), &mask_ne3)); - CL_CHECK(clSetKernelArg(kernel, 38, sizeof(cl_mem), &sinks_buffer)); - CL_CHECK(clSetKernelArg(kernel, 39, sizeof(cl_ulong), &offset_sinks)); - if (n_q > 1 && is_mixed) { - CL_CHECK(clSetKernelArg(kernel, 40, sizeof(cl_mem), &k_pad_buffer)); - CL_CHECK(clSetKernelArg(kernel, 41, sizeof(cl_mem), &v_pad_buffer)); - CL_CHECK(clSetKernelArg(kernel, 42, sizeof(cl_mem), &mask_pad_buffer)); - CL_CHECK(clSetKernelArg(kernel, 43, sizeof(cl_mem), &blk_buffer)); - CL_CHECK(clSetKernelArg(kernel, 44, sizeof(int), &n_kv_blocks)); - CL_CHECK(clSetKernelArg(kernel, 45, sizeof(cl_ulong), &mask_pad_nb1)); - CL_CHECK(clSetKernelArg(kernel, 46, sizeof(cl_ulong), &mask_pad_nb2)); - CL_CHECK(clSetKernelArg(kernel, 47, sizeof(cl_ulong), &mask_pad_nb3)); - } else if (use_native_q8_0 || use_native_q4_0) { - // arg 40 = blk classification buffer (NULL disables prepass opt). - CL_CHECK(clSetKernelArg(kernel, 40, sizeof(cl_mem), &blk_buffer)); - } - - if (n_q == 1) { - if (use_local_tile) { - const size_t lt_wg = 128; - size_t local_work_size[] = { lt_wg, 1, 1 }; - size_t global_work_size[] = { lt_wg, (size_t) n_head, (size_t) n_batch }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - // q1_vec dispatches with NSG subgroups - const size_t q1_wg = backend_ctx->gpu_family == INTEL ? 32 : 64; - const size_t wg_size = use_q1_vec ? 256 : q1_wg; - const size_t head_dim_global = use_q1_vec_mq - ? (size_t)(n_head_kv * n_batch) - : (size_t)(n_head * n_batch); - size_t local_work_size[] = { wg_size, 1 }; - size_t global_work_size[] = { wg_size, head_dim_global }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); - } - } else if (use_native_q8_0 || use_native_q4_0) { - // Native quant prefill. The split variant may override BLOCK_M - // (e.g. DK=96 quant uses BM=16). - const bool use_split = use_native_q8_0 ? use_split_q8_0 : use_split_q4_0; - int bm; - size_t wg_size; - if (use_split) { - bm = use_native_q8_0 ? backend_ctx->fa.f32_q8_0_split_bm.at(dk_dv) - : backend_ctx->fa.f32_q4_0_split_bm.at(dk_dv); - wg_size = use_native_q8_0 ? backend_ctx->fa.f32_q8_0_split_wg_size.at(dk_dv) - : backend_ctx->fa.f32_q4_0_split_wg_size.at(dk_dv); - } else { - bm = backend_ctx->fa.bm.at(dk_dv); - wg_size = (size_t) bm; - } - size_t local_work_size[] = { wg_size, 1 }; - size_t global_work_size[] = { (size_t)((n_q + bm - 1) / bm) * wg_size, (size_t)(n_head * n_batch) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); - } else { - const size_t wg_size = (size_t) wg_size_fa; - size_t local_work_size[] = { wg_size, 1 }; - size_t global_work_size[] = { (size_t)((n_q + block_m - 1) / block_m) * wg_size, (size_t)(n_head * n_batch) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); - } -} - -static void ggml_cl_mul_mat_f16_f32_tiled(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int M = src0->ne[1]; - const int N = src1->ne[1]; - const int K = src0->ne[0]; - - cl_kernel kernel = backend_ctx->kernel_mul_mat_f16_f32_tiled; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - - // Tiling parameters. These need to be tuned for optimal performance. - // They must match the #defines in the kernel mul_mat_f16_f32.cl. - // - // OPWM / OPWN: Output tile size per Work-Group. A work-group computes a tile of size OPWM x OPWN. - // TPWM / TPWN: Threads per Work-group. This is the work-group size. - // OPTM / OPTN: Output elements per Thread. Each thread computes OPTM x OPTN elements. - // - // The following relationships must hold: - // OPWM = TPWM * OPTM - // OPWN = TPWN * OPTN - // - const int OPWM = 64; - const int OPWN = 64; - const int TPWM = 16; - const int TPWN = 8; - - size_t local_work_size[2] = { TPWM, TPWN }; - size_t global_work_size[2] = { - (size_t) ((M + OPWM - 1) / OPWM) * TPWM, - (size_t) ((N + OPWN - 1) / OPWN) * TPWN, - }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static bool ggml_cl_can_use_adreno_xmem_gemm_f16_f32( - const ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * src0, - const ggml_tensor * src1, - const ggml_tensor * dst) { - if (!backend_ctx->adreno_xmem_gemm_enabled) { - return false; - } - if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO) { - return false; - } - if ((src0->type != GGML_TYPE_F16 && src0->type != GGML_TYPE_BF16) || - src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { - return false; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) { - return false; - } - if (src0->ne[2] != 1 || src0->ne[3] != 1 || - src1->ne[2] != 1 || src1->ne[3] != 1 || - dst->ne[2] != 1 || dst->ne[3] != 1) { - return false; - } - const int K = src0->ne[0]; - const int M = src0->ne[1]; - const int N = src1->ne[1]; - if (src1->ne[0] != K || dst->ne[0] != M || dst->ne[1] != N) { - return false; - } - if (N <= 1 || M < 64 || N < 16 || K < 64) { - return false; - } - if ((K % 8) != 0) { - return false; - } - const int kpack = K / 4; - const int npack = CEIL_DIV(M, 4); - if (static_cast(N) > backend_ctx->image2d_max_width || - static_cast(kpack) > backend_ctx->image2d_max_height) { - return false; - } - if (static_cast(N) > backend_ctx->image2d_max_width || - static_cast(npack) > backend_ctx->image2d_max_height) { - return false; - } - return true; -} - -static void ggml_cl_mul_mat_f16_f32_adreno_xmem( - ggml_backend_t backend, - const ggml_tensor * src0, - const ggml_tensor * src1, - ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - const cl_ulong offset0 = extra0->offset + src0->view_offs; - const cl_ulong offset1 = extra1->offset + src1->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int K = src0->ne[0]; - const int M = src0->ne[1]; - const int N = src1->ne[1]; - const int kpack = K / 4; - const int npack = CEIL_DIV(M, 4); - const int os = 8; - // Pad weights to the 32-row tiles read by the xmem kernel. - const int npack_padded = CEIL_DIV(npack, os)*os; - - const size_t xmem_bytes = 6144; - const size_t weight_bytes = static_cast(kpack) * static_cast(npack_padded) * 4u * sizeof(cl_half4); - - backend_ctx->prealloc_adreno_xmem_const.allocate(backend_ctx->context, xmem_bytes); - - cl_int err = CL_SUCCESS; - cl_image_format fmt = {}; - fmt.image_channel_order = CL_RGBA; - fmt.image_channel_data_type = CL_HALF_FLOAT; - - cl_image_desc desc_src = {}; - desc_src.image_type = CL_MEM_OBJECT_IMAGE2D; - desc_src.image_width = static_cast(N); - desc_src.image_height = static_cast(kpack); - cl_mem src_img = clCreateImage(backend_ctx->context, CL_MEM_READ_WRITE, &fmt, &desc_src, nullptr, &err); - CL_CHECK(err); - - cl_image_desc desc_dst = {}; - desc_dst.image_type = CL_MEM_OBJECT_IMAGE2D; - desc_dst.image_width = static_cast(N); - desc_dst.image_height = static_cast(npack); - cl_mem dst_img = clCreateImage(backend_ctx->context, CL_MEM_READ_WRITE, &fmt, &desc_dst, nullptr, &err); - CL_CHECK(err); - - cl_mem weights = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, weight_bytes, nullptr, &err); - CL_CHECK(err); - - cl_kernel prepack = backend_ctx->kernel_adreno_xmem_prepack_weight_f16; - CL_CHECK(clSetKernelArg(prepack, 0, sizeof(cl_mem), &weights)); - CL_CHECK(clSetKernelArg(prepack, 1, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(prepack, 2, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(prepack, 3, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(prepack, 4, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(prepack, 5, sizeof(int), &kpack)); - CL_CHECK(clSetKernelArg(prepack, 6, sizeof(int), &npack_padded)); - CL_CHECK(clSetKernelArg(prepack, 7, sizeof(int), &os)); - size_t lws = 256; - size_t max_wg = backend_ctx->get_kernel_workgroup_size(prepack); - if (lws > max_wg) { - lws = max_wg; - } - size_t gws = CEIL_DIV(static_cast(kpack) * static_cast(npack_padded), lws) * lws; - backend_ctx->enqueue_ndrange_kernel(prepack, 1, &gws, &lws, dst); - - cl_kernel pack_src = backend_ctx->kernel_adreno_xmem_pack_src_f32; - CL_CHECK(clSetKernelArg(pack_src, 0, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(pack_src, 1, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(pack_src, 2, sizeof(cl_mem), &src_img)); - CL_CHECK(clSetKernelArg(pack_src, 3, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(pack_src, 4, sizeof(int), &N)); - size_t pack_src_lws[2] = { 16, 16 }; - size_t pack_src_gws[2] = { - CEIL_DIV(static_cast(N), pack_src_lws[0])*pack_src_lws[0], - CEIL_DIV(static_cast(kpack), pack_src_lws[1])*pack_src_lws[1] - }; - backend_ctx->enqueue_ndrange_kernel(pack_src, 2, pack_src_gws, pack_src_lws, dst); - - cl_kernel gemm = backend_ctx->kernel_gemm_xmem_f16_f32_os8; - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &weights)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &backend_ctx->prealloc_adreno_xmem_const.buffer)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &src_img)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &dst_img)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(int), &npack)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(int), &kpack)); - const size_t z_values = CEIL_DIV(static_cast(npack), static_cast(os)); - size_t gemm_lws[3] = { 64, 1, 1 }; - size_t gemm_gws[3] = { - z_values*gemm_lws[0], - CEIL_DIV(static_cast(N), gemm_lws[0]), - 1 - }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, gemm_gws, gemm_lws, dst); - - cl_kernel store_dst = backend_ctx->kernel_adreno_xmem_store_dst_f32; - CL_CHECK(clSetKernelArg(store_dst, 0, sizeof(cl_mem), &dst_img)); - CL_CHECK(clSetKernelArg(store_dst, 1, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(store_dst, 2, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(store_dst, 3, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(store_dst, 4, sizeof(int), &N)); - size_t store_lws[2] = { 16, 16 }; - size_t store_gws[2] = { - CEIL_DIV(static_cast(N), store_lws[0])*store_lws[0], - CEIL_DIV(static_cast(npack), store_lws[1])*store_lws[1] - }; - backend_ctx->enqueue_ndrange_kernel(store_dst, 2, store_gws, store_lws, dst); - - CL_CHECK(clReleaseMemObject(weights)); - CL_CHECK(clReleaseMemObject(dst_img)); - CL_CHECK(clReleaseMemObject(src_img)); -} -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -static void ggml_cl_conv_2d(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_TENSOR_BINARY_OP_LOCALS; - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const cl_uint Cout = ne03; - const cl_uint Cin = ne02; - const cl_uint N = ne13; - const cl_uint KW = ne00; - const cl_uint KH = ne01; - const cl_uint W = ne10; - const cl_uint H = ne11; - const cl_uint OW = ne0; - const cl_uint OH = ne1; - - const cl_uint s0 = dst->op_params[0]; - const cl_uint s1 = dst->op_params[1]; - const cl_uint p0 = dst->op_params[2]; - const cl_uint p1 = dst->op_params[3]; - const cl_uint d0 = dst->op_params[4]; - const cl_uint d1 = dst->op_params[5]; - - const cl_uint cl_nb00 = nb00/ggml_type_size(src0->type); - const cl_uint cl_nb01 = nb01/ggml_type_size(src0->type); - const cl_uint cl_nb02 = nb02/ggml_type_size(src0->type); - const cl_uint cl_nb03 = nb03/ggml_type_size(src0->type); - const cl_uint cl_nb10 = nb10/ggml_type_size(src1->type); - const cl_uint cl_nb11 = nb11/ggml_type_size(src1->type); - const cl_uint cl_nb12 = nb12/ggml_type_size(src1->type); - const cl_uint cl_nb13 = nb13/ggml_type_size(src1->type); - const cl_uint cl_nb1 = nb1/ggml_type_size(dst->type); - const cl_uint cl_nb2 = nb2/ggml_type_size(dst->type); - const cl_uint cl_nb3 = nb3/ggml_type_size(dst->type); - - const int64_t NPQ = (int64_t)N * OW * OH; - - const uint32_t BS_K = 64; - const uint32_t BS_NPQ = 64; - const uint32_t BS_CRS = 16; - const uint32_t VEC_SIZE = 4; - - const uint32_t TS_K = 4; - const uint32_t TS_NPQ = 8; - - const uint32_t WG_K = BS_K / TS_K; - const uint32_t WG_NPQ = BS_NPQ / TS_NPQ; - - auto splitWork = [](uint32_t work_size, uint32_t block_size) { return (block_size + work_size - 1) / block_size; }; - const uint32_t NB_K = splitWork(Cout, BS_K); - const uint32_t NB_NPQ = splitWork(NPQ, BS_NPQ); - - cl_kernel kernel; - size_t shmem_size; - - if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16) { - kernel = backend_ctx->kernel_conv_2d_f16; - shmem_size = (size_t)(BS_K * BS_CRS * sizeof(cl_half) + BS_CRS * (BS_NPQ / VEC_SIZE) * sizeof(cl_half4)); - } else if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_conv_2d_f32; - shmem_size = (size_t)(BS_K * BS_CRS * sizeof(cl_float) + BS_CRS * (BS_NPQ / VEC_SIZE) * sizeof(cl_float4)); - } else if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_conv_2d_f16_f32; - shmem_size = (size_t)(BS_K * BS_CRS * sizeof(cl_half) + BS_CRS * (BS_NPQ / VEC_SIZE) * sizeof(cl_float4)); - } else { - GGML_ASSERT(false && "Unsupported data type combination for conv2d"); - } - - cl_uint idx = 0; - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, idx++, shmem_size, NULL)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &Cout)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &Cin)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &N)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &KW)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &KH)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &W)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &OW)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &OH)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &s0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &s1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &p0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &p1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &d0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &d1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb00)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb01)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb02)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb03)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb10)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb11)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb12)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb13)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb3)); - - size_t global_work_size[] = { (size_t)NB_K * WG_K, (size_t)NB_NPQ * WG_NPQ, 1 }; - size_t local_work_size[] = { (size_t)WG_K, (size_t)WG_NPQ, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); -} - -static void ggml_cl_conv2_dw(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_TENSOR_BINARY_OP_LOCALS; - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; - - const cl_long offset0 = extra0->offset + src0->view_offs; - const cl_long offset1 = extra1->offset + src1->view_offs; - const cl_long offsetd = extrad->offset + dst->view_offs; - - const cl_long C = ne12; - const cl_long N = ne13; - const cl_long KW = ne00; - const cl_long KH = ne01; - const cl_long W = ne10; - const cl_long H = ne11; - const cl_long OW = ne0; - const cl_long OH = ne1; - - const cl_int s0 = dst->op_params[0]; - const cl_int s1 = dst->op_params[1]; - const cl_int p0 = dst->op_params[2]; - const cl_int p1 = dst->op_params[3]; - const cl_int d0 = dst->op_params[4]; - const cl_int d1 = dst->op_params[5]; - - const cl_long cl_nb01 = nb01/ggml_type_size(src0->type); - const cl_long cl_nb03 = nb03/ggml_type_size(src0->type); - const cl_long cl_nb11 = nb11/ggml_type_size(src1->type); - const cl_long cl_nb12 = nb12/ggml_type_size(src1->type); - const cl_long cl_nb13 = nb13/ggml_type_size(src1->type); - const cl_long cl_nb1 = nb1/ggml_type_size(dst->type); - const cl_long cl_nb2 = nb2/ggml_type_size(dst->type); - const cl_long cl_nb3 = nb3/ggml_type_size(dst->type); - - cl_kernel kernel; - if (src0->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_conv2d_dw_f32_f32; - } else if (src0->type == GGML_TYPE_F16) { - kernel = backend_ctx->kernel_conv2d_dwf16_f32; - } else { - GGML_ASSERT(false && "Unsupported data type combination for conv2_dw"); - } - - cl_uint idx = 0; - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &offset0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &offset1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &C)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &N)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &KW)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &KH)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &W)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &H)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &OW)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &OH)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &s0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &s1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &p0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &p1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &d0)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &d1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb01)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb03)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb11)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb12)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb13)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb3)); - - const size_t total = (size_t) N * C * OH * OW; - const size_t local_size = MIN((size_t) 256, backend_ctx->get_kernel_workgroup_size(kernel)); - size_t global_work_size[] = { CEIL_DIV(total, local_size) * local_size }; - size_t local_work_size[] = { local_size }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); -} - -// is_kq selects which of the two products this call is, and it is decided by the -// CALLER -- the two admission arms in ggml_cl_mul_mat, each of which knows which -// one it matched. It used to be re-derived here from nb01 > nb02, i.e. "K is -// head-major, V^T is not". That discriminator COLLAPSES at n_head_kv == 1, where -// the two strides are equal because there is only one head to order, so nothing -// here could tell a KQ from a KQV. Pass it in rather than infer it. -static void ggml_cl_mul_mat_kq_kqv_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool is_kq) { - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - - const int ne10 = src1->ne[0]; - const int ne11 = src1->ne[1]; - const int ne12 = src1->ne[2]; - - const cl_ulong nb10 = src1->nb[0]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 == ne10); - - cl_kernel kernel; - cl_context context = backend_ctx->context; - - cl_int status; - cl_image_format img_fmt_1d; - cl_image_desc img_desc_1d; - cl_buffer_region region; - cl_mem A_image1d; - cl_mem A_sub_buffer; - cl_mem B_sub_buffer; - cl_mem D_image1d; - cl_mem D_sub_buffer; - - int M = ne01; - int N = ne1; - int K = ne00; - - kernel = is_kq ? backend_ctx->kernel_mul_mm_f16_f32_kq - : backend_ctx->kernel_mul_mm_f16_f32_kqv; - // create sub-buffer for A - // <--------------------------------------------> // - extra0 = src0->view_src ? (ggml_tensor_extra_cl *)src0->view_src->extra : (ggml_tensor_extra_cl *)src0->extra; - - region.origin = (extra0->offset + src0->view_offs); - if (is_kq) { - // KQ - region.size = nb01 * ne01; - } else { - // KQV - region.size = nb02 * ne02; - } - - A_sub_buffer = clCreateSubBuffer((extra0->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // <--------------------------------------------> // - - // create sub-buffer for B - // <--------------------------------------------> // - region.origin = (extra1->offset + src1->view_offs); - region.size = nb10 * ne10 * ne11 * ne12; - B_sub_buffer = clCreateSubBuffer((extra1->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - // <--------------------------------------------> // - - img_fmt_1d = {CL_RGBA, CL_FLOAT}; - memset(&img_desc_1d, 0, sizeof(img_desc_1d)); - img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - if (is_kq) { - img_desc_1d.image_width = (nb01 * ne01 / 4)/4; - } - else { - img_desc_1d.image_width = (nb02 * ne02 / 4)/4; - } - img_desc_1d.buffer = A_sub_buffer; - A_image1d = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &status); - CL_CHECK(status); - - // create sub-buffer for output C - // <--------------------------------------------> // - region.origin = (extrad->offset + dst->view_offs); - region.size = ne0 * ne1 * dst->ne[2] * dst->nb[0]; // size of C in bytes - D_sub_buffer = clCreateSubBuffer((extrad->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - // <--------------------------------------------> // - - // create image for C output - // <--------------------------------------------> // - img_fmt_1d = {CL_R, CL_FLOAT}; - memset(&img_desc_1d, 0, sizeof(img_desc_1d)); - img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc_1d.image_width = ne0 * ne1 * dst->ne[2] * dst->nb[0] / 4; - img_desc_1d.buffer = D_sub_buffer; - D_image1d = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &status); - CL_CHECK(status); - // <--------------------------------------------> // - - int offset_src0 = 0; - int offset_src1 = 0; - - // set kernel args - // <--------------------------------------------> // - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &A_image1d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset_src0)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &B_sub_buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset_src1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &D_image1d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &extrad->offset)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &nb01)); - - size_t global_work_size[3] = {64, static_cast(((M+63)/64)), static_cast(((N+31)/32)*ne12)}; - size_t local_work_size[3] = {64, 1, 2}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - // deallocate sub buffers and images - // <--------------------------------------------> // - CL_CHECK(clReleaseMemObject(A_image1d)); - CL_CHECK(clReleaseMemObject(D_image1d)); - CL_CHECK(clReleaseMemObject(A_sub_buffer)); - CL_CHECK(clReleaseMemObject(B_sub_buffer)); - CL_CHECK(clReleaseMemObject(D_sub_buffer)); -} - -static void ggml_cl_mul_mat_q1_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - GGML_ASSERT(src0->type == GGML_TYPE_Q1_0); - GGML_ASSERT(src1->type == GGML_TYPE_F32); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q1_0 * extra0_q1_0 = (ggml_tensor_extra_cl_q1_0 *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_ASSERT(src1->view_offs == 0); - GGML_ASSERT(dst->view_offs == 0); - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - - const int ne10 = src1->ne[0]; - const int ne12 = src1->ne[2]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 == ne10); - GGML_ASSERT((ne00 % 128) == 0); - GGML_ASSERT(ne0 == ne01); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - if (ne1 == 1) { - cl_mem q_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for q (uint32: each texel packs 32 sign bits) - img_fmt = { CL_R, CL_UNSIGNED_INT32}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 32; - img_desc.buffer = extra0_q1_0->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // create a sub_buffer for B - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer((extra1->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // Tall M has enough row parallelism to skip the K split and its reduction. - const bool use_nsg1 = backend_ctx->min_m_gemv_nsg1_q1_0 > 0 && M >= backend_ctx->min_m_gemv_nsg1_q1_0; - kernel = use_nsg1 ? backend_ctx->kernel_gemv_noshuffle_q1_0_f32_nsg1 : backend_ctx->kernel_gemv_noshuffle_q1_0_f32; - - int r2 = 1; - int r3 = 1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q1_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &extra1->offset)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &extrad->offset)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); - - size_t wavesize = backend_ctx->adreno_wave_size; - const size_t nsg = use_nsg1 ? 1 : 4; - size_t local_work_size[] = { wavesize, nsg, 1 }; - size_t global_work_size[] = { CEIL_DIV(M, wavesize)*wavesize, nsg, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } else { - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q1_0_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q1_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q1_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(N, 8), (size_t)CEIL_DIV(M, 4), 1 }; - size_t local_work_size[] = { 2, 128, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static bool ggml_cl_mul_mat_q2_0_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_q2_0 * extra0 = (ggml_tensor_extra_cl_q2_0 *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_q2_0_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_q2_0_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_Q2_0_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static void ggml_cl_mul_mat_q2_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_q2_0 * extra0 = (ggml_tensor_extra_cl_q2_0 *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - const bool wide = m >= 16384 && m % 8 == 0; - cl_kernel gemv = wide ? backend_ctx->kernel_gemv_noshuffle_q2_0_f32_wide : backend_ctx->kernel_gemv_noshuffle_q2_0_f32; - const size_t workgroup = wide ? backend_ctx->q2_0_mv_workgroup_size_wide : backend_ctx->q2_0_mv_workgroup_size; - const size_t rows = wide ? 8 : 4; - size_t nsg = std::min((size_t)backend_ctx->q2_0_mv_nsg, wide ? size_t(8) : m >= 4096 ? size_t(16) : size_t(32)); - while (nsg > (size_t)k/64 || nsg*16 > workgroup) { - nsg /= 2; - } - const size_t lanes = workgroup/nsg; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &stride_d)); - size_t global[] = { (size_t)CEIL_DIV(m, rows*lanes)*lanes, (size_t)n*nsg, 1 }; - size_t local[] = { lanes, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_q2_0_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_q2_0_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static bool ggml_cl_mul_mat_coopmat(ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, - std::initializer_list weights, - const ggml_tensor * src1, ggml_tensor * dst, int K, int M, int N) { - if (kernel == nullptr || M % 64 != 0 || N < 2) { - return false; - } - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int n_tiles = CEIL_DIV(N, 64); - - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, (size_t)n_tiles * 64 * K * sizeof(cl_half)); - - cl_kernel pk = backend_ctx->kernel_pack_b_f16_coopmat; - CL_CHECK(clSetKernelArg(pk, 0, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(pk, 1, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(pk, 2, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); - CL_CHECK(clSetKernelArg(pk, 3, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(pk, 4, sizeof(int), &N)); - size_t p_local[2] = { 64, 4 }; - size_t p_global[2] = { (size_t)n_tiles * 64, (size_t)CEIL_DIV(K, 64) * 4 }; - backend_ctx->enqueue_ndrange_kernel(pk, 2, p_global, p_local, dst); - - cl_uint ka = 0; - for (cl_mem w : weights) { - CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &w)); - } - CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); - CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &N)); - - size_t c_local[3] = { 64, 1, 4 }; - size_t c_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(n_tiles, 4) * 4 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, c_global, c_local, dst); - return true; -} - -static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, - const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - if (ne1 == 1) { - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_RGBA, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32b_trans; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &K)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &M)); - - size_t wavesize = backend_ctx->adreno_wave_size; - size_t local_work_size[3] = { wavesize, 4, 1 }; - size_t global_work_size[3] = { (size_t)CEIL_DIV(M, 64) * 64, 4, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - const bool have_a8 = backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin != nullptr; - const int gemm_tile_n = have_a8 ? 64 : 32; - int N_pad = (N + gemm_tile_n - 1) & ~(gemm_tile_n - 1); - - cl_mem a_img = extra0_q4_0->q_img; - cl_mem s_img = extra0_q4_0->d_img; - GGML_ASSERT(a_img && s_img && "ILA Q4_0 weight images missing; set_tensor should have built them"); - - static const char * q4_0_bin_dp4a_env = getenv("GGML_OPENCL_Q4_0_BIN_DP4A"); - bool q4_0_bin_dp4a_on = q4_0_bin_dp4a_env - ? (atoi(q4_0_bin_dp4a_env) != 0) - : true; - // dot prod has to be available - q4_0_bin_dp4a_on = backend_ctx->has_integer_dot && q4_0_bin_dp4a_on; - - if (q4_0_bin_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin) { - const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; - const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); - - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_mem b_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_int tb = (cl_int)((size_t)N * (K / 32)); - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_mem d_sub = nullptr; - cl_mem d_img = nullptr; - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin; - - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 1, 1 }; - size_t global_work_size[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub)); - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub)); - return; - } - - // Pad B through a zero-filled scratch buffer when N needs - // padding, since the GEMM kernel always reads a full N-tile. - const bool need_pad = N_pad > N; - cl_mem b_sub_buf = nullptr; - cl_mem b_padded = nullptr; - if (need_pad) { - CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, - (size_t)K * N_pad * sizeof(float), NULL, &err), err)); - const float zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), - 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, - offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - } else { - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = need_pad ? (size_t)K * N_pad : (size_t)K * N; - img_desc.buffer = need_pad ? b_padded : b_sub_buf; - cl_mem b_img; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - int line_stride_matrix_A_in_bytes = M * 4; - int line_stride_matrix_S_in_bytes = M * 2; - int line_stride_matrix_B_in_bytes = K * 4; - int line_stride_matrix_C_in_bytes = M * 4; - - const int b_offset_for_kernel = 0; - - if (!have_a8) { - const int c_offset_for_kernel = (int)offsetd; - - kernel = backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin; - - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &b_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_A_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_S_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_B_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_C_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - if ((m_tiles % 2) != 0) { - // keep the work-group count in y even so every work-group is full - m_tiles += 1; - } - - size_t local_work_size[3] = { 64, 2, 4 }; - size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img)); - if (b_sub_buf) { - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } - if (b_padded) { - CL_CHECK(clReleaseMemObject(b_padded)); - } - return; - } - - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - cl_mem d_sub_buf; - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub_buf; - cl_mem d_img; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - const int c_offset_for_kernel = 0; - - kernel = backend_ctx->kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin; - - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &s_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &b_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_A_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_S_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_B_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_C_in_bytes)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 2 }; - size_t global_work_size[3] = { 64, (size_t)CEIL_DIV(M, 64), (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - - if (b_sub_buf) { - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } - if (b_padded) { - CL_CHECK(clReleaseMemObject(b_padded)); - } - } -} -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -static void ggml_cl_mul_mat_q4_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - - const int ne10 = src1->ne[0]; - const int ne12 = src1->ne[2]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - // Multi-column (N=3) verify GEMV for q4_0 - static const bool q40_mc3 = (getenv("GGML_OPENCL_Q4_0_MC3") != nullptr); - const bool use_q40_mc3 = q40_mc3 && (ne1 >= 2 && ne1 <= 4) && (ne01 < 32768); - - const bool use_bin = use_q4_0_bin_kernels(backend_ctx, src0); - - if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_0_f32_coopmat, - { extra0_q4_0->q, extra0_q4_0->d }, src1, dst, K, M, N)) { - return; - } - - if (use_bin) { - if (use_q40_mc3) { - static bool warned = false; - if (!warned) { - GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q4_0_MC3 is bypassed by Q4_0 binary kernels\n"); - warned = true; - } - } - // This bin layout is not supported by CoopK. - ggml_cl_mul_mat_q4_0_f32_adreno_ila(backend, src0, src1, dst); - return; - } - - if (ne1 == 1 || use_q40_mc3) { - cl_mem q_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for q - img_fmt = { CL_R, CL_UNSIGNED_INT32}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_q4_0->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - if (use_q40_mc3) { - kernel = backend_ctx->kernel_gemv_noshuffle_q4_0_f32_mc3; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne1)); - } else { - kernel = backend_ctx->kernel_gemv_noshuffle_q4_0_f32; - if (M == 4096 && K == 4096) { - kernel = backend_ctx->kernel_gemv_noshuffle_q4_0_f32_4096_1_4096; - } else if (M == 4096 && K == 11008) { - kernel = backend_ctx->kernel_gemv_noshuffle_q4_0_f32_4096_1_11008; - } else if (M == 11008 && K == 4096) { - kernel = backend_ctx->kernel_gemv_noshuffle_q4_0_f32_11008_1_4096; - } else if (M == 32000 && K == 4096) { - kernel = backend_ctx->kernel_gemv_noshuffle_q4_0_f32_32000_1_4096; - } - - int r2 = 1; - int r3 = 1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); - } - - // Small-M mc3 verify is occupancy/latency-bound (too few WGs at small M, so - // its bandwidth falls well short of the FFN matmuls'). Use 8 subgroups (512-WI WGs, half the - // per-lane K-walk) for small M. Layout stride is fixed (4 uints/block), so only - // the K-split count changes; the mc3 kernel reads it via get_local_size(1). The - // ne1==1 base kernel hardcodes N_SIMDGROUP=4, so it always stays at 4. - int mc3_nsg = (use_q40_mc3 && ne01 < 4096) ? 8 : 4; - if (use_q40_mc3) { - // Register pressure can lower the kernel limit below the device limit. - const size_t max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - while (mc3_nsg > 1 && (size_t)(64 * mc3_nsg) > max_workgroup_size) { - mc3_nsg /= 2; - } - } - size_t local_work_size[3] = {64, (size_t)mc3_nsg, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, (size_t)mc3_nsg, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - // CoopK uses the same untiled weight layout as gemm_noshuffle_q4_0_f32, with K-major Q8_1 activations (K contiguous). - if (ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q4_0) - && backend_ctx->kernel_gemm_coopk_q4_0_q8_1_dp4a_c4 != nullptr - && ((N <= 2) ? backend_ctx->kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 - : backend_ctx->kernel_gemm_coopk_q4_0_q8_1_dp4a_c4) != nullptr) { - cl_mem b_sub_buf = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const int cols = (N <= 2) ? 2 : 4; - const size_t n_blocks_padded = (size_t)cols * (K / 32); - const size_t size_qa = (size_t)cols * K * sizeof(cl_char); - const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; - const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; - backend_ctx->prealloc_moe_qa.allocate(context, size_qa); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); - if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { - const cl_char z8 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, - &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); - } - if (backend_ctx->prealloc_moe_da.size != size_da_prev) { - const cl_half z16 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); - } - - cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); - cl_kernel kernel_quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); - size_t local_work_size_quant[1] = { 64 }; - size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); - - cl_kernel kernel_coopk = (N <= 2) ? backend_ctx->kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 - : backend_ctx->kernel_gemm_coopk_q4_0_q8_1_dp4a_c4; - const cl_int n_padded = cols; - CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_int), &n_padded)); - CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_int), &K)); - CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &N)); - - const size_t nsg = (size_t)backend_ctx->nsg_coopk_dp4a_q4_0; - size_t local_work_size[3] = { 64, nsg, 1 }; - size_t global_work_size[3] = { (size_t)(M / backend_ctx->rows_coopk_dp4a_q4_0), nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - static const char * q4_0_act_vload4_env = getenv("GGML_OPENCL_Q4_0_DP4A_ACT_VLOAD4"); - const bool q4_0_act_vload4_on = q4_0_act_vload4_env == nullptr || atoi(q4_0_act_vload4_env) != 0; - // Enable dense prefill by default on X2E when the uint4 activation tile is enabled. - static const char * q4_0_dense_dp4a_env = getenv("GGML_OPENCL_Q4_0_DENSE_DP4A"); - bool q4_0_dense_dp4a_on = q4_0_dense_dp4a_env - ? (atoi(q4_0_dense_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && q4_0_act_vload4_on); - // dot prod has to be available - q4_0_dense_dp4a_on = backend_ctx->has_integer_dot && q4_0_dense_dp4a_on; - - if (q4_0_dense_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a - && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { - cl_mem a_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const size_t n_blocks = (size_t)N * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_kernel dk = q4_0_act_vload4_on - ? backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 - : backend_ctx->kernel_gemm_noshuffle_q4_0_q8_1_dp4a; - int ai = 0; - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - CL_CHECK(clReleaseMemObject(a_sub)); - return; - } - - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - cl_mem d_sub_buf = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for output - region.origin = extrad->offset; // Specify the starting offset (in bytes) - region.size = M * N * sizeof(float); // Specify the size of the sub-buffer - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, CL_MEM_WRITE_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - if (ne0 == 4096 && ne1 == 128 && ne10 == 4096) { - local_work_size_t[0]=4; - local_work_size_t[1]=8; - } else if (ne0 == 11008 && ne1 == 128 && ne10 == 4096) { - local_work_size_t[0]=2; - local_work_size_t[1]=8; - } else if(ne0 == 4096 && ne1 == 128 && ne10 == 11008) { - local_work_size_t[0]=1; - local_work_size_t[1]=8; - } else if(ne0 == 32000 && ne1 == 128 && ne10 == 4096) { - local_work_size_t[0]=2; - local_work_size_t[1]=8; - } - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q4_0_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &d_sub_buf)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne1)); - - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; - size_t local_work_size[3] = {1, 128, 1}; - if (ne0 == 4096 && ne1 == 128 && ne10 == 4096) { - local_work_size[0] = 1; - local_work_size[1] = 128; - } else if (ne0 == 11008 && ne1 == 128 && ne10 == 4096) { - local_work_size[0] = 2; - local_work_size[1] = 64; - } else if (ne0 == 4096 && ne1 == 128 && ne10 == 11008) { - local_work_size[0] = 2; - local_work_size[1] = 64; - } else if (ne0 == 32000 && ne1 == 128 && ne10 == 4096) { - local_work_size[0] = 2; - local_work_size[1] = 64; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -static void ggml_cl_mul_mat_q4_1_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q4_1 * extra0_q4_1 = (ggml_tensor_extra_cl_q4_1 *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - // Multi-column (N=3) verify GEMV for q4_1 - static const bool q41_mc3 = (getenv("GGML_OPENCL_Q4_1_MC3") != nullptr); - const bool use_q41_mc3 = q41_mc3 && (ne1 >= 2 && ne1 <= 4) && (ne01 < 32768); - - if (ne1 == 1 || use_q41_mc3) { - cl_mem q_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for q - img_fmt = { CL_R, CL_UNSIGNED_INT32}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_q4_1->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = use_q41_mc3 ? backend_ctx->kernel_gemv_noshuffle_q4_1_f32_mc3 - : backend_ctx->kernel_gemv_noshuffle_q4_1_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_1->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_1->m)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); - if (use_q41_mc3) { - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne1)); // n_cols - } - - size_t local_work_size[3] = {64, 4, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q4_1_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_1->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_1->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_1->m)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne1)); - - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; - size_t local_work_size[3] = {1, 128, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -static void ggml_cl_mul_mat_q5_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q5_0 * extra0_q5_0 = (ggml_tensor_extra_cl_q5_0 *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_0_f32_coopmat, - { extra0_q5_0->qs, extra0_q5_0->qh, extra0_q5_0->d }, src1, dst, K, M, N)) { - return; - } - - if (ne1 == 1) { - cl_mem qs_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for qs - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_q5_0->qs; - CL_CHECK((qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemv_noshuffle_q5_0_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); - - size_t local_work_size[3] = {64, 4, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(qs_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - // dp4a (int8) dense q5_0 prefill GEMM, default off - static const char * q5_dense_dp4a_env = getenv("GGML_OPENCL_Q5_DENSE_DP4A"); - static const char * q5_dense_wimg_env = getenv("GGML_OPENCL_Q5_DENSE_DP4A_WIMG"); - const bool q5_dense_wimg_on = q5_dense_wimg_env && (atoi(q5_dense_wimg_env) != 0); - bool q5_dense_dp4a_on = q5_dense_wimg_on - ? true - : (q5_dense_dp4a_env && (atoi(q5_dense_dp4a_env) != 0)); - // dot prod has to be available - q5_dense_dp4a_on = backend_ctx->has_integer_dot && q5_dense_dp4a_on; - - if (q5_dense_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q5_0_q8_1_dp4a - && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { - cl_mem a_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const size_t n_blocks = (size_t)N * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - // optional qs texture (image1d_buffer over the nibble plane; the same - // CL_R/UINT32 view, width M*K/8, the GEMV path builds). - cl_mem q5_qs_img = nullptr; - bool use_wimg = q5_dense_wimg_on; - if (use_wimg) { - const size_t tex = (size_t)M * (size_t)K / 8; // uint32 texels (2 ushorts/texel) - if (tex == 0 || tex > backend_ctx->image_max_buffer_size) { - use_wimg = false; - } else { - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = tex; - img_desc.buffer = extra0_q5_0->qs; - q5_qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err); - if (err != CL_SUCCESS || q5_qs_img == nullptr) { use_wimg = false; q5_qs_img = nullptr; } - } - } - - cl_kernel dk = use_wimg ? backend_ctx->kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg - : backend_ctx->kernel_gemm_noshuffle_q5_0_q8_1_dp4a; - int ai = 0; - if (use_wimg) { - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &q5_qs_img)); - } else { - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_0->qs)); - } - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_0->d)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - if (q5_qs_img != nullptr) { - CL_CHECK(clReleaseMemObject(q5_qs_img)); - } - CL_CHECK(clReleaseMemObject(a_sub)); - return; - } - - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - cl_mem d_sub_buf = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for output - region.origin = extrad->offset; - region.size = M * N * sizeof(float); - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, CL_MEM_WRITE_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q5_0_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d_sub_buf)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne1)); - - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; - size_t local_work_size[3] = {1, 128, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -static void ggml_cl_mul_mat_q5_1_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q5_1 * extra0_q5_1 = (ggml_tensor_extra_cl_q5_1 *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - if (ne1 == 1) { - cl_mem qs_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for qs - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_q5_1->qs; - CL_CHECK((qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemv_noshuffle_q5_1_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_1->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_1->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_1->m)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); - - size_t local_work_size[3] = {64, 4, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(qs_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - cl_mem d_sub_buf = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for output - region.origin = extrad->offset; - region.size = M * N * sizeof(float); - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, CL_MEM_WRITE_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q5_1_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_1->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_1->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_1->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_1->m)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &d_sub_buf)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne1)); - - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; - size_t local_work_size[3] = {1, 128, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -static void ggml_cl_mul_mat_iq4_nl_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_iq4_nl * extra0_iq4_nl = (ggml_tensor_extra_cl_iq4_nl *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % 32 == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - if (ne1 == 1) { - cl_mem q_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for q - img_fmt = { CL_R, CL_UNSIGNED_INT32}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_iq4_nl->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemv_noshuffle_iq4_nl_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_nl->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); - - size_t local_work_size[3] = {64, 4, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - // dp4a (int8) dense IQ4_NL prefill GEMM. Quantizes the [N,K] activations to - // q8_1 and runs the int8 dot instead of the f16 half-dot. Large-batch - // (ne1>8) only - static const char * iq4nl_dense_dp4a_env = getenv("GGML_OPENCL_IQ4NL_DENSE_DP4A"); - bool iq4nl_dense_dp4a_on = iq4nl_dense_dp4a_env - ? (atoi(iq4nl_dense_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - // dot prod has to be available - iq4nl_dense_dp4a_on = backend_ctx->has_integer_dot && iq4nl_dense_dp4a_on; - - if (iq4nl_dense_dp4a_on && backend_ctx->kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a - && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { - cl_mem a_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const size_t n_blocks = (size_t)N * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_kernel dk = backend_ctx->kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a; - int ai = 0; - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_iq4_nl->q)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_iq4_nl->d)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - CL_CHECK(clReleaseMemObject(a_sub)); - return; - } - - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_iq4_nl_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_nl->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_nl->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne1)); - - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; - size_t local_work_size[3] = {1, 128, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static bool ggml_cl_mul_mat_iq4_xs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq4_xs * extra0 = (ggml_tensor_extra_cl_iq4_xs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ4_XS_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sl)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->sh)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static void ggml_cl_mul_mat_iq4_xs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq4_xs * extra0 = (ggml_tensor_extra_cl_iq4_xs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq4_xs_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->sl)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sh)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq4_xs_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq4_xs_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq4_xs_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sl)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->sh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -#endif - -static void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - GGML_ASSERT(src0->type == GGML_TYPE_Q8_0); - GGML_ASSERT(src1->type == GGML_TYPE_F32); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - // SoA extra lives on view_src (view->extra is pre-SoA). - const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; - ggml_tensor_extra_cl_q8_0 * extra0_q8_0 = (ggml_tensor_extra_cl_q8_0 *)soa0_src->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - - const int ne10 = src1->ne[0]; - const int ne12 = src1->ne[2]; - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 == ne10); - GGML_ASSERT((ne00 % 32) == 0); - GGML_ASSERT(ne0 == ne01); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q8_0_f32_coopmat, - { extra0_q8_0->q, extra0_q8_0->d }, src1, dst, K, M, N)) { - return; - } - - // Multi-column verify GEMV for ne1 2..4, reuses the ne1 == 1 image setup. - // Default on for X2E, GGML_OPENCL_Q8_0_MC=0/1 forces it. - static const char * q8_mc_env = getenv("GGML_OPENCL_Q8_0_MC"); - const bool q8_mc = q8_mc_env ? atoi(q8_mc_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; - const bool use_q8_mc = q8_mc && ne1 >= 2 && ne1 <= 4; - - if (ne1 == 1 || use_q8_mc) { - cl_mem q_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for q - img_fmt = { CL_R, CL_UNSIGNED_INT32}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 4; - img_desc.buffer = extra0_q8_0->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // create a sub_buffer for B - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer((extra1->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - if (use_q8_mc) { - kernel = backend_ctx->kernel_gemv_noshuffle_q8_0_f32_mc; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne1)); - - size_t wavesize = backend_ctx->adreno_wave_size; - size_t local_work_size[] = { wavesize, 4, 1 }; - size_t global_work_size[] = { CEIL_DIV(M, wavesize)*wavesize, 4, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - // Split-K for small-M decode GEMVs. The base kernel puts one output row - // per lane and splits K only inside one workgroup, so M is the sole source - // of workgroup parallelism: gpt-oss's K and V projections are M=512 = 8 - // workgroups on a 16-CU X2, and the kernel measures 48 GB/s where the - // M=2880/4096 projections in the same decode graph reach 122-123. Mirrors - // the q4_0/q4_K split-K above and reuses their reduce kernel. - // - // Enabled where it is measured to win, like the q4_K gate: X2-90 +2.8% - // tg32 @d4096 on gpt-oss; Adreno 840 (12 CU) NEUTRAL on Llama-3.2-3B-Q8_0 - // (0.0% @d4096 -- its K/V proj is M=1024 = 16 workgroups, which already - // fills 12 CUs). Unmeasured on X1E/A7X/A6X and the q4_K split-K measured - // -0.7% on X1E, so the default is not widened on absence of evidence. - static const bool q8_splitk_env_set = []{ - const char * e = std::getenv("GGML_OPENCL_Q8_GEMV_SPLITK"); - return e && e[0] != '\0'; - }(); - static const bool q8_splitk_env_on = []{ - const char * e = std::getenv("GGML_OPENCL_Q8_GEMV_SPLITK"); - return !(e && e[0] == '0'); - }(); - const bool q8_splitk_on = q8_splitk_env_set - ? q8_splitk_env_on - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - if (q8_splitk_on && backend_ctx->kernel_gemv_noshuffle_q8_0_f32_splitk && - ne01 <= 1024 && ne01 % 64 == 0) { - const int nsg = 8; - const int ksplit = 8; // -> 8 * M/64 workgroups - const size_t gx = (size_t) CEIL_DIV(ne01, 64) * 64; - - backend_ctx->prealloc_splitk_partial.allocate( - backend_ctx->context, (size_t) ksplit * ne01 * sizeof(float)); - cl_mem partial = backend_ctx->prealloc_splitk_partial.buffer; - - cl_kernel ks = backend_ctx->kernel_gemv_noshuffle_q8_0_f32_splitk; - CL_CHECK(clSetKernelArg(ks, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(ks, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(ks, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(ks, 3, sizeof(cl_mem), &partial)); - CL_CHECK(clSetKernelArg(ks, 4, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(ks, 5, sizeof(cl_int), &ne01)); - size_t lsk[3] = { 64, (size_t) nsg, 1 }; - size_t gsk[3] = { gx, (size_t) (nsg * ksplit), 1 }; - backend_ctx->enqueue_ndrange_kernel(ks, 3, gsk, lsk, dst); - - cl_kernel kr = backend_ctx->kernel_gemv_splitk_reduce_f32; - CL_CHECK(clSetKernelArg(kr, 0, sizeof(cl_mem), &partial)); - CL_CHECK(clSetKernelArg(kr, 1, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kr, 2, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kr, 3, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kr, 4, sizeof(cl_int), &ksplit)); - size_t lr[3] = { 64, 1, 1 }; - size_t gr[3] = { (size_t) CEIL_DIV(ne01, 64) * 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(kr, 3, gr, lr, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - kernel = backend_ctx->kernel_gemv_noshuffle_q8_0_f32; - - int r2 = 1; - int r3 = 1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); - - size_t wavesize = backend_ctx->adreno_wave_size; - size_t local_work_size[] = { wavesize, 4, 1 }; - size_t global_work_size[] = { CEIL_DIV(M, wavesize)*wavesize, 4, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } else { - static const char * q8_bin_dp4a_env = getenv("GGML_OPENCL_Q8_0_BIN_DP4A"); - const bool q8_bin_dp4a_on = backend_ctx->has_integer_dot && - (q8_bin_dp4a_env ? (atoi(q8_bin_dp4a_env) != 0) : true); - - if (q8_bin_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin - && M % 64 == 0) { - cl_mem a_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const size_t n_blocks = (size_t)N * (K / 32); - - const size_t N_pad = ((size_t)N + 31) / 32 * 32; - const size_t n_blocks_pad = N_pad * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N_pad * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks_pad * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_pad * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_mem q_img = nullptr; - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * (size_t)K / 4; - img_desc.buffer = extra0_q8_0->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - cl_mem d_sub_buf = nullptr; - cl_mem d_img = nullptr; - region.origin = extrad->offset; - region.size = (size_t)M * N * sizeof(float); - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub_buf; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - cl_kernel dk = backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin; - cl_uint ne00_u = (cl_uint)K; - cl_uint ne01_u = (cl_uint)M; - CL_CHECK(clSetKernelArg(dk, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(dk, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(dk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, 4, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(dk, 5, sizeof(cl_uint), &ne00_u)); - CL_CHECK(clSetKernelArg(dk, 6, sizeof(cl_uint), &ne01_u)); - CL_CHECK(clSetKernelArg(dk, 7, sizeof(int), &N)); - - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - CL_CHECK(clReleaseMemObject(a_sub)); - return; - } - - // dp4a dense q8_0 prefill GEMM. Quantizes the [N,K] activations to - // q8_1 and runs the int8 dot instead of the f16 half-dot. Large-batch - // (ne1>8) only; q8_0 weights are already int8 (no requant) and symmetric - // (no min term) - static const char * q8_dense_dp4a_env = getenv("GGML_OPENCL_Q8_DENSE_DP4A"); - static const char * q8_dense_wimg_env = getenv("GGML_OPENCL_Q8_DENSE_DP4A_WIMG"); - const bool q8_dense_wimg_on = q8_dense_wimg_env && (atoi(q8_dense_wimg_env) != 0); - - const bool q8_bin_loaded = (backend_ctx->kernel_gemm_noshuffle_q8_0_f32_bin != nullptr); - // bin kernel takes precedence - bool q8_dense_dp4a_on = q8_dense_wimg_on - ? true - : q8_dense_dp4a_env - ? (atoi(q8_dense_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && !q8_bin_loaded); - // dot prod has to be available - q8_dense_dp4a_on = backend_ctx->has_integer_dot && q8_dense_dp4a_on; - - if (q8_dense_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a - && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { - cl_mem a_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const size_t n_blocks = (size_t)N * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - // optional weight texture, the same CL_R/UINT32 view, width M*K/4 - cl_mem q8_q_img = nullptr; - bool use_wimg = q8_dense_wimg_on; - if (use_wimg) { - const size_t tex = (size_t)M * (size_t)K / 4; // uint32 texels - if (tex == 0 || tex > backend_ctx->image_max_buffer_size) { - use_wimg = false; - } else { - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = tex; - img_desc.buffer = extra0_q8_0->q; - q8_q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err); - if (err != CL_SUCCESS || q8_q_img == nullptr) { use_wimg = false; q8_q_img = nullptr; } - } - } - - static const char * q8_0_act_vload4_env = getenv("GGML_OPENCL_Q8_0_DP4A_ACT_VLOAD4"); - const bool q8_0_act_vload4_on = q8_0_act_vload4_env == nullptr || atoi(q8_0_act_vload4_env) != 0; - cl_kernel dk = use_wimg - ? backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg - : q8_0_act_vload4_on - ? backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4 - : backend_ctx->kernel_gemm_noshuffle_q8_0_q8_1_dp4a; - int ai = 0; - if (use_wimg) { - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &q8_q_img)); - } else { - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q8_0->q)); - } - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - if (q8_q_img != nullptr) { - CL_CHECK(clReleaseMemObject(q8_q_img)); - } - CL_CHECK(clReleaseMemObject(a_sub)); - return; - } - - const bool have_a8 = (backend_ctx->kernel_gemm_noshuffle_q8_0_f32_bin != nullptr); - - if (!have_a8 && backend_ctx->kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin && M >= 64) { - const int gemm_tile_n = 32; - int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; - - cl_mem a_img_a7 = nullptr; - cl_mem b_src_sub = nullptr; - cl_mem b_pad_sub = nullptr; - cl_mem b_buf = nullptr; - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * K / 4; - img_desc.buffer = extra0_q8_0->q; - CL_CHECK((a_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - if (N_pad == N) { - b_buf = b_src_sub; - } else { - size_t padded_bytes = (size_t)K * N_pad * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); - region.origin = 0; - region.size = padded_bytes; - CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const float b_pad_zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), - 0, padded_bytes, 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - b_buf = b_pad_sub; - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N_pad; - img_desc.buffer = b_buf; - cl_mem b_img_a7; - CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - const int c_offset_for_kernel = (int)offsetd; - - int line_stride_B = K * (int)sizeof(float); - int line_stride_C = M * (int)sizeof(float); - - kernel = backend_ctx->kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin; - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img_a7)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 4 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_y = ((m_tiles + 1) / 2) * 2; - size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(a_img_a7)); - CL_CHECK(clReleaseMemObject(b_img_a7)); - if (b_src_sub) { - CL_CHECK(clReleaseMemObject(b_src_sub)); - } - if (b_pad_sub) { - CL_CHECK(clReleaseMemObject(b_pad_sub)); - } - return; - } - - // use bin kernel if available - if (backend_ctx->kernel_gemm_noshuffle_q8_0_f32_bin) { - int K_pad = K; - - cl_mem b_sub_buf = nullptr; - cl_mem d_sub_buf = nullptr; - - cl_mem a_img = nullptr; - cl_mem s_img = nullptr; - cl_mem b_img = nullptr; - cl_mem d_img = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K_pad * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // Create subbuffer and image1d_buffer for dst - region.origin = (extrad->offset); // + dst->view_offs; - region.size = M * N * sizeof(float); - CL_CHECK((d_sub_buf = clCreateSubBuffer((extrad->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // create an image for A - img_fmt = { CL_R, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 4; // Divide by 4 for char -> float - img_desc.buffer = extra0_q8_0->q; - CL_CHECK((a_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // create an image for Scale - img_fmt = { CL_R, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 32; // Block size is 32 - img_desc.buffer = extra0_q8_0->d; - CL_CHECK((s_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // create an image for B from sub_buffer - img_fmt = {CL_R, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K_pad * N; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // img for d - img_fmt = {CL_R, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * N; - img_desc.buffer = d_sub_buf; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q8_0_f32_bin; - - bool layoutA_Mfirst = true; - bool layoutS_Mfirst = true; - bool layoutB_Nfirst = false; - bool layoutC_Mfirst = true; - - cl_uint lineStrideMatrixAinBytes = layoutA_Mfirst ? M * 4 : K; // int8 - cl_uint lineStrideMatrixSinBytes = layoutS_Mfirst ? M * 2 : (K / 32) * 2; // fp16 - cl_uint lineStrideMatrixBinBytes = layoutB_Nfirst ? N * 4 : K_pad * 4; // fp32 - cl_uint lineStrideMatrixCinBytes = layoutC_Mfirst ? M * 4 : N * 4; // fp32 - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &a_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s_img)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &extra1->offset)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &extrad->offset)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &lineStrideMatrixAinBytes)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &lineStrideMatrixSinBytes)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &lineStrideMatrixBinBytes)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &lineStrideMatrixCinBytes)); - - size_t global_work_size[] = { 64, (size_t)CEIL_DIV(M, 64), (size_t)CEIL_DIV(N, 64)}; - size_t local_work_size[] = { 64, 2, 2 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - CL_CHECK(clReleaseMemObject(a_img)); - CL_CHECK(clReleaseMemObject(s_img)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(d_img)); - return; - } - - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q8_0_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q8_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - - size_t global_work_size[] = { (size_t)CEIL_DIV(N, 8), (size_t)CEIL_DIV(M, 4), 1 }; - size_t local_work_size[] = { 2, 128, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -// make sure the image1d_buffer `image` is a proper view of `buffer` by either -// creating a new image1d_buffer or reuse existing one. -// upon success, `image_buffer` is set to the cl_mem in `buffer` and -// `image_bytes` the size in `buffer` and `image` is the image1d_buffer. -static bool ggml_cl_coopk_c8_image( - ggml_backend_opencl_context * backend_ctx, - ggml_cl_buffer & buffer, - size_t bytes, - cl_mem & image, - cl_mem & image_buffer, - size_t & image_bytes -) { - // required bytes exceed image1d_buffer limit - if (bytes / 16 > backend_ctx->image_max_buffer_size) { - return false; - } - // existing image1d_buffer can be reused - if (image != nullptr && image_buffer == buffer.buffer && image_bytes >= bytes) { - return true; - } - // a new one is needed, so release the existing one - if (image != nullptr) { - CL_CHECK(clReleaseMemObject(image)); - image = nullptr; - } - - image_buffer = nullptr; - image_bytes = 0; - - cl_image_format format = {CL_RGBA, CL_UNSIGNED_INT32}; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = bytes / 16; - desc.buffer = buffer.buffer; - - cl_int err; - image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); - if (err != CL_SUCCESS) { - image = nullptr; - return false; - } - - image_buffer = buffer.buffer; - image_bytes = bytes; - return true; -} - -static int ggml_cl_coopk_ksplit(const ggml_backend_opencl_context * backend_ctx, int base_wg, int n_blocks) { - const int cu = MAX(1, (int) backend_ctx->fa.compute_units); - int ksplit = 1; - float best_eff = 0.0f; - for (int k = 1; k <= MIN(8, n_blocks); ++k) { - const int wg = base_wg * k; - const int waves = CEIL_DIV(wg, cu); - const float eff = (float) wg / (waves * cu); - if (eff > best_eff + 0.06f) { - best_eff = eff; - ksplit = k; - } - } - return ksplit; -} - -static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, - const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q4_K * extra0_q4_k = (ggml_tensor_extra_cl_q4_K *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - const int coopk_c8_min_n = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 2 : 5; - if (backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 != nullptr && - N >= coopk_c8_min_n && N <= 8 && M > 0 && K > 0 && M % 256 == 0 && K % 256 == 0 && - src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && - K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && - src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && - src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && - ggml_is_contiguous(src1) && ggml_is_contiguous(dst) - ) { - const int kb = K / 32; - const size_t qa_bytes = (size_t)8 * K; - const size_t ds_bytes = (size_t)16 * kb * sizeof(cl_half); - - backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); - backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); - - if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, - backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && - ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, - backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) - ) { - const int n_blocks = N * kb; - - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); - CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); - - size_t quant_local[] = {64}; - size_t quant_global[] = {(size_t)8 * kb}; - backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); - - int ksplit = ggml_cl_coopk_ksplit(backend_ctx, M / 256, kb); - if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) { - ksplit = 1; - } - - cl_mem out = extrad->data_device; - cl_ulong out_offset = offsetd; - - if (ksplit > 1) { - backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float)); - out = backend_ctx->prealloc_splitk_partial.buffer; - out_offset = 0; - } - - const cl_uchar mask_d6 = 0x3F; - const cl_uchar mask_d4 = 0x0F; - const cl_uchar mask_hi2 = 0xC0; - - const size_t nsg = backend_ctx->nsg_coopk_dp4a_q4_k_bin_c8; - cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8; - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q4_k->q)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(gemm, 12, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(gemm, 13, sizeof(cl_uchar), &mask_hi2)); - CL_CHECK(clSetKernelArg(gemm, 14, sizeof(int), &ksplit)); - - size_t local[] = {64, nsg, 1}; - size_t global[] = {(size_t)M / 4, nsg * ksplit, 1}; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - - if (ksplit > 1) { - const int rows = M * N; - cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32; - CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); - CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); - CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); - size_t reduce_local[] = {64}; - size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64}; - backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); - } - return; - } - } - - // CoopK handles with _bin use the bin weight layout (uint-transposed q), with K-major Q8_1 activations (K contiguous). - if (ne1 >= 2 && ne1 <= 4 && - ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q4_k) && - backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 != nullptr && - ((ne1 <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 - : backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4) != nullptr) { - cl_mem b_sub_buf = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // Allocate all kernel columns; padded columns have independent accumulators and are not stored. - const int cols = (ne1 <= 2) ? 2 : 4; - const size_t size_qa = (size_t)cols * K * sizeof(cl_char); - const size_t n_blocks_padded = (size_t)cols * (K / 32); - const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; - const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; - backend_ctx->prealloc_moe_qa.allocate(context, size_qa); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); - if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { - const cl_char z8 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, - &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); - } - if (backend_ctx->prealloc_moe_da.size != size_da_prev) { - const cl_half z16 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); - } - - cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); - cl_kernel kernel_quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); - size_t local_work_size_quant[1] = { 64 }; - size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); - - cl_kernel kernel_coopk = (ne1 <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 - : backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4; - const int nsg_selected = (ne1 <= 2) ? backend_ctx->nsg_coopk_dp4a_q4_k_bin_c2 - : backend_ctx->nsg_coopk_dp4a_q4_k_bin_c4; - const cl_uchar mask_d6 = 0x3F, mask_d4 = 0x0F, mask_hi2 = 0xC0; - const cl_int n_padded = cols; - CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q4_k->q)); - CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel_coopk, 10, sizeof(cl_int), &n_padded)); - CL_CHECK(clSetKernelArg(kernel_coopk, 11, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel_coopk, 12, sizeof(cl_int), &ne1)); - CL_CHECK(clSetKernelArg(kernel_coopk, 13, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(kernel_coopk, 14, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(kernel_coopk, 15, sizeof(cl_uchar), &mask_hi2)); - - // Each width can compile with a different subgroup count. - const size_t nsg = (size_t)nsg_selected; - size_t local_work_size[3] = { 64, nsg, 1 }; - size_t global_work_size[3] = { (size_t)(ne01 / backend_ctx->rows_coopk_dp4a_q4_k), nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - if (ne1 == 1) { - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_RGBA, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemv_noshuffle_q4_k_f32_32b_trans; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); - - size_t local_work_size[3] = { 64, 8, 1 }; - size_t global_work_size[3] = { (size_t)ne01, 8, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - const int gemm_tile_n = 64; - int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; - - const bool have_a8 = backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin != nullptr; - - static const char * q4_k_bin_dp4a_env = getenv("GGML_OPENCL_Q4_K_BIN_DP4A"); - bool q4_k_bin_dp4a_on = q4_k_bin_dp4a_env - ? (atoi(q4_k_bin_dp4a_env) != 0) - : true; - // dot prod has to be available - q4_k_bin_dp4a_on = backend_ctx->has_integer_dot && q4_k_bin_dp4a_on; - - if (q4_k_bin_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin) { - const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; - const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); - - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_mem b_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_int tb = (cl_int)((size_t)N * (K / 32)); - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_mem d_sub = nullptr; - cl_mem d_img = nullptr; - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin; - - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_int), &N)); - - size_t local_work_size[3] = { 64, 1, 1 }; - size_t global_work_size[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub)); - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub)); - return; - } - - if (!have_a8) { - cl_mem b_src_sub = nullptr; - cl_mem b_pad_sub = nullptr; - cl_mem b_buf = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - if (N_pad == N) { - b_buf = b_src_sub; - } else { - size_t padded_bytes = (size_t)K * N_pad * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); - region.origin = 0; - region.size = padded_bytes; - CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const float b_pad_zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), - 0, padded_bytes, 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - b_buf = b_pad_sub; - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N_pad; - img_desc.buffer = b_buf; - cl_mem b_img_a7; - CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - const int c_offset_for_kernel = (int)offsetd; - - int line_stride_B = K * (int)sizeof(float); - int line_stride_C = M * (int)sizeof(float); - - kernel = backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin; - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 4 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_y = ((m_tiles + 1) / 2) * 2; - size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img_a7)); - if (b_src_sub) { - CL_CHECK(clReleaseMemObject(b_src_sub)); - } - if (b_pad_sub) { - CL_CHECK(clReleaseMemObject(b_pad_sub)); - } - return; - } - - cl_mem b_sub_buf = nullptr; - cl_mem b_padded = nullptr; - cl_mem b_buf = nullptr; - if (N_pad == N) { - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - b_buf = b_sub_buf; - } else { - CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, (size_t)K * N_pad * sizeof(float), NULL, &err), err)); - const float zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - b_buf = b_padded; - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N_pad; - img_desc.buffer = b_buf; - cl_mem b_img; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - cl_mem d_sub_buf; - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub_buf; - cl_mem d_img; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 2 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img)); - if (b_sub_buf) { - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } - if (b_padded) { - CL_CHECK(clReleaseMemObject(b_padded)); - } - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - } -} -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -static void ggml_cl_mul_mat_q4_k_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q4_K * extra0_q4_k = (ggml_tensor_extra_cl_q4_K *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - cl_uchar mask_d6 = 0x3F; - cl_uchar mask_d4 = 0x0F; - cl_uchar mask_hi2 = 0xC0; - - // Multi-column verify GEMV - static const bool q4k_mc3 = (getenv("GGML_OPENCL_Q4_K_MC3") != nullptr); - const bool use_mc3 = q4k_mc3 && (ne1 == 3) && (ne01 < 32768); - - const bool use_bin = use_q4_k_bin_kernels(backend_ctx, src0); - - if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q4_k_f32_coopmat, - { extra0_q4_k->q, extra0_q4_k->s, extra0_q4_k->d, extra0_q4_k->dm }, src1, dst, K, M, N)) { - return; - } - - if (use_bin) { - if (use_mc3) { - static bool warned = false; - if (!warned) { - GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q4_K_MC3 is bypassed by Q4_K binary kernels\n"); - warned = true; - } - } - ggml_cl_mul_mat_q4_k_f32_adreno_ila(backend, src0, src1, dst); - return; - } - - if (ne1 == 1 || use_mc3) { - cl_mem q_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - const bool use_tiled = !use_mc3 && use_q4k_tiled(backend_ctx, src0); - - // image for q (not needed for the tiled path, which reads __global) - if (!use_tiled) { - img_fmt = { CL_R, CL_UNSIGNED_INT32}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_q4_k->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - } - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // 4-output-per-WI o4 variant for the long-vocab lm_head/embed GEMV - // (ne01 = vocab ~256K on Gemma): shares one activation read across 4 - // output rows. Gated to large ne01 (lm_head/embed). Default on; opt-out - // GGML_OPENCL_Q4K_GEMV_O4=0. (Skipped when mc3 handles the ne1==3 verify.) - static const bool q4k_o4_env = []{ - const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_O4"); - return !e || e[0] == '\0' || e[0] != '0'; - }(); - const bool use_q4k_o4 = !use_tiled && !use_mc3 && q4k_o4_env && (ne01 % 4 == 0) && (ne01 >= 32768); - // Split-K across workgroups for small-M decode GEMVs. A single-token GEMV - // makes only CEIL_DIV(M/2,64) workgroups; even with the wide intra-WG split - // (16 subgroups) those all land on ONE CU, so small-M matmuls under-fill the - // 16 CUs and their bandwidth falls well short of what the large-M FFN matmuls - // reach. Adding a `ksplit` second grid dim that spreads K across WGs (+ a - // reduce pass) fills the CUs. Gate is M<=2560: the tiny M<=1024 ones only - // break even (the reduce dispatch eats the kernel win), but the big-K M=2560 - // cases (ffn_down, attn_output) make the per-call win dwarf the reduce, and - // are byte-identical. ffn_gate/up (large M) fill the CUs already and are excluded. - // - // DEVICE-GATED. Split-K buys GPU time by spending an extra kernel LAUNCH (the - // reduce), so it only pays where launches are cheap. That is a per-device - // property and it does not travel from the X2-90 this was tuned on. Measured - // with one binary, env A/B (tg32, GGML_OPENCL_Q4K_GEMV_SPLITK=0/1): - // - // X2-90 +3.36% gemma-4 E4B (the number this gate was built on) - // 840 -1.3% Qwen3.5-4B-Q4_K_M 14.00 -> 13.85 - // 850 -20.0% Qwen3-1.7B-Q4_K_M 6.97 -> 5.58 (6 interleaved reps) - // - // The kernel is not the problem. On the 850 split-K makes the GPU strictly - // faster -- total busy 537 -> 485 ms, this GEMV 43.7 -> 34.0 us/call (-22%) -- - // and still costs a fifth of decode, because the +3696 reduce dispatches cost - // ~550 us of HOST round-trip each against 2.7 us of GPU work (~200x; that part - // is ~95% host-bound at decode). The 840 pays the same tax at ~42 us/dispatch. - // Break-even needs launch cost below the ~9.7 us/call the split actually saves, - // so this is not a "the 850 is slow" adjustment that a faster part would fix -- - // the 840 is 13x cheaper per launch and still loses. - // - // Enabled where it is measured to win, i.e. X2E only. The X1-85 was measured - // afterwards and is NOT a win either: Qwen3.5-4B-Q4_K_M tg32, split-K off - // 17.98/18.10/18.19 vs on 18.03/17.91/17.97 = -0.7%, so X1E stays excluded on - // evidence rather than on absence of it. Do not widen this without a NEW - // measurement. The env still forces either way so every device stays measurable. - static const bool splitk_env_set = []{ - const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_SPLITK"); - return e && e[0] != '\0'; - }(); - static const bool splitk_env_on = []{ - const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_SPLITK"); - return !(e && e[0] == '0'); - }(); - const bool splitk_wg_env = splitk_env_set - ? splitk_env_on - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - // Gate: small-M decode GEMVs that under-fill the 16 CUs even with the wide - // intra-WG split (all 16 subgroups land on one CU). M<=2560 covers Kcur/Vcur - // (M=1024), Qcur (2048), attn_output + ffn_down (2560). The tiny ones - // (M<=1024) only break even (reduce dispatch eats the kernel win), but the - // big-K M=2560 cases (ffn_down K=10240 @182us, attn_output @42us) have a - // large per-call win that dwarfs the ~5us reduce, so extending to 2560 nets - // positive end-to-end. ffn_gate/up (M=10240) already fill the CUs -> excluded. - const bool use_splitk = splitk_wg_env && !use_tiled && !use_q4k_o4 && !use_mc3 && ne01 <= 2560; - - if (use_splitk) { - const int nsg = 8; - const int ksplit = (ne01 <= 512) ? 8 : 4; // -> ~32 total WGs - const size_t gx = (size_t)CEIL_DIV(ne01/2, 64) * 64; - - backend_ctx->prealloc_splitk_partial.allocate( - backend_ctx->context, (size_t)ksplit * ne01 * sizeof(float)); - cl_mem partial = backend_ctx->prealloc_splitk_partial.buffer; - - cl_kernel ks = backend_ctx->kernel_gemv_noshuffle_q4_k_f32_splitk; - CL_CHECK(clSetKernelArg(ks, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(ks, 1, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(ks, 2, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(ks, 3, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(ks, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(ks, 5, sizeof(cl_mem), &partial)); - CL_CHECK(clSetKernelArg(ks, 6, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(ks, 7, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(ks, 8, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(ks, 9, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(ks, 10, sizeof(cl_uchar), &mask_hi2)); - size_t lsk[3] = {64, (size_t)nsg, 1}; - size_t gsk[3] = {gx, (size_t)(nsg * ksplit), 1}; - backend_ctx->enqueue_ndrange_kernel(ks, 3, gsk, lsk, dst); - - cl_kernel kr = backend_ctx->kernel_gemv_splitk_reduce_f32; - CL_CHECK(clSetKernelArg(kr, 0, sizeof(cl_mem), &partial)); - CL_CHECK(clSetKernelArg(kr, 1, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kr, 2, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kr, 3, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kr, 4, sizeof(cl_int), &ksplit)); - size_t lr[3] = {64, 1, 1}; - size_t gr[3] = {(size_t)CEIL_DIV(ne01, 64) * 64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kr, 3, gr, lr, dst); - - if (q_img) CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - return; - } - - kernel = use_mc3 ? backend_ctx->kernel_gemv_noshuffle_q4_k_f32_mc3 - : use_tiled ? backend_ctx->kernel_gemv_noshuffle_q4_k_f32_tiled - : use_q4k_o4 ? backend_ctx->kernel_gemv_noshuffle_q4_k_f32_o4 - : backend_ctx->kernel_gemv_noshuffle_q4_k_f32; - - if (use_tiled) { - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); - } else { - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_uchar), &mask_hi2)); - } - - // Wide K-split for the decode GEMV: the default 4-subgroup K-split leaves - // each Adreno SP with only ~4 waves, too few to hide LPDDR weight-load - // latency, so even the large FFN matmuls run well below the achievable - // bandwidth. Widen to 16 subgroups/WG (= the 1024-lane Adreno WG max) so - // each SP holds enough in-flight memory requests. Prefill is unaffected (the - // GEMM path is separate) and coherence-identical (greedy output unchanged). - // Applies to the plain base - // GEMV only; tiled/o4/mc3 keep 4 (their reductions are hard-coded to 4). - // Layout-safe: the base kernel derives its K-split from get_local_size(1) - // and the packed block stride is a physical constant (independent of it). - // Opt-out: GGML_OPENCL_Q4K_GEMV_WIDE=0. - static const bool splitk_wide_env = []{ - const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_WIDE"); - return !e || e[0] == '\0' || e[0] != '0'; - }(); - const bool splitk_wide = splitk_wide_env && !use_tiled && !use_q4k_o4 && !use_mc3; - size_t nsg_y = splitk_wide ? 16 : 4; - // Cap the wide K-split by the kernel's real max WG. X1-class drivers cap - // this GEMV at 768 (< 64*16 = 1024), so an uncapped lws aborts the - // dispatch with CL_INVALID_WORK_GROUP_SIZE (-54) and breaks ALL q4_K - // decode for M>2560. nsg_y is a pure K-split (the base kernel reads it - // from get_local_size(1); the packed block stride is a physical constant), - // so halving it stays coherent — just a narrower split. X2 keeps 16 - // (maxwg 1024); X1 falls to 8. - if (splitk_wide) { - const size_t maxwg = backend_ctx->get_kernel_workgroup_size(kernel); - while (nsg_y > 4 && 64 * nsg_y > maxwg) { nsg_y >>= 1; } - } - size_t local_work_size[3] = {64, nsg_y, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(use_tiled ? ne01 : (use_q4k_o4 ? ne01/4 : ne01/2), 64)*64, nsg_y, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - if (q_img) CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // Only the tiled kernels can read the tiled layout (use_q4k_tiled). - if (use_q4k_tiled(backend_ctx, src0)) { - const size_t n_blocks = (size_t)N * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tbq = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tbq)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_kernel dk = backend_ctx->kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a; - CL_CHECK(clSetKernelArg(dk, 0, sizeof(cl_mem), &extra0_q4_k->q)); - CL_CHECK(clSetKernelArg(dk, 1, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(dk, 2, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(dk, 3, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(dk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, 9, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(dk, 10, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(dk, 11, sizeof(cl_int), &ne1)); - - const int WROWS_D = 4 * 64; - const int BN_DP = 8; - size_t dlocal[3] = {64, 4, 1}; - size_t dglobal[3] = {(size_t)CEIL_DIV(ne01, WROWS_D) * 64, 4, (size_t)CEIL_DIV(ne1, BN_DP)}; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dglobal, dlocal, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - // CoopK handles without _bin use the same untiled weight layout as gemm_noshuffle_q4_k_f32. - // Activations use K-major Q8_1 SoA (K contiguous). - if (ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q4_k) - && backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4 != nullptr - && ((N <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c2 - : backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4) != nullptr) { - const int cols = (N <= 2) ? 2 : 4; - const size_t size_qa = (size_t)cols * K * sizeof(cl_char); - const size_t n_blocks_padded = (size_t)cols * (K / 32); - const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; - const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; - backend_ctx->prealloc_moe_qa.allocate(context, size_qa); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); - if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { - const cl_char z8 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, - &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); - } - if (backend_ctx->prealloc_moe_da.size != size_da_prev) { - const cl_half z16 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); - } - - cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); - cl_kernel kernel_quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); - size_t local_work_size_quant[1] = { 64 }; - size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); - - cl_kernel kernel_coopk = (N <= 2) ? backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c2 - : backend_ctx->kernel_gemm_coopk_q4_k_q8_1_dp4a_c4; - const cl_uchar mask_d6 = 0x3F, mask_d4 = 0x0F, mask_hi2 = 0xC0; - const cl_int n_padded = cols; - CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q4_k->q)); - CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(kernel_coopk, 10, sizeof(cl_int), &n_padded)); - CL_CHECK(clSetKernelArg(kernel_coopk, 11, sizeof(cl_int), &K)); - CL_CHECK(clSetKernelArg(kernel_coopk, 12, sizeof(cl_int), &N)); - CL_CHECK(clSetKernelArg(kernel_coopk, 13, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(kernel_coopk, 14, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(kernel_coopk, 15, sizeof(cl_uchar), &mask_hi2)); - - const size_t nsg = (size_t)backend_ctx->nsg_coopk_dp4a_q4_k; - size_t local_work_size[3] = { 64, nsg, 1 }; - size_t global_work_size[3] = { (size_t)(M / backend_ctx->rows_coopk_dp4a_q4_k), nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // transpose activations - int height_B = N/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = K/4; - int padded_height_B = (N + padding)/4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = { 1, 16 }; - size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // dp4a (int8) dense prefill GEMM and weight via texture - static const char * q4k_dense_dp4a_env = getenv("GGML_OPENCL_Q4K_DENSE_DP4A"); - static const char * q4k_dense_wimg_env = getenv("GGML_OPENCL_Q4K_DENSE_DP4A_WIMG"); - - const bool q4k_dense_wimg_on = q4k_dense_wimg_env && (atoi(q4k_dense_wimg_env) != 0); - bool q4k_dense_dp4a_on = q4k_dense_wimg_on - ? true - : q4k_dense_dp4a_env - ? (atoi(q4k_dense_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - - // dp4 has to be available - q4k_dense_dp4a_on = backend_ctx->has_integer_dot && q4k_dense_dp4a_on; - - // Min N for the dp4a prefill GEMM, default 9, i.e., ne1 > 8 - static const char * q4k_dp4a_minn_env = getenv("GGML_OPENCL_Q4K_DP4A_MINN"); - const int q4k_dp4a_minn = q4k_dp4a_minn_env ? atoi(q4k_dp4a_minn_env) : 9; - - if (q4k_dense_dp4a_on && N >= q4k_dp4a_minn && (K % 32 == 0) && (M % 64 == 0)) { - const size_t n_blocks = (size_t)N * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - // check if weights go through texture - cl_mem q4k_q_img = nullptr; - bool use_wimg = q4k_dense_wimg_on; - if (use_wimg) { - const size_t tex = (size_t)M * (size_t)K / 8; // uint32 texels = bytes/4 - if (tex == 0 || tex > backend_ctx->image_max_buffer_size) { - use_wimg = false; - } else { - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = tex; - img_desc.buffer = extra0_q4_k->q; - q4k_q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err); - if (err != CL_SUCCESS || q4k_q_img == nullptr) { - use_wimg = false; - q4k_q_img = nullptr; - } - } - } - - const bool use_narrow = backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow != nullptr - && N <= backend_ctx->max_n_dp4a_narrow_q4_k; - static const char * q4_k_act_vload4_env = getenv("GGML_OPENCL_Q4_K_DP4A_ACT_VLOAD4"); - const bool q4_k_act_vload4_on = q4_k_act_vload4_env == nullptr || atoi(q4_k_act_vload4_env) != 0; - cl_kernel dk = use_narrow - ? (use_wimg ? backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow_wimg - : backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow) - : use_wimg - ? backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg - : q4_k_act_vload4_on - ? backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4 - : backend_ctx->kernel_gemm_noshuffle_q4_k_q8_1_dp4a; - int ai = 0; - if (use_wimg) { - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &q4k_q_img)); - } else { - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->q)); - } - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_hi2)); - const int tile_n = use_narrow ? backend_ctx->tile_n_dp4a_narrow_q4_k : backend_ctx->tile_n_dp4a_q4_k; - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, tile_n) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - if (q4k_q_img != nullptr) { - CL_CHECK(clReleaseMemObject(q4k_q_img)); - } - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - return; - } - - // gemm - // Small-batch (medium n_q) occupancy fix: at ne1<=8 the 2x8 grid is - // (1, ceil(M/2)) -> ~M/256 workgroups, which under-occupies the SP and - // makes the GEMM much slower than the ne1==1 GEMV at the same weight - // traffic. The _r1 (1-row) kernel doubles the M-axis workgroup count - // and removes the accumulator spill. Opt-in via env while validating. - static const bool q4k_gemm_r1 = (getenv("GGML_OPENCL_Q4K_GEMM_R1") != nullptr); - static const bool q4k_gemm_kimg = (getenv("GGML_OPENCL_Q4K_GEMM_KIMG") != nullptr); - // Cooperative-K (intra-WG K-split + reduction) for the small-batch - // (n_q in [2..8]) path: DEFAULT ON, opt out with GGML_OPENCL_Q4K_GEMM_COK=0. - // Byte-identical greedy output; large-batch (ne1>8) untouched. - static const char * q4k_cok_env = getenv("GGML_OPENCL_Q4K_GEMM_COK"); - static const bool q4k_gemm_cok = (q4k_cok_env == nullptr) || (atoi(q4k_cok_env) != 0); - const bool use_cok = q4k_gemm_cok && (ne1 <= 8); - const bool use_r1 = !use_cok && q4k_gemm_r1 && (ne1 <= 8); - // Weights-as-image (L1/TPL1) for the small-batch weight-read-bound path. - const bool use_kimg = !use_cok && !use_r1 && q4k_gemm_kimg && (ne1 <= 8); - - cl_mem q_img = nullptr; - if (use_kimg) { - img_fmt = { CL_R, CL_UNSIGNED_INT32 }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_q4_k->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - } - - kernel = use_cok ? backend_ctx->kernel_gemm_noshuffle_q4_k_f32_cok - : use_r1 ? backend_ctx->kernel_gemm_noshuffle_q4_k_f32_r1 - : use_kimg ? backend_ctx->kernel_gemm_noshuffle_q4_k_f32_kimg - : backend_ctx->kernel_gemm_noshuffle_q4_k_f32; - int padded_N = N + padding; - - if (use_kimg) { - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - } else { - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q)); - } - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->s)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_uchar), &mask_hi2)); - - size_t global_work_size[3]; - size_t local_work_size[3]; - if (use_cok) { - // (COK_SG lanes x COK_NSG subgroups): one row per lane, K split - // across the COK_NSG subgroups. ne01 is a multiple of 64. - global_work_size[0] = (size_t)ne01; // rows - global_work_size[1] = 8; // COK_NSG - global_work_size[2] = 1; - local_work_size[0] = 64; // COK_SG - local_work_size[1] = 8; // COK_NSG - local_work_size[2] = 1; - } else if (use_r1) { - // 1 row per WI (opt-in occupancy experiment). - global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); - global_work_size[1] = (size_t)ne01; - global_work_size[2] = 1; - local_work_size[0] = 1; - local_work_size[1] = 128; - local_work_size[2] = 1; - } else if (use_kimg) { - // kimg is a 2-row tile (opt-in weights-as-image experiment). - global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); - global_work_size[1] = (size_t)CEIL_DIV(ne01, 2); - global_work_size[2] = 1; - local_work_size[0] = 1; - local_work_size[1] = 128; - local_work_size[2] = 1; - } else { - // Default: x2-unified base kernel is the 4-row (gx<<2) tile. - global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); - global_work_size[1] = (size_t)CEIL_DIV(ne01, 4); - global_work_size[2] = 1; - local_work_size[0] = 1; - local_work_size[1] = 128; - local_work_size[2] = 1; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - if (q_img) CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static void ggml_cl_mul_mat_q6_K_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, - const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_buffer_region region; - cl_image_format img_fmt; - cl_image_desc img_desc; - - const int M = ne01; - const int N = ne1; - const int K = ne00; - - if (backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 != nullptr && - N >= 2 && N <= 8 && M > 0 && K > 0 && M % 4 == 0 && K % 256 == 0 && - src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && - K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && - src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && - src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && - ggml_is_contiguous(src1) && ggml_is_contiguous(dst) - ) { - const int kb = K / 32; - const size_t qa_bytes = (size_t)8 * K; - const size_t ds_bytes = (size_t)24 * kb * sizeof(cl_half); - - backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); - backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); - - if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, - backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && - ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, - backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) - ) { - const int n_blocks = N * kb; - - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1_k4h; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); - CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); - - size_t quant_local[] = {64}; - size_t quant_global[] = {(size_t)8 * kb}; - backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); - - int ksplit = ggml_cl_coopk_ksplit(backend_ctx, CEIL_DIV(M / 4, 64), kb); - if (backend_ctx->kernel_gemv_splitk_reduce_f32 == nullptr) { - ksplit = 1; - } - - cl_mem out = extrad->data_device; - cl_ulong out_offset = offsetd; - - if (ksplit > 1) { - backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float)); - out = backend_ctx->prealloc_splitk_partial.buffer; - out_offset = 0; - } - - const cl_uchar mask_c0 = 0xC0; - - const size_t nsg = backend_ctx->nsg_coopk_dp4a_q6_k_bin_c8; - cl_kernel gemm = backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8; - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_c0)); - CL_CHECK(clSetKernelArg(gemm, 12, sizeof(int), &ksplit)); - - size_t local[] = {64, nsg, 1}; - size_t global[] = {(size_t)CEIL_DIV(M / 4, 64) * 64, nsg * ksplit, 1}; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - - if (ksplit > 1) { - const int rows = M * N; - cl_kernel reduce = backend_ctx->kernel_gemv_splitk_reduce_f32; - CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); - CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); - CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); - size_t reduce_local[] = {64}; - size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64}; - backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); - } - return; - } - } - - if (ne1 == 1) { - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_RGBA, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemv_noshuffle_q6_k_f32_32b_trans; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh_img)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); - - size_t local_work_size[3] = { 64, 8, 1 }; - size_t global_work_size[3] = { (size_t)ne01, 8, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } else { - const int gemm_tile_n = 64; - int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; - - const bool have_a8 = backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin != nullptr; - - static const char * q6_k_bin_dp4a_env = getenv("GGML_OPENCL_Q6_K_BIN_DP4A"); - bool q6_k_bin_dp4a_on = q6_k_bin_dp4a_env - ? (atoi(q6_k_bin_dp4a_env) != 0) - : true; - // dot prod has to be available - q6_k_bin_dp4a_on = backend_ctx->has_integer_dot && q6_k_bin_dp4a_on; - - if (q6_k_bin_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin) { - const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; - const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); - - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_mem b_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_int tb = (cl_int)((size_t)N * (K / 32)); - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_mem d_sub = nullptr; - cl_mem d_img = nullptr; - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin; - - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->ql_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 1, 1 }; - size_t global_work_size[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub)); - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub)); - return; - } - - if (!have_a8) { - cl_mem b_src_sub = nullptr; - cl_mem b_pad_sub = nullptr; - cl_mem b_buf = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - if (N_pad == N) { - b_buf = b_src_sub; - } else { - size_t padded_bytes = (size_t)K * N_pad * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); - region.origin = 0; - region.size = padded_bytes; - CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - const float b_pad_zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), - 0, padded_bytes, 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - b_buf = b_pad_sub; - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N_pad; - img_desc.buffer = b_buf; - cl_mem b_img_a7; - CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - const int c_offset_for_kernel = (int)offsetd; - - int line_stride_B = K * (int)sizeof(float); - int line_stride_C = M * (int)sizeof(float); - - kernel = backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin; - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->ql_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 4 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_y = ((m_tiles + 1) / 2) * 2; - size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img_a7)); - if (b_src_sub) { - CL_CHECK(clReleaseMemObject(b_src_sub)); - } - if (b_pad_sub) { - CL_CHECK(clReleaseMemObject(b_pad_sub)); - } - return; - } - - cl_mem b_sub_buf = nullptr; - cl_mem b_padded = nullptr; - cl_mem b_buf = nullptr; - if (N_pad == N) { - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - b_buf = b_sub_buf; - } else { - CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, (size_t)K * N_pad * sizeof(float), NULL, &err), err)); - const float zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - b_buf = b_padded; - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N_pad; - img_desc.buffer = b_buf; - cl_mem b_img; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - cl_mem d_sub_buf; - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub_buf; - cl_mem d_img; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 2 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img)); - if (b_sub_buf) { - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } - if (b_padded) { - CL_CHECK(clReleaseMemObject(b_padded)); - } - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - } -} -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -static void ggml_cl_mul_mat_q6_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_buffer_region region; - cl_image_format img_fmt; - cl_image_desc img_desc; - - // Multi-column verify GEMV - static const bool q6k_mc3 = (getenv("GGML_OPENCL_Q6_K_MC3") != nullptr); - const bool use_q6k_mc3 = q6k_mc3 && (ne1 == 3) && (ne01 < 32768); - // Multi-column tiled vocab GEMV for verify - // streams the large lm_head weight once across the verify columns - static const char * q6k_tiled_mc_env = getenv("GGML_OPENCL_Q6_K_TILED_MC"); - const bool q6k_tiled_mc = q6k_tiled_mc_env ? atoi(q6k_tiled_mc_env) != 0 - : (q6k_mc3 || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - const bool use_q6k_tiled_mc = q6k_tiled_mc && (ne1 >= 2 && ne1 <= 4) && (ne01 >= 32768) && use_q6k_tiled(backend_ctx, src0); - - const bool use_bin = use_q6_k_bin_kernels(backend_ctx, src0); - - if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q6_k_f32_coopmat, - { extra0_q6_K->ql, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, src1, dst, ne00, ne01, ne1)) { - return; - } - - if (use_bin) { - if (use_q6k_mc3 || use_q6k_tiled_mc) { - static bool warned = false; - if (!warned) { - GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q6_K_MC3 is bypassed by Q6_K binary kernels\n"); - warned = true; - } - } - // This bin layout is not supported by CoopK. - ggml_cl_mul_mat_q6_K_f32_adreno_ila(backend, src0, src1, dst); - return; - } - - if (ne1 == 1 || use_q6k_mc3 || use_q6k_tiled_mc) { - cl_mem ql_img = nullptr; - cl_mem qh_img = nullptr; - cl_mem b_sub_buffer = nullptr; - cl_mem b_img = nullptr; - - // o4 = 4-output-per-WI variant for long-vocab lm_head/embed; gated to - // ne01 >= 32768 so per-layer q6_K (ne01=hidden 2-8K) keeps the 2-output - // kernel (o4 regresses there). o4_global reads the weights from __global - // coalesced instead of image1d_buffer -- the texture cache caps the - // read-once-per-token lm_head bandwidth, while __global reaches the higher - // rate the rest of the model gets. Both default ON; opt out via - // GGML_OPENCL_Q6K_GEMV_O4 / GGML_OPENCL_Q6K_GEMV_O4_GLOBAL = 0. - static const bool gemv_o4_env = []{ - const char * e = std::getenv("GGML_OPENCL_Q6K_GEMV_O4"); - return !e || e[0] == '\0' || e[0] != '0'; - }(); - static const bool o4_global_env = []{ - const char * e = std::getenv("GGML_OPENCL_Q6K_GEMV_O4_GLOBAL"); - return !e || e[0] == '\0' || e[0] != '0'; - }(); - const bool use_tiled = !use_q6k_mc3 && use_q6k_tiled(backend_ctx, src0); - const bool use_o4 = !use_tiled && !use_q6k_mc3 && gemv_o4_env && (ne01 % 4 == 0) && (ne01 >= 32768); - const bool use_o4_global = use_o4 && o4_global_env; - - // ql/qh image views are only needed when NOT reading weights from global. - if (!use_o4_global && !use_tiled) { - // image for ql - img_fmt.image_channel_order = CL_R; - img_fmt.image_channel_data_type = CL_FLOAT; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = ne01 * ne00 / 8; - img_desc.buffer = extra0_q6_K->ql; - CL_CHECK((ql_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // image for qh - img_fmt.image_channel_order = CL_R; - img_fmt.image_channel_data_type = CL_HALF_FLOAT; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = ne01 * ne00 / 8; - img_desc.buffer = extra0_q6_K->qh; - CL_CHECK((qh_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - } - - region.origin = offset1; - region.size = ne00 * ne1 * sizeof(float); - CL_CHECK((b_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt.image_channel_order = CL_RGBA; - img_fmt.image_channel_data_type = CL_FLOAT; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = ne00 * ne1 / 4; - img_desc.buffer = b_sub_buffer; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = use_q6k_mc3 ? backend_ctx->kernel_gemv_noshuffle_q6_K_f32_mc3 - : use_q6k_tiled_mc ? backend_ctx->kernel_gemv_noshuffle_q6_K_f32_tiled_mc3 - : use_tiled ? backend_ctx->kernel_gemv_noshuffle_q6_K_f32_tiled - : use_o4_global ? backend_ctx->kernel_gemv_noshuffle_q6_K_f32_o4_global - : use_o4 ? backend_ctx->kernel_gemv_noshuffle_q6_K_f32_o4 - : backend_ctx->kernel_gemv_noshuffle_q6_K_f32; - - if (use_o4_global || use_tiled) { - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - } else { - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &ql_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh_img)); - } - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); - if (use_q6k_tiled_mc) { - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne1)); - } - - const size_t gws_x = use_tiled - ? (size_t) CEIL_DIV(ne01, 64) * 64 - : use_o4 - ? (size_t) CEIL_DIV(ne01/4, 64) * 64 - : (size_t) CEIL_DIV(ne01/2, 64) * 64; - size_t local_work_size[3] = {64, 4, 1}; - size_t global_work_size[3] = {gws_x, 4, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - if (ql_img) CL_CHECK(clReleaseMemObject(ql_img)); - if (qh_img) CL_CHECK(clReleaseMemObject(qh_img)); - CL_CHECK(clReleaseMemObject(b_sub_buffer)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - // Tiled-layout batched GEMM. When the weight was converted to the 64-row - // tiled canonical layout (use_q6k_tiled — the default for lm_head/embed), - // the plain noshuffle GEMM below reads it as plain-transposed and produces - // garbage. Use the batched GEMM that matches the decode tiled GEMV's - // layout; it reads the f32 activation directly (column-major, no transpose). - if (use_q6k_tiled(backend_ctx, src0)) { - cl_mem b_sub_buf_t = nullptr; - cl_mem b_img_t = nullptr; - - region.origin = offset1; - region.size = ne00 * ne1 * sizeof(float); - CL_CHECK((b_sub_buf_t = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt.image_channel_order = CL_RGBA; - img_fmt.image_channel_data_type = CL_FLOAT; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = ne00 * ne1 / 4; - img_desc.buffer = b_sub_buf_t; - CL_CHECK((b_img_t = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - cl_kernel kt = backend_ctx->kernel_gemm_noshuffle_q6_K_f32_tiled; - CL_CHECK(clSetKernelArg(kt, 0, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(kt, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kt, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kt, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kt, 4, sizeof(cl_mem), &b_img_t)); - CL_CHECK(clSetKernelArg(kt, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kt, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kt, 7, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kt, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kt, 9, sizeof(int), &ne1)); - - // Must match the kernel: NTILES=4 64-row tiles per work-group (256 rows), - // BN=8 output columns per work-group. - const int BN_T = 16; - const int WROWS = 4 * 64; // NTILES * TILE_ROWS - size_t local_work_size[3] = {64, 4, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01, WROWS) * 64, 4, (size_t)CEIL_DIV(ne1, BN_T)}; - backend_ctx->enqueue_ndrange_kernel(kt, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img_t)); - CL_CHECK(clReleaseMemObject(b_sub_buf_t)); - return; - } - - cl_mem b_sub_buf; - cl_mem b_buf_trans; - cl_mem b_img; - cl_mem b_img_trans; - - // subbuffer for activation - region.origin = offset1; - region.size = ne00 * ne1 * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // CoopK uses the same untiled weight layout as gemm_noshuffle_q6_K_f32, with K-major Q8_1 activations (K contiguous). - // Keep output and embedding weights on the existing path for logit stability. - if (ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->rows_coopk_dp4a_q6_k) - && backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4 != nullptr - && strncmp(src0->name, "output", 6) != 0 - && strncmp(src0->name, "token_embd", 10) != 0 - && ((ne1 <= 2) ? backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 - : backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4) != nullptr) { - const int N = (int)ne1, K = (int)ne00; - const int cols = (N <= 2) ? 2 : 4; - const size_t n_blocks_padded = (size_t)cols * (K / 32); - const size_t size_qa = (size_t)cols * K * sizeof(cl_char); - const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; - const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; - backend_ctx->prealloc_moe_qa.allocate(context, size_qa); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); - if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { - const cl_char z8 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, - &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); - } - if (backend_ctx->prealloc_moe_da.size != size_da_prev) { - const cl_half z16 = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, - &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); - } - - cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); - cl_kernel kernel_quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); - size_t local_work_size_quant[1] = { 64 }; - size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); - - cl_kernel kernel_coopk = (N <= 2) ? backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 - : backend_ctx->kernel_gemm_coopk_q6_k_q8_1_dp4a_c4; - const cl_ushort mask_f000 = 0xF000; - const cl_uchar mask_c0 = 0xC0; - const cl_int n_padded = cols; - const cl_int m = (cl_int)ne01, k = (cl_int)ne00, n = (cl_int)ne1; - CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_int), &m)); - CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &n_padded)); - CL_CHECK(clSetKernelArg(kernel_coopk, 10, sizeof(cl_int), &k)); - CL_CHECK(clSetKernelArg(kernel_coopk, 11, sizeof(cl_int), &n)); - CL_CHECK(clSetKernelArg(kernel_coopk, 12, sizeof(cl_ushort), &mask_f000)); - CL_CHECK(clSetKernelArg(kernel_coopk, 13, sizeof(cl_uchar), &mask_c0)); - - const size_t nsg = (size_t)backend_ctx->nsg_coopk_dp4a_q6_k; - size_t local_work_size[3] = { 64, nsg, 1 }; - size_t global_work_size[3] = { (size_t)(ne01 / backend_ctx->rows_coopk_dp4a_q6_k), nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - // dp4a (int8) dense q6_K prefill GEMM - static const char * q6k_dense_dp4a_env = getenv("GGML_OPENCL_Q6K_DENSE_DP4A"); - bool q6k_dense_dp4a_on = (q6k_dense_dp4a_env != nullptr) - ? (atoi(q6k_dense_dp4a_env) != 0) - : (backend_ctx->adreno_gen != ADRENO_GPU_GEN::X1E); - // dot prod has to be available - q6k_dense_dp4a_on = backend_ctx->has_integer_dot && q6k_dense_dp4a_on; - - const bool is_output_w_dp4a = strncmp(src0->name, "output", 6) == 0 || - strncmp(src0->name, "token_embd", 10) == 0; - - if (q6k_dense_dp4a_on && !is_output_w_dp4a && ne1 > 8 && (ne00 % 32 == 0) && (ne01 % 64 == 0)) { - const int M = ne01, N = ne1, K = ne00; - const size_t n_blocks = (size_t)N * (K / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - static const char * q6_k_act_vload4_env = getenv("GGML_OPENCL_Q6_K_DP4A_ACT_VLOAD4"); - const bool q6_k_act_vload4_on = q6_k_act_vload4_env == nullptr || atoi(q6_k_act_vload4_env) != 0; - cl_kernel dk = q6_k_act_vload4_on - ? backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4 - : backend_ctx->kernel_gemm_noshuffle_q6_k_q8_1_dp4a; - int ai = 0; - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - return; - } - - // image for activation - img_fmt.image_channel_order = CL_RGBA; - img_fmt.image_channel_data_type = CL_FLOAT; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = ne00 * ne1 / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = ne1 % 8; - int padding = 0; - if (extra_elements > 0){ - padding = 8 - extra_elements; - } - - // subbuffer for transposed activation - region.origin = 0; - region.size = ne00 * (ne1 + padding) * sizeof(float)/2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activation - img_fmt.image_channel_order = CL_RGBA; - img_fmt.image_channel_data_type = CL_HALF_FLOAT; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = ne00 * (ne1 + padding) / 4; - img_desc.buffer = b_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // transpose activation - int height_B = ne1/4; - if (height_B == 0) { - height_B = 1; - } - int width_B = ne00/4; - int padded_height_B = (ne1 + padding) / 4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_size_t[2] = { 1, 16 }; - size_t global_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_size_t, local_size_t, dst); - - // gemm - // Cooperative-K small-batch (n_q in [2..8]) path: intra-WG K-split, - // mirrors the q4_K _cok path (batched serving). OPT-IN - // (GGML_OPENCL_Q6K_GEMM_COK=1), DEFAULT OFF: q6_K is the tied lm_head/ - // output projection, so the K-reassociation perturbs final logits and - // greedy is NOT byte-identical (op-tests pass, output coherent, but not - // bit-exact). It is also NEUTRAL on end-to-end MTP (q4_K cok already - // captured that; the MTP bottleneck moved off the GEMMs). Keep opt-in - // for batched serving until PPL-validated on a non-GDN q6_K model. - static const char * q6k_cok_env = getenv("GGML_OPENCL_Q6K_GEMM_COK"); - static const bool q6k_gemm_cok = (q6k_cok_env != nullptr) && (atoi(q6k_cok_env) != 0); - const bool use_q6k_cok = q6k_gemm_cok && (ne1 <= 8); - kernel = use_q6k_cok ? backend_ctx->kernel_gemm_noshuffle_q6_K_f32_cok - : backend_ctx->kernel_gemm_noshuffle_q6_K_f32; - int padded_N = ne1 + padding; - - cl_ushort mask_f000 = 0xF000; - cl_uchar mask_c0 = 0xC0; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ushort),&mask_f000)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_c0)); - - size_t global_work_size[3]; - size_t local_work_size[3]; - if (use_q6k_cok) { - global_work_size[0] = (size_t)ne01; // rows (1 per lane) - global_work_size[1] = 8; // COK_NSG - global_work_size[2] = 1; - local_work_size[0] = 64; // COK_SG - local_work_size[1] = 8; // COK_NSG - local_work_size[2] = 1; - } else { - global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); - global_work_size[1] = (size_t)CEIL_DIV(ne01, 4); - global_work_size[2] = 1; - local_work_size[0] = 2; - local_work_size[1] = 128; - local_work_size[2] = 1; - } - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static void ggml_cl_mul_mat_q5_K_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, - const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl_q5_K * extra0_q5_k = (ggml_tensor_extra_cl_q5_K *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_buffer_region region; - cl_image_format img_fmt; - cl_image_desc img_desc; - - const int M = ne01; - const int N = ne1; - const int K = ne00; - - if (ne1 == 1) { - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_RGBA, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemv_noshuffle_q5_k_f32_32b_trans; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_k->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne01)); - - size_t local_work_size[3] = { 64, 8, 1 }; - size_t global_work_size[3] = { (size_t)ne01, 8, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } else { - static const char * q5_k_bin_dp4a_env = getenv("GGML_OPENCL_Q5_K_BIN_DP4A"); - bool q5_k_bin_dp4a_on = q5_k_bin_dp4a_env - ? (atoi(q5_k_bin_dp4a_env) != 0) - : true; - // dot prod has to be available - q5_k_bin_dp4a_on = backend_ctx->has_integer_dot && q5_k_bin_dp4a_on; - - if (q5_k_bin_dp4a_on && backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin) { - const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; - const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); - - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_mem b_sub = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - cl_int tb = (cl_int)((size_t)N * (K / 32)); - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - cl_mem d_sub = nullptr; - cl_mem d_img = nullptr; - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin; - - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->qh)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->dm)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->s)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_int), &N)); - - size_t local_work_size_dp4a[3] = { 64, 1, 1 }; - size_t global_work_size_dp4a[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size_dp4a, local_work_size_dp4a, dst); - - CL_CHECK(clReleaseMemObject(b_sub)); - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub)); - return; - } - - const int gemm_tile_n = 64; - int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; - - const bool have_a8 = backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin != nullptr; - - if (!have_a8) { - cl_mem b_src_sub = nullptr; - cl_mem b_pad_sub = nullptr; - cl_mem b_buf = nullptr; - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - if (N_pad == N) { - b_buf = b_src_sub; - } else { - size_t padded_bytes = (size_t)K * N_pad * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); - region.origin = 0; - region.size = padded_bytes; - CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - const float b_pad_zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), - 0, padded_bytes, 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - b_buf = b_pad_sub; - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N_pad; - img_desc.buffer = b_buf; - cl_mem b_img_a7; - CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - const int c_offset_for_kernel = (int)offsetd; - - int line_stride_B = K * (int)sizeof(float); - int line_stride_C = M * (int)sizeof(float); - - kernel = backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin; - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->qh)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->d)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->dm)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->s)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 4 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_y = ((m_tiles + 1) / 2) * 2; - size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img_a7)); - if (b_src_sub) { - CL_CHECK(clReleaseMemObject(b_src_sub)); - } - if (b_pad_sub) { - CL_CHECK(clReleaseMemObject(b_pad_sub)); - } - return; - } - - cl_mem b_sub_buf = nullptr; - cl_mem b_padded = nullptr; - cl_mem b_buf = nullptr; - if (N_pad == N) { - region.origin = offset1; - region.size = (size_t)K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - b_buf = b_sub_buf; - } else { - CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, (size_t)K * N_pad * sizeof(float), NULL, &err), err)); - const float zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); - CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); - b_buf = b_padded; - } - - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)K * N_pad; - img_desc.buffer = b_buf; - cl_mem b_img; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - region.origin = offsetd; - region.size = (size_t)M * N * sizeof(float); - cl_mem d_sub_buf; - CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - img_fmt = { CL_R, CL_FLOAT }; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)M * N; - img_desc.buffer = d_sub_buf; - cl_mem d_img; - CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = backend_ctx->kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_k->q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_k->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &d_img)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uint), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &N)); - - size_t local_work_size[3] = { 64, 2, 2 }; - size_t m_tiles = (size_t)CEIL_DIV(M, 64); - size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_img)); - if (b_sub_buf) { - CL_CHECK(clReleaseMemObject(b_sub_buf)); - } - if (b_padded) { - CL_CHECK(clReleaseMemObject(b_padded)); - } - CL_CHECK(clReleaseMemObject(d_img)); - CL_CHECK(clReleaseMemObject(d_sub_buf)); - } -} -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - -static void ggml_cl_mul_mat_q5_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - ggml_tensor_extra_cl_q5_K * extra0_q5_k = (ggml_tensor_extra_cl_q5_K *)src0->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne1 = dst->ne[1]; - - GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); - - cl_context context = backend_ctx->context; - cl_kernel kernel; - - cl_int err; - cl_image_format img_fmt; - cl_image_desc img_desc; - cl_buffer_region region; - - int M = ne01; - int N = ne1; - int K = ne00; - - cl_uchar mask_d6 = 0x3F; - cl_uchar mask_d4 = 0x0F; - cl_uchar mask_hi2 = 0xC0; - - // Multi-column (N=3) verify GEMV for q5_K: route the spec/MTP verify batch - // (ne1==3) onto the efficient GEMV path instead of the transposed-GEMM dead- - // zone (gemm_noshuffle_q5_k, the #2 chunk of MTP decode on a Q4_0-mix model - // after q4_0 mc3). Reuses the ne1==1 GEMV image setup (q + qh + activations). - // Default on for X2E, GGML_OPENCL_Q5_K_MC3=0/1 forces it. Per-layer only (ne01 < 32768). - static const char * q5k_mc3_env = getenv("GGML_OPENCL_Q5_K_MC3"); - const bool q5k_mc3 = q5k_mc3_env ? atoi(q5k_mc3_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; - const bool use_q5k_mc3 = q5k_mc3 && (ne1 >= 2 && ne1 <= 4) && (ne01 < 32768); - - const bool use_bin = use_q5_k_bin_kernels(backend_ctx, src0); - - if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->kernel_gemm_noshuffle_q5_k_f32_coopmat, - { extra0_q5_k->q, extra0_q5_k->qh, extra0_q5_k->s, extra0_q5_k->d, extra0_q5_k->dm }, src1, dst, K, M, N)) { - return; - } - - if (use_bin) { - if (use_q5k_mc3) { - static bool warned = false; - if (!warned) { - GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q5_K_MC3 is bypassed by Q5_K binary kernels\n"); - warned = true; - } - } - ggml_cl_mul_mat_q5_K_f32_adreno_ila(backend, src0, src1, dst); - return; - } - - if (ne1 == 1 || use_q5k_mc3) { - cl_mem q_img = nullptr; - cl_mem qh_img = nullptr; - cl_mem b_sub_buf = nullptr; - cl_mem b_img = nullptr; - - // image for q (CL_R, CL_UNSIGNED_INT32): width = M*K/2/4 - img_fmt = {CL_R, CL_UNSIGNED_INT32}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 2 / 4; - img_desc.buffer = extra0_q5_k->q; - CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // image for qh (CL_R, CL_HALF_FLOAT): width = M*K/16 - img_fmt = {CL_R, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = M * K / 16; - img_desc.buffer = extra0_q5_k->qh; - CL_CHECK((qh_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations (CL_RGBA, CL_FLOAT): width = K*N/4 - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - kernel = use_q5k_mc3 ? backend_ctx->kernel_gemv_noshuffle_q5_k_f32_mc3 - : backend_ctx->kernel_gemv_noshuffle_q5_k_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh_img)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_hi2)); - if (use_q5k_mc3) { - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_int), &ne1)); // n_cols - } - - size_t local_work_size[3] = {64, 4, 1}; - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(q_img)); - CL_CHECK(clReleaseMemObject(qh_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_img)); - } else { - cl_mem b_sub_buf = nullptr; - cl_mem b_sub_buf_trans = nullptr; - cl_mem b_img = nullptr; - cl_mem b_img_trans = nullptr; - - // subbuffer for activations - region.origin = offset1; - region.size = K * N * sizeof(float); - CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for activations - img_fmt = {CL_RGBA, CL_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * N / 4; - img_desc.buffer = b_sub_buf; - CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); - - // pad N to multiple of 8 - int extra_elements = N % 8; - int padding = 0; - if (extra_elements > 0) { - padding = 8 - extra_elements; - } - - // subbuffer for transposed activations - region.origin = 0; - region.size = K * (N + padding) * sizeof(float) / 2; - backend_ctx->prealloc_act_trans.allocate(context, region.size); - CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); - - // image for transposed activations - img_fmt = {CL_RGBA, CL_HALF_FLOAT}; - memset(&img_desc, 0, sizeof(img_desc)); - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = K * (N + padding) / 4; - img_desc.buffer = b_sub_buf_trans; - CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); - - // transpose activations - int height_B = N / 4; - if (height_B == 0) height_B = 1; - int width_B = K / 4; - int padded_height_B = (N + padding) / 4; - - kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); - - size_t local_work_size_t[2] = {1, 16}; - size_t global_work_size_t[2] = {(size_t)width_B, (size_t)padded_height_B}; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); - - // dp4a (int8) dense q5_K prefill GEMM - static const char * q5k_dense_dp4a_env = getenv("GGML_OPENCL_Q5K_DENSE_DP4A"); - bool q5k_dense_dp4a_on = q5k_dense_dp4a_env - ? (atoi(q5k_dense_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - // dot prod has to be available - q5k_dense_dp4a_on = backend_ctx->has_integer_dot && q5k_dense_dp4a_on; - - if (q5k_dense_dp4a_on && ne1 > 8 && (ne00 % 32 == 0) && (ne01 % 64 == 0)) { - const int Mm = ne01, Nn = ne1, Kk = ne00; - const size_t n_blocks = (size_t)Nn * (Kk / 32); - backend_ctx->prealloc_moe_qa.allocate(context, (size_t)Nn * Kk * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); - - cl_int tb = (cl_int)n_blocks; - cl_kernel qk = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); - CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); - size_t q_local[1] = { 64 }; - size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; - backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); - - static const char * q5_k_act_vload4_env = getenv("GGML_OPENCL_Q5_K_DP4A_ACT_VLOAD4"); - const bool q5_k_act_vload4_on = q5_k_act_vload4_env == nullptr || atoi(q5_k_act_vload4_env) != 0; - cl_kernel dk = q5_k_act_vload4_on - ? backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4 - : backend_ctx->kernel_gemm_noshuffle_q5_k_q8_1_dp4a; - int ai = 0; - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->q)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->qh)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->s)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->d)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->dm)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &Mm)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &Nn)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &Kk)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_hi2)); - size_t d_local[3] = { 64, 1, 1 }; - size_t d_global[3] = { 64, (size_t)(Mm / 64), (size_t)CEIL_DIV(Nn, 32) }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - return; - } - - // gemm - kernel = backend_ctx->kernel_gemm_noshuffle_q5_k_f32; - int padded_N = N + padding; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_k->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_k->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->dm)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &padded_N)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_d6)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_uchar), &mask_d4)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_uchar), &mask_hi2)); - - size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; - size_t local_work_size[3] = {1, 128, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - CL_CHECK(clReleaseMemObject(b_sub_buf)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_img_trans)); - } -#else - GGML_UNUSED(backend); - GGML_UNUSED(src0); - GGML_UNUSED(src1); - GGML_UNUSED(dst); -#endif -} - -// Dequant a possibly-strided q4_0/q8_0 tensor to tight-packed f16. Returns a -// temp cl_mem the caller must release. SoA inputs are reconstructed into a -// temp AoS buffer reported via *extra_reconstruct (also caller-released). -// this is for quantized K cache without FA. -static cl_mem ggml_cl_mul_mat_dequant_quant_to_f16( - ggml_backend_opencl_context * backend_ctx, - const ggml_tensor * tensor, - cl_mem * extra_reconstruct /* out, may be NULL */ -) { - GGML_ASSERT(tensor->type == GGML_TYPE_Q4_0 || tensor->type == GGML_TYPE_Q8_0); - - if (extra_reconstruct) { - *extra_reconstruct = NULL; - } - - cl_mem src_buf; - cl_ulong src_offset; - cl_ulong src_nb1; - cl_ulong src_nb2; - cl_ulong src_nb3; - - uintptr_t pool_key_buf = 0; - cl_ulong pool_key_off = (cl_ulong) tensor->view_offs; - - const bool is_soa = tensor->type == GGML_TYPE_Q4_0 - ? ggml_cl_is_q4_0_soa(tensor) - : ggml_cl_is_q8_0_soa(tensor); - - cl_mem aos = nullptr; - if (is_soa) { - // Reconstruct full parent AoS; view's own nb[] then index it correctly. - const ggml_tensor * parent = tensor->view_src ? tensor->view_src : tensor; - const ggml_tensor * soa_src = parent; - const size_t block_bytes = (size_t) ggml_type_size(tensor->type); - const size_t blck_size = (size_t) ggml_blck_size(tensor->type); - const size_t parent_row_blocks = (size_t) parent->ne[0] / blck_size; - const size_t parent_row_bytes = parent_row_blocks * block_bytes; - const size_t parent_nbytes = (size_t) ggml_nelements(parent) / blck_size * block_bytes; - - cl_int err; - aos = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, parent_nbytes, NULL, &err); - CL_CHECK(err); - - // large q4_0/q8_0 WEIGHTS are stored transposed and small weights - // (and the AoS KV-cache, handled in the else branch above) are not. - // choose a proper restore kernel based on this. - bool restored = false; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - const int p_ne00 = (int) parent->ne[0]; - const int p_ne01 = (int) parent->ne[1]; - if (tensor->type == GGML_TYPE_Q8_0 && enable_adreno_trans_weight(backend_ctx, parent)) { - auto * extra = (ggml_tensor_extra_cl_q8_0 *) soa_src->extra; - pool_key_buf = (uintptr_t) extra->q; - cl_kernel kernel = backend_ctx->kernel_restore_block_q8_0_trans; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &p_ne00)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &p_ne01)); - size_t gws[] = { (size_t)(((p_ne01 + 63) / 64) * 64), 1, 1 }; - size_t lws[] = { 64, 1, 1 }; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, gws, lws, 0, NULL, NULL)); - restored = true; - } else if (tensor->type == GGML_TYPE_Q4_0 && - use_adreno_kernels(backend_ctx, parent) && - !use_adreno_moe_kernels(backend_ctx, parent)) { - auto * extra = (ggml_tensor_extra_cl_q4_0 *) soa_src->extra; - pool_key_buf = (uintptr_t) extra->q; - const size_t size_q = (size_t) ggml_nelements(parent) / blck_size * (blck_size / 2); - const size_t size_d = (size_t) ggml_nelements(parent) / blck_size * sizeof(ggml_fp16_t); - cl_int err2 = CL_SUCCESS; - cl_mem buf_tq = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size_q, NULL, &err2); CL_CHECK(err2); - cl_mem buf_td = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size_d, NULL, &err2); CL_CHECK(err2); - transpose_2d_as_16b(backend_ctx, extra->q, buf_tq, size_q, p_ne01, p_ne00 / 4); - transpose_2d_as_16b(backend_ctx, extra->d, buf_td, size_d, p_ne01, p_ne00 / 32); - cl_uchar mask_0F = 0x0F, mask_F0 = 0xF0; - cl_kernel kernel = backend_ctx->kernel_restore_block_q4_0_noshuffle; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_tq)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_td)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); - const size_t n_blk = parent_nbytes / block_bytes; - size_t gws[] = { n_blk, 1, 1 }; - size_t lws[] = { 1, 1, 1 }; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, gws, lws, 0, NULL, NULL)); - - CL_CHECK(clReleaseMemObject(buf_tq)); - CL_CHECK(clReleaseMemObject(buf_td)); - restored = true; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - if (!restored) { - cl_kernel kernel; - if (tensor->type == GGML_TYPE_Q8_0) { - auto * extra = (ggml_tensor_extra_cl_q8_0 *) soa_src->extra; - kernel = backend_ctx->kernel_restore_block_q8_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); - pool_key_buf = (uintptr_t) extra->q; - } else { - auto * extra = (ggml_tensor_extra_cl_q4_0 *) soa_src->extra; - kernel = backend_ctx->kernel_restore_block_q4_0; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); - pool_key_buf = (uintptr_t) extra->q; - } - - const size_t n_blocks = parent_nbytes / block_bytes; - size_t gws_rec[] = { n_blocks, 1, 1 }; - size_t lws_rec[] = { 1, 1, 1 }; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, gws_rec, lws_rec, 0, NULL, NULL)); - } - - (void) parent_row_blocks; - (void) parent_row_bytes; - src_buf = aos; - src_offset = tensor->view_offs; - src_nb1 = tensor->nb[1]; - src_nb2 = tensor->nb[2]; - src_nb3 = tensor->nb[3]; - - if (extra_reconstruct) { - *extra_reconstruct = aos; - } - } else { - auto * extra = (ggml_tensor_extra_cl *) tensor->extra; - GGML_ASSERT(extra && extra->data_device); - src_buf = extra->data_device; - src_offset = extra->offset + tensor->view_offs; - src_nb1 = tensor->nb[1]; - src_nb2 = tensor->nb[2]; - src_nb3 = tensor->nb[3]; - pool_key_buf = (uintptr_t) extra->data_device; - pool_key_off = (cl_ulong) src_offset; - } - - const cl_int nblk0 = (cl_int) (tensor->ne[0] / ggml_blck_size(tensor->type)); - const cl_int ne1_ = (cl_int) tensor->ne[1]; - const cl_int ne2_ = (cl_int) tensor->ne[2]; - const cl_int ne3_ = (cl_int) tensor->ne[3]; - - const size_t out_bytes = (size_t) ggml_nelements(tensor) * sizeof(ggml_fp16_t); - - // reuse a pooled f16 buffer for this KV-cache view across decode steps instead of - // allocating new one per attention op - cl_mem out = nullptr; - { - auto & pool = backend_ctx->dequant_f16_pool; - ggml_backend_opencl_context::ImagePoolKey key{pool_key_buf, (uint64_t) pool_key_off}; - auto it = pool.find(key); - if (it != pool.end() && it->second.k_bytes >= out_bytes && it->second.image) { - out = it->second.image; - } else { - if (it != pool.end()) { - if (it->second.image) { CL_CHECK(clReleaseMemObject(it->second.image)); } - pool.erase(it); - } - cl_int err = CL_SUCCESS; - out = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, out_bytes, NULL, &err); - CL_CHECK(err); - ggml_backend_opencl_context::ImagePoolEntry entry; - entry.image = out; - entry.k_bytes = out_bytes; - pool[key] = entry; - } - } - - cl_kernel dq_kernel = tensor->type == GGML_TYPE_Q8_0 - ? backend_ctx->kernel_dequant_q8_0_f16_view_aos - : backend_ctx->kernel_dequant_q4_0_f16_view_aos; - - CL_CHECK(clSetKernelArg(dq_kernel, 0, sizeof(cl_mem), &src_buf)); - CL_CHECK(clSetKernelArg(dq_kernel, 1, sizeof(cl_ulong), &src_offset)); - CL_CHECK(clSetKernelArg(dq_kernel, 2, sizeof(cl_ulong), &src_nb1)); - CL_CHECK(clSetKernelArg(dq_kernel, 3, sizeof(cl_ulong), &src_nb2)); - CL_CHECK(clSetKernelArg(dq_kernel, 4, sizeof(cl_ulong), &src_nb3)); - CL_CHECK(clSetKernelArg(dq_kernel, 5, sizeof(cl_int), &nblk0)); - CL_CHECK(clSetKernelArg(dq_kernel, 6, sizeof(cl_int), &ne1_)); - CL_CHECK(clSetKernelArg(dq_kernel, 7, sizeof(cl_int), &ne2_)); - CL_CHECK(clSetKernelArg(dq_kernel, 8, sizeof(cl_int), &ne3_)); - CL_CHECK(clSetKernelArg(dq_kernel, 9, sizeof(cl_mem), &out)); - - size_t gws[3] = { (size_t) nblk0, (size_t) ne1_, (size_t) (ne2_ * ne3_) }; - size_t lws[3] = { 1, 1, 1 }; - CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, dq_kernel, 3, NULL, gws, lws, 0, NULL, NULL)); - - // release the reconstructed aos if - // 1. it was actually reconstructed - // 2. the caller didn't request it to be returned - // src_buf may refer to aos, so we should release after this enqueue - if (aos && !extra_reconstruct) { - CL_CHECK(clReleaseMemObject(aos)); - } - return out; -} - -// look up or create a pooled image1d_buffer over a KV-cache view. -static cl_mem ggml_cl_img_pool_get_or_create( - ggml_backend_opencl_context * backend_ctx, - std::map & pool, - cl_mem data_device, - cl_ulong offset0, - size_t required_bytes, - cl_channel_type channel_data_type -) { - ggml_backend_opencl_context::ImagePoolKey key{(uintptr_t)data_device, (uint64_t)offset0}; - auto it = pool.find(key); - if (it != pool.end() - && it->second.k_bytes >= required_bytes - && it->second.channel_data_type == channel_data_type - && it->second.image != nullptr) { - return it->second.image; - } - - // need to create or recreate and release any stale entry first. - if (it != pool.end()) { - if (it->second.image) { CL_CHECK(clReleaseMemObject(it->second.image)); } - if (it->second.sub_buffer) {CL_CHECK(clReleaseMemObject(it->second.sub_buffer)); } - pool.erase(it); - } - - cl_int status = CL_SUCCESS; - cl_buffer_region region = {}; - region.origin = (size_t)offset0; - region.size = required_bytes; - cl_mem sub = clCreateSubBuffer(data_device, 0, - CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - if (status != CL_SUCCESS) { - return nullptr; - } - - const size_t pixel_size = (channel_data_type == CL_HALF_FLOAT) ? 8 : 16; - cl_image_format fmt = {CL_RGBA, channel_data_type}; - cl_image_desc desc = {}; - desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - desc.image_width = required_bytes / pixel_size; - desc.buffer = sub; - cl_mem img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, - &fmt, &desc, NULL, &status); - if (status != CL_SUCCESS) { - CL_CHECK(clReleaseMemObject(sub)); - return nullptr; - } - - ggml_backend_opencl_context::ImagePoolEntry entry; - entry.sub_buffer = sub; - entry.image = img; - entry.k_bytes = required_bytes; - entry.channel_data_type = channel_data_type; - pool[key] = entry; - return img; -} - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS -static bool ggml_cl_mul_mat_q2_K_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_q2_K * extra0 = (ggml_tensor_extra_cl_q2_K *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 16 ? 8 : 32; - cl_kernel gemm = n <= 16 ? backend_ctx->kernel_gemm_noshuffle_q2_k_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_q2_k_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_Q2_K_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->dm)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_q3_K_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_q3_K * extra0 = (ggml_tensor_extra_cl_q3_K *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 16 ? 8 : 32; - cl_kernel gemm = n <= 16 ? backend_ctx->kernel_gemm_noshuffle_q3_k_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_q3_k_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_Q3_K_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->hm)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_iq3_s_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq3_s * extra0 = (ggml_tensor_extra_cl_iq3_s *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq3_s_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq3_s_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ3_S_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sg)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 11, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_iq3_xxs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq3_xxs * extra0 = (ggml_tensor_extra_cl_iq3_xxs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ3_XXS_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sas)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_iq1_m_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq1_m * extra0 = (ggml_tensor_extra_cl_iq1_m *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq1_m_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq1_m_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ1_M_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_iq1_s_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq1_s * extra0 = (ggml_tensor_extra_cl_iq1_s *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq1_s_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq1_s_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ1_S_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_iq2_s_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq2_s * extra0 = (ggml_tensor_extra_cl_iq2_s *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq2_s_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq2_s_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ2_S_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sg)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 11, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_iq2_xs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq2_xs * extra0 = (ggml_tensor_extra_cl_iq2_xs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ2_XS_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static bool ggml_cl_mul_mat_iq2_xxs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq2_xxs * extra0 = (ggml_tensor_extra_cl_iq2_xxs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - const int tile_n = n <= 8 ? 8 : 32; - cl_kernel gemm = n <= 8 ? backend_ctx->kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a_narrow - : backend_ctx->kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a; - const char * env = getenv("GGML_OPENCL_IQ2_XXS_DENSE_DP4A"); - if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || - n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - return false; - } - - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - const size_t n_blocks = (size_t)n*(k/32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); - - cl_int nb = n_blocks; - cl_kernel quant = backend_ctx->kernel_quant_a_q8_1; - CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); - CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); - size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; - size_t q_local[] = { 64 }; - backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); - - CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sas)); - CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); - size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; - size_t local[] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); - CL_CHECK(clReleaseMemObject(activation)); - return true; -} - -static void ggml_cl_mul_mat_q2_k_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_q2_K * extra0 = (ggml_tensor_extra_cl_q2_K *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_q2_k_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->dm)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_d)); - const size_t rows = 64*(size_t)backend_ctx->q2_k_mv_rows; - const size_t nsg = backend_ctx->q2_k_mv_nsg; - size_t global[] = { CEIL_DIV((size_t)m, rows)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_q2_K_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_q2_k_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_q3_k_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_q3_K * extra0 = (ggml_tensor_extra_cl_q3_K *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_q3_k_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->hm)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); - const size_t rows = 64*(size_t)backend_ctx->q3_k_mv_rows; - const size_t nsg = backend_ctx->q3_k_mv_nsg; - size_t global[] = { CEIL_DIV((size_t)m, rows)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_q3_K_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_q3_k_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->hm)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_iq3_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq3_s * extra0 = (ggml_tensor_extra_cl_iq3_s *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq3_s_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq3_s_grid_image)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sg)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 12, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 13, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq3_s_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq3_s_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq3_s_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_iq3_xxs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq3_xxs * extra0 = (ggml_tensor_extra_cl_iq3_xxs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq3_xxs_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq3_xxs_grid_image)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sas)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq3_xxs_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq3_xxs_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq3_xxs_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_iq1_m_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq1_m * extra0 = (ggml_tensor_extra_cl_iq1_m *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq1_m_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq1_s_grid_image)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq1_m_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq1_m_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq1_m_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_iq1_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq1_s * extra0 = (ggml_tensor_extra_cl_iq1_s *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq1_s_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq1_s_grid_image)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq1_s_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq1_s_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq1_s_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_iq2_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq2_s * extra0 = (ggml_tensor_extra_cl_iq2_s *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq2_s_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq2_s_grid_image)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sg)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 12, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 13, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq2_s_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq2_s_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq2_s_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_iq2_xs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq2_xs * extra0 = (ggml_tensor_extra_cl_iq2_xs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq2_xs_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq2_xs_grid_image)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq2_xs_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq2_xs_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq2_xs_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} - -static void ggml_cl_mul_mat_iq2_xxs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; - ggml_tensor_extra_cl_iq2_xxs * extra0 = (ggml_tensor_extra_cl_iq2_xxs *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - const int m = src0->ne[1]; - const int n = src1->ne[1]; - const int k = src0->ne[0]; - - if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { - cl_kernel gemv = backend_ctx->kernel_gemv_noshuffle_iq2_xxs_f32; - const int stride_d = dst->ne[0]; - const int stride_b = src1->nb[1]/sizeof(float); - CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq2_xxs_grid_image)); - CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sas)); - CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); - const size_t nsg = backend_ctx->iq2_xxs_mv_nsg; - size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; - size_t local[] = { 64, nsg, 1 }; - backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); - return; - } - - if (ggml_cl_mul_mat_iq2_xxs_dp4a(backend, src0, src1, dst)) { - return; - } - - cl_context context = backend_ctx->context; - cl_int err; - cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; - cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; - cl_image_desc img_desc = {}; - img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; - img_desc.image_width = (size_t)k*n/4; - img_desc.buffer = b_sub_buf; - cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int padded_n = CEIL_DIV(n, 8)*8; - region.origin = 0; - region.size = (size_t)k*padded_n*sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(context, region.size); - cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - img_fmt = { CL_RGBA, CL_HALF_FLOAT }; - img_desc.image_width = (size_t)k*padded_n/4; - img_desc.buffer = b_sub_buf_trans; - cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); - CL_CHECK(err); - - const int height_b = std::max(n/4, 1); - const int width_b = k/4; - const int padded_height_b = padded_n/4; - cl_kernel kernel = backend_ctx->kernel_transpose_32_16; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); - size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; - size_t t_local[] = { 1, 16 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); - - kernel = backend_ctx->kernel_gemm_noshuffle_iq2_xxs_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); - size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; - size_t local[] = { 1, 128, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); - - CL_CHECK(clReleaseMemObject(b_img_trans)); - CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); - CL_CHECK(clReleaseMemObject(b_img)); - CL_CHECK(clReleaseMemObject(b_sub_buf)); -} -#endif - -static void ggml_cl_fwht(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - - auto * extra_src = (ggml_tensor_extra_cl *) src->extra; - auto * extra_dst = (ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset_src = extra_src->offset + src->view_offs; - const cl_ulong offset_dst = extra_dst->offset + dst->view_offs; - - const cl_ulong ne1 = src->ne[1]; - const cl_ulong ne2 = src->ne[2]; - const cl_ulong nb1 = src->nb[1]; - const cl_ulong nb2 = src->nb[2]; - const cl_ulong nb3 = src->nb[3]; - - const int n = src->ne[0]; - const float scale = 1.0f/sqrtf((float)n); - const int type_index = src->type == GGML_TYPE_F16 ? 1 : 0; - - cl_kernel kernel = backend_ctx->kernel_fwht[type_index]; - const size_t nth = std::min((size_t)n/2, backend_ctx->fwht_workgroup_size[type_index]); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_src)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_dst)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 11, n*sizeof(float), nullptr)); - - size_t global[] = { nth, (size_t)ggml_nrows(src) }; - size_t local[] = { nth, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst); -} - -// reduce lanes per row for short K, down to four lanes. -static int ggml_cl_mcr_lpr_log2(int ne00) { - int lpr_log2 = 6; - while (lpr_log2 > 2 && ((ne00 / 4) >> lpr_log2) < 4) { - lpr_log2--; - } - return lpr_log2; -} - -static bool ggml_cl_mcr_wide_enough(int ne00, int ne01) { - const int rows_per_wg = 64 >> ggml_cl_mcr_lpr_log2(ne00); - return CEIL_DIV((size_t) ne01, rows_per_wg) >= 256; -} - -static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - // bf16 is stored as f16 on device - const enum ggml_type src0t = (src0->type == GGML_TYPE_BF16) ? GGML_TYPE_F16 : src0->type; - const enum ggml_type src1t = src1->type; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - if (ggml_cl_mul_mat_can_use_fwht(backend_ctx, dst)) { - ggml_cl_fwht(backend, src1, dst); - return; - } - - // quant kv without FA - // used for non-contiguous src0 (the usual head-major permuted K view when n_head_kv>1) - // AND for the contiguous case that occurs when n_head_kv==1 (e.g. Gemma-4 E2B) - // Q4_0 bin kernels use a special weight layout, which the restore below does not support. - bool q4_0_bin_layout = false; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - q4_0_bin_layout = src0t == GGML_TYPE_Q4_0 && src0->view_src == nullptr && - ggml_is_contiguous(src0) && - src0->ne[2] == 1 && src0->ne[3] == 1 && - use_adreno_kernels(backend_ctx, src0) && - !use_adreno_moe_kernels(backend_ctx, src0) && - use_q4_0_bin_kernels(backend_ctx, src0); -#endif - if ((src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q8_0) && !q4_0_bin_layout && - (!ggml_is_contiguous(src0) || src1->ne[2] > src0->ne[2])) { - cl_mem f16_buf = ggml_cl_mul_mat_dequant_quant_to_f16(backend_ctx, src0, nullptr); - - ggml_tensor fake_src0 = *src0; - ggml_tensor_extra_cl fake_extra = {}; - fake_extra.data_device = f16_buf; - fake_extra.offset = 0; - fake_src0.type = GGML_TYPE_F16; - fake_src0.extra = &fake_extra; - fake_src0.view_src = nullptr; - fake_src0.view_offs = 0; - fake_src0.nb[0] = sizeof(ggml_fp16_t); - fake_src0.nb[1] = fake_src0.nb[0] * src0->ne[0]; - fake_src0.nb[2] = fake_src0.nb[1] * src0->ne[1]; - fake_src0.nb[3] = fake_src0.nb[2] * src0->ne[2]; - - ggml_cl_mul_mat(backend, &fake_src0, src1, dst); - return; - } - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - -#ifdef GGML_OPENCL_SOA_Q - // view->extra stays pre-SoA; cast to the SoA struct would SIGSEGV. - // Follow view_src to reach the real SoA extra. - const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; - ggml_tensor_extra_cl_q1_0 * extra0_q1_0 = (ggml_tensor_extra_cl_q1_0 *)src0->extra; - ggml_tensor_extra_cl_q2_0 * extra0_q2_0 = (ggml_tensor_extra_cl_q2_0 *)soa0_src->extra; - ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)soa0_src->extra; - ggml_tensor_extra_cl_q4_1 * extra0_q4_1 = (ggml_tensor_extra_cl_q4_1 *)soa0_src->extra; - ggml_tensor_extra_cl_q5_0 * extra0_q5_0 = (ggml_tensor_extra_cl_q5_0 *)soa0_src->extra; - ggml_tensor_extra_cl_q5_1 * extra0_q5_1 = (ggml_tensor_extra_cl_q5_1 *)soa0_src->extra; - ggml_tensor_extra_cl_mxfp4 * extra0_mxfp4 = (ggml_tensor_extra_cl_mxfp4 *)soa0_src->extra; - ggml_tensor_extra_cl_q8_0 * extra0_q8_0 = (ggml_tensor_extra_cl_q8_0 *)soa0_src->extra; - ggml_tensor_extra_cl_iq4_nl * extra0_iq4_nl = (ggml_tensor_extra_cl_iq4_nl *)soa0_src->extra; - ggml_tensor_extra_cl_iq4_xs * extra0_iq4_xs = (ggml_tensor_extra_cl_iq4_xs *)soa0_src->extra; - ggml_tensor_extra_cl_q2_K * extra0_q2_K = (ggml_tensor_extra_cl_q2_K *)soa0_src->extra; - ggml_tensor_extra_cl_q3_K * extra0_q3_K = (ggml_tensor_extra_cl_q3_K *)soa0_src->extra; - ggml_tensor_extra_cl_iq2_s * extra0_iq2_s = (ggml_tensor_extra_cl_iq2_s *)soa0_src->extra; - ggml_tensor_extra_cl_iq2_xs * extra0_iq2_xs = (ggml_tensor_extra_cl_iq2_xs *)soa0_src->extra; - ggml_tensor_extra_cl_iq2_xxs * extra0_iq2_xxs = (ggml_tensor_extra_cl_iq2_xxs *)soa0_src->extra; - ggml_tensor_extra_cl_iq1_m * extra0_iq1_m = (ggml_tensor_extra_cl_iq1_m *)soa0_src->extra; - ggml_tensor_extra_cl_iq1_s * extra0_iq1_s = (ggml_tensor_extra_cl_iq1_s *)soa0_src->extra; - ggml_tensor_extra_cl_iq3_s * extra0_iq3_s = (ggml_tensor_extra_cl_iq3_s *)soa0_src->extra; - ggml_tensor_extra_cl_iq3_xxs * extra0_iq3_xxs = (ggml_tensor_extra_cl_iq3_xxs *)soa0_src->extra; - ggml_tensor_extra_cl_q4_K * extra0_q4_K = (ggml_tensor_extra_cl_q4_K *)soa0_src->extra; - ggml_tensor_extra_cl_q5_K * extra0_q5_K = (ggml_tensor_extra_cl_q5_K *)soa0_src->extra; - ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *)soa0_src->extra; -#endif - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(int, ne1, src1, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); - GGML_TENSOR_LOCALS(int, ne, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - int r2 = ne12/ne02; - int r3 = ne13/ne03; - - GGML_ASSERT(ne00 == ne10); - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // adreno GEMM/GEMV kernels do not support broadcast, assuming ne2 and ne3 are 1 for src1 - // so we handle broadcast here - if ((ne12 > 1 || ne13 > 1) && ne02 == 1 && ne03 == 1 && - src0t != GGML_TYPE_F16 && src0t != GGML_TYPE_F32) { - for (int i13 = 0; i13 < ne13; ++i13) { - for (int i12 = 0; i12 < ne12; ++i12) { - ggml_tensor s1 = *src1; - s1.ne[2] = 1; s1.ne[3] = 1; - s1.view_offs = src1->view_offs + (size_t)i12*nb12 + (size_t)i13*nb13; - ggml_tensor d = *dst; - d.ne[2] = 1; d.ne[3] = 1; - d.view_offs = dst->view_offs + (size_t)i12*nb2 + (size_t)i13*nb3; - d.src[1] = &s1; - ggml_cl_mul_mat(backend, src0, &s1, &d); - } - } - return; - } -#endif - - int nth0 = 32; - int nth1 = 1; - int nrows = 1; - // The number of values produced by each subgroup - int ndst = 4; - - cl_kernel kernel; - -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if(src0t == GGML_TYPE_F16 && src1t == GGML_TYPE_F32){ - // Two tiling assumptions these kernels make but nothing enforced: - // - // ne00 % TILESIZE_K(16): the K loop has no tail, so a K that does not - // divide folds 1-15 rows of whatever follows the operands into every - // output. - // - // ne01 % TILESIZE_M(64): mm_store_c_N guards the n direction with its - // `mask` argument but nothing guards m -- the store walks all 64 rows - // of the tile at a stride of M. When M does not divide, the last tile - // does not run off the end of the buffer, it writes 64 - (M % 64) - // values ON TOP OF the next column, so the result is silently wrong. - // Reachable on the KQV side for any head size >= 64 that is not a - // multiple of it (80, 96, 112). - // - // Attention shapes in the graph satisfy both -- head sizes are multiples - // of 64 and n_kv is padded -- which is why this has stayed latent. - // Declining leaves the odd shapes on the generic GEMM, which handles them. - if (ne01 >= 64 && ne1 >= 32 && ne00 >= 16 && - (ne00 % 16) == 0 && (ne01 % 64) == 0 && (ne12 % ne02) == 0 && - // the KQ/KQV image kernels do not handle dim 3 (multi-stream batches) - ne03 == 1 && ne13 == 1 && - // dst is wrapped with image1d_buffer, the size limit applies, also src0 - (ne0 * ne1 * dst->ne[2] * dst->nb[0] / 4 <= backend_ctx->image_max_buffer_size)) { - // For KQ. - // - // Layout admission, mirroring the KQV arm below. The KQ kernel takes - // no stride arguments for A or B: it derives them as K*D_A*2 and - // K*D_B*4, i.e. it assumes both operands pack exactly D heads of K - // elements per row. Every real KV-cache view and permuted-Q view - // does, but a view spanning part of a wider allocation does not, and - // the kernel then walks the wrong rows with nothing to range-check - // it. Gate on the packed layout itself rather than on the stride - // ORDERING, which a wider parent satisfies just as well. - const bool kq_packed_a = (nb01 == (cl_ulong)ne00 * ne02 * ggml_type_size(src0t)) && - (nb02 == (cl_ulong)ne00 * ggml_type_size(src0t)); - const bool kq_packed_b = (nb11 == (cl_ulong)ne10 * ne12 * ggml_type_size(src1t)) && - (nb12 == (cl_ulong)ne10 * ggml_type_size(src1t)); - // - // ggml_is_permuted(src0) stands in for "K is head-major", but it is - // only a proxy and it COLLAPSES at n_head_kv == 1: with a single - // head there is no head stride to be out of order, so nb01 == nb02 - // and the view reports itself unpermuted. Such a KQ was declined - // here and fell through to the generic GEMM (gemma-4 E2B, and any - // other multi-query model). The packed check above is the contract - // the kernel actually needs -- it pins both strides exactly -- so - // require permutedness only where there is more than one head for - // it to mean anything. - // - // Default on; GGML_OPENCL_KQ_NHEAD_KV1=0 restores the old proxy so - // the two routings can be compared in one binary. - static const char * kq_nhkv1_env = getenv("GGML_OPENCL_KQ_NHEAD_KV1"); - static const bool kq_nhkv1_on = - (kq_nhkv1_env == nullptr || kq_nhkv1_env[0] != '0'); - if ((ggml_is_permuted(src0) || (ne02 == 1 && kq_nhkv1_on)) && ggml_is_permuted(src1) && - kq_packed_a && kq_packed_b && - ((nb01 * ne01 / 4)/4 <= backend_ctx->image_max_buffer_size) && - nb00 <= nb02 && - nb02 <= nb01 && - nb01 <= nb03 && - nb10 <= nb12 && - nb12 <= nb11 && - nb11 <= nb13) { - ggml_cl_mul_mat_kq_kqv_adreno(backend, src0, src1, dst, /*is_kq =*/ true); - return; - } - // For KQV. Reaching this arm is what makes the op a KQV; the callee - // is told so explicitly rather than re-deriving it from the strides - // the arm above has already ruled on. - if (!ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && - ((nb02 * ne02 / 4)/4 <= backend_ctx->image_max_buffer_size)) { - ggml_cl_mul_mat_kq_kqv_adreno(backend, src0, src1, dst, /*is_kq =*/ false); - return; - } - } - - static const char * mm_kq_gqa_img_env = getenv("GGML_OPENCL_MM_KQ_GQA_IMG"); - static const bool mm_kq_gqa_img_on = (mm_kq_gqa_img_env == nullptr || mm_kq_gqa_img_env[0] != '0'); - static const char * mm_kq_gqa_r4_img_env = getenv("GGML_OPENCL_MM_KQ_GQA_R4_IMG"); - static const bool mm_kq_gqa_r4_img_on = (mm_kq_gqa_r4_img_env == nullptr || mm_kq_gqa_r4_img_env[0] != '0'); - const bool img_r4_gate = - mm_kq_gqa_r4_img_on && - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img != nullptr && - ne11 == 1 && ne01 >= 64 && (ne01 % 16) == 0 && ne00 == 128 && - (ne12 % ne02) == 0 && (ne12 / ne02) == 4 && (ne13 / ne03) == 1; - if (mm_kq_gqa_img_on && - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4_img != nullptr && - ne11 == 1 && ne01 >= 64 && (ne01 % 16) == 0 && ne00 == 128 && - (ne12 % ne02) == 0 && (ne12 / ne02) == 8 && (ne13 / ne03) == 1) { - const size_t nb00_bytes = sizeof(uint16_t); - const size_t k_bytes_span = - (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + - (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + - (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + - (size_t)ne00 * nb00_bytes; - - const size_t k_bytes = (k_bytes_span + 15) & ~(size_t)15; - const size_t k_pixels = k_bytes >> 4; - if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { - cl_kernel kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4_img; - cl_mem K_img = ggml_cl_img_pool_get_or_create( - backend_ctx, backend_ctx->kq_img_pool, - extra0->data_device, offset0, k_bytes, CL_FLOAT); - if (K_img != nullptr) { - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &K_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); - - const int nth0_d = 64; - const int64_t n_wg_x = ne01 / 16; - size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; - size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - } - } - - // r2=4 specialization - if (img_r4_gate) { - const size_t nb00_bytes = sizeof(uint16_t); - const size_t k_bytes_span = - (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + - (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + - (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + - (size_t)ne00 * nb00_bytes; - const size_t k_bytes = (k_bytes_span + 15) & ~(size_t)15; - const size_t k_pixels = k_bytes >> 4; - if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { - cl_kernel kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img; - cl_mem K_img = ggml_cl_img_pool_get_or_create( - backend_ctx, backend_ctx->kq_img_pool, - extra0->data_device, offset0, k_bytes, CL_FLOAT); - if (K_img != nullptr) { - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &K_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); - - const int nth0_d = 64; - const int64_t n_wg_x = ne01 / 16; - size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; - size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - } - } - - // DK=256, r2=2 specialization - static const char * mm_kq_r2_dk256_env = getenv("GGML_OPENCL_MM_KQ_GQA_R2_DK256_IMG"); - static const bool mm_kq_r2_dk256_on = (mm_kq_r2_dk256_env != nullptr && mm_kq_r2_dk256_env[0] != '0'); - if (mm_kq_r2_dk256_on && - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img != nullptr && - ne11 == 1 && ne01 >= 64 && (ne01 % 16) == 0 && ne00 == 256 && - (ne12 % ne02) == 0 && (ne12 / ne02) == 2 && (ne13 / ne03) == 1) { - const size_t nb00_bytes = sizeof(uint16_t); - const size_t k_bytes_span = - (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + - (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + - (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + - (size_t)ne00 * nb00_bytes; - const size_t k_bytes = (k_bytes_span + 15) & ~(size_t)15; - const size_t k_pixels = k_bytes >> 4; - if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { - cl_kernel kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img; - cl_mem K_img = ggml_cl_img_pool_get_or_create( - backend_ctx, backend_ctx->kq_img_pool, - extra0->data_device, offset0, k_bytes, CL_FLOAT); - if (K_img != nullptr) { - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &K_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); - - const int nth0_d = 64; - const int64_t n_wg_x = ne01 / 16; - size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; - size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - } - } - - // GQA-coalesced KQV for decode using image1d_buffer_t - static const char * mm_kqv_gqa_img_env = getenv("GGML_OPENCL_MM_KQV_GQA_IMG"); - static const bool mm_kqv_gqa_img_on = (mm_kqv_gqa_img_env != nullptr && mm_kqv_gqa_img_env[0] != '0'); - if (mm_kqv_gqa_img_on && - backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa_img != nullptr && - ne11 == 1 && ne01 == 128 && - (ne12 % ne02) == 0 && (ne12 / ne02) == 8 && (ne13 / ne03) == 1) { - const size_t nb00_bytes = sizeof(uint16_t); - const size_t v_bytes_span = - (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + - (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + - (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + - (size_t)ne00 * nb00_bytes; - const size_t v_bytes = (v_bytes_span + 7) & ~(size_t)7; - const size_t v_pixels = v_bytes >> 3; - if (v_pixels > 0 && v_pixels <= backend_ctx->image_max_buffer_size) { - cl_kernel kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa_img; - cl_mem V_img = ggml_cl_img_pool_get_or_create( - backend_ctx, backend_ctx->kqv_img_pool, - extra0->data_device, offset0, v_bytes, CL_HALF_FLOAT); - if (V_img != nullptr) { - cl_uint k_arg = 0; - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &V_img)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); - - const int nth0_d = 64; - const int64_t n_wg_x = ne01 / 8; - size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; - size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - } - } - } - - if (ne01 && ne1 && use_adreno_kernels(backend_ctx, src0)) { - // NOTE: Kernels using image1d_buffer_t (e.g., src0_q) would normally require - // a limit check, but q4_0 / q4_1 tensors are very unlikely to exceed that - // limit, so the check is omitted. - - // q1_0 x fp32 - if (src0t == GGML_TYPE_Q1_0 && src1t == GGML_TYPE_F32 && - enable_adreno_trans_weight(backend_ctx, src0)) { - ggml_cl_mul_mat_q1_0_f32_adreno(backend, src0, src1, dst); - return; - } - - // q2_0 x fp32 - if (src0t == GGML_TYPE_Q2_0 && src1t == GGML_TYPE_F32 && extra0_q2_0->noshuffle) { - ggml_cl_mul_mat_q2_0_f32_adreno(backend, src0, src1, dst); - return; - } - - // q4_0 x fp32 - if(src0t == GGML_TYPE_Q4_0 && src1t == GGML_TYPE_F32) { - ggml_cl_mul_mat_q4_0_f32_adreno(backend, src0, src1, dst); - return; - } - - // q4_1 x fp32 - if (src0t == GGML_TYPE_Q4_1 && src1t == GGML_TYPE_F32) { - ggml_cl_mul_mat_q4_1_f32_adreno(backend, src0, src1, dst); - return; - } - - // q5_0 x fp32 - if (src0t == GGML_TYPE_Q5_0 && src1t == GGML_TYPE_F32) { - ggml_cl_mul_mat_q5_0_f32_adreno(backend, src0, src1, dst); - return; - } - - // q5_1 x fp32 - if (src0t == GGML_TYPE_Q5_1 && src1t == GGML_TYPE_F32) { - ggml_cl_mul_mat_q5_1_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq4_nl x fp32 - if (src0t == GGML_TYPE_IQ4_NL && src1t == GGML_TYPE_F32) { - ggml_cl_mul_mat_iq4_nl_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq4_xs x fp32 - if (src0t == GGML_TYPE_IQ4_XS && src1t == GGML_TYPE_F32 && extra0_iq4_xs->noshuffle) { - ggml_cl_mul_mat_iq4_xs_f32_adreno(backend, src0, src1, dst); - return; - } - - // q8_0 x fp32 - if (src0t == GGML_TYPE_Q8_0 && src1t == GGML_TYPE_F32 && - enable_adreno_trans_weight(backend_ctx, src0)) { - ggml_cl_mul_mat_q8_0_f32_adreno(backend, src0, src1, dst); - return; - } - - // q2_k x fp32 - if (src0t == GGML_TYPE_Q2_K && src1t == GGML_TYPE_F32 && extra0_q2_K->noshuffle) { - ggml_cl_mul_mat_q2_k_f32_adreno(backend, src0, src1, dst); - return; - } - - // q3_k x fp32 - if (src0t == GGML_TYPE_Q3_K && src1t == GGML_TYPE_F32 && extra0_q3_K->noshuffle) { - ggml_cl_mul_mat_q3_k_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq3_s x fp32 - if (src0t == GGML_TYPE_IQ3_S && src1t == GGML_TYPE_F32 && extra0_iq3_s->noshuffle) { - ggml_cl_mul_mat_iq3_s_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq3_xxs x fp32 - if (src0t == GGML_TYPE_IQ3_XXS && src1t == GGML_TYPE_F32 && extra0_iq3_xxs->noshuffle) { - ggml_cl_mul_mat_iq3_xxs_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq1_m x fp32 - if (src0t == GGML_TYPE_IQ1_M && src1t == GGML_TYPE_F32 && extra0_iq1_m->noshuffle) { - ggml_cl_mul_mat_iq1_m_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq1_s x fp32 - if (src0t == GGML_TYPE_IQ1_S && src1t == GGML_TYPE_F32 && extra0_iq1_s->noshuffle) { - ggml_cl_mul_mat_iq1_s_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq2_s x fp32 - if (src0t == GGML_TYPE_IQ2_S && src1t == GGML_TYPE_F32 && extra0_iq2_s->noshuffle) { - ggml_cl_mul_mat_iq2_s_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq2_xs x fp32 - if (src0t == GGML_TYPE_IQ2_XS && src1t == GGML_TYPE_F32 && extra0_iq2_xs->noshuffle) { - ggml_cl_mul_mat_iq2_xs_f32_adreno(backend, src0, src1, dst); - return; - } - - // iq2_xxs x fp32 - if (src0t == GGML_TYPE_IQ2_XXS && src1t == GGML_TYPE_F32 && extra0_iq2_xxs->noshuffle) { - ggml_cl_mul_mat_iq2_xxs_f32_adreno(backend, src0, src1, dst); - return; - } - - // q4_k x fp32 - if (src0t == GGML_TYPE_Q4_K && src1t == GGML_TYPE_F32 && !use_flat_gemv_for_large_m_q4_K(backend_ctx, src0)) { - ggml_cl_mul_mat_q4_k_f32_adreno(backend, src0, src1, dst); - return; - } - - // q6_K x fp32 - if (src0t == GGML_TYPE_Q6_K && src1t == GGML_TYPE_F32 && !use_flat_gemv_for_large_m_q6_K(backend_ctx, src0)) { - ggml_cl_mul_mat_q6_K_f32_adreno(backend, src0, src1, dst); - return; - } - - // q5_K x fp32 - if (src0t == GGML_TYPE_Q5_K && src1t == GGML_TYPE_F32 && - enable_adreno_trans_weight_q5_K(backend_ctx, src0)) { - ggml_cl_mul_mat_q5_K_f32_adreno(backend, src0, src1, dst); - return; - } - } // if (ne01 && ne1) -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - - // GEMM using local memory - // Current BK = 16, so ne00 % 16 == 0 - // - // Certain A7X compiler (E031.41) executes kernel_mul_mm_f32_f32_l4_lm poorly; - // matrices with ne11 <= 8 appears OK. - // Fallback to the MV style kernels for A7x and ne11 > 8. - // Override with GGML_OPENCL_A7X_F32_LM_BYPASS=0. - static const char * a7x_f32lm_env = getenv("GGML_OPENCL_A7X_F32_LM_BYPASS"); - static const bool a7x_f32lm_bypass = (a7x_f32lm_env == nullptr || a7x_f32lm_env[0] != '0'); - // The 64-column tile wastes work on small F32 matrices, including block rotations. - const bool f32_use_mv = (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || - (backend_ctx->kernel_mul_mv_f32_f32_r2 != nullptr && ne00 <= 512)) && - src0t == GGML_TYPE_F32 && ne00 >= 256 && ne00 <= 1024 && ne00 % 16 == 0 && ne01 <= 512 && ne11 <= 16 && - ne02 == 1 && ne12 == 1 && ne13 == 1 && - ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && (offset0 | offset1) % 16 == 0; - if (src1t == GGML_TYPE_F32 && - ne00 % 16 == 0 && - ne11 > 1 && !f32_use_mv && - !(a7x_f32lm_bypass && src0t == GGML_TYPE_F32 && ne11 > 8 && - backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X)) { - switch(src0t) { - case GGML_TYPE_F32: { - // Small-N f32 GEMV for the spec/MTP verify batch: the tiled GEMM - // below always computes a full 64x64 tile, so at ne11=3 with a - // skinny f32 weight (GDN ssm_alpha/ssm_beta, M=32) it launches one - // under-occupied WG at ~2.3% tile utilization. Route to a per-output - // (m,n) GEMV (64-thread WG, K-split + __local reduce) instead. - // 2D contiguous, small N + skinny M only. Default on for X2E, GGML_OPENCL_F32_MC=0/1 forces it. - static const int f32_mc_env = [] { - const char * env = getenv("GGML_OPENCL_F32_MC"); - return env ? atoi(env) : -1; - }(); - const bool f32_mc = f32_mc_env >= 0 ? f32_mc_env != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; - - static const int f32_mcr_env = [] { - const char * env = getenv("GGML_OPENCL_F32_MCR"); - return env && *env ? atoi(env) : -1; - }(); - const bool f32_mcr = f32_mcr_env >= 0 ? f32_mcr_env != 0 : - (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X); - const bool f32_mcr_allowed = f32_mc_env >= 0 ? f32_mc_env != 0 : !adreno_e17_compiler_quirks(backend_ctx); - - if (f32_mcr && f32_mcr_allowed && backend_ctx->kernel_gemv_f32_f32_mcr != nullptr && - ne11 >= 2 && ne11 <= 8 && ne00 > 0 && ne00 <= INT_MAX && ne01 > 0 && ne01 <= 512 && - (size_t) ne01 <= SIZE_MAX / 64 && (ne00 % 4 == 0) && - ne02 == 1 && ne03 == 1 && ne12 == 1 && ne13 == 1 && - dst->ne[2] == 1 && dst->ne[3] == 1 && - ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) && - offset0 % 16 == 0 && offset1 % 16 == 0 && offsetd % sizeof(float) == 0 && - ggml_cl_mcr_wide_enough((int) ne00, (int) ne01) - ) { - const int K = (int) ne00; - const int M = (int) ne01; - const int N = (int) ne11; - - const int stride_a = K; - const int stride_b = K; - const int stride_d = M; - - const int lpr_log2 = ggml_cl_mcr_lpr_log2(K); - const int rows_per_wg = 64 >> lpr_log2; - - cl_kernel mcr = backend_ctx->kernel_gemv_f32_f32_mcr; - - CL_CHECK(clSetKernelArg(mcr, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(mcr, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(mcr, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(mcr, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(mcr, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(mcr, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(mcr, 6, sizeof(int), &K)); - CL_CHECK(clSetKernelArg(mcr, 7, sizeof(int), &M)); - CL_CHECK(clSetKernelArg(mcr, 8, sizeof(int), &N)); - CL_CHECK(clSetKernelArg(mcr, 9, sizeof(int), &stride_a)); - CL_CHECK(clSetKernelArg(mcr, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(mcr, 11, sizeof(int), &stride_d)); - CL_CHECK(clSetKernelArg(mcr, 12, sizeof(int), &lpr_log2)); - - size_t global[] = {CEIL_DIV((size_t) M, rows_per_wg) * 64, 1, 1}; - size_t local[] = {64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(mcr, 3, global, local, dst); - return; - } - - if (f32_mc && ne11 >= 2 && ne11 <= 8 && ne01 <= 512 && (ne00 % 4 == 0) && - ne02 == 1 && ne12 == 1 && ne13 == 1 && - ggml_is_contiguous(src0) && ggml_is_contiguous(src1)) { - cl_kernel kmc = backend_ctx->kernel_gemv_f32_f32_mc; - int stride_a = ne00, stride_b = ne00, stride_d = ne01; - CL_CHECK(clSetKernelArg(kmc, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kmc, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kmc, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kmc, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kmc, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kmc, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kmc, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kmc, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kmc, 8, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kmc, 9, sizeof(int), &stride_a)); - CL_CHECK(clSetKernelArg(kmc, 10, sizeof(int), &stride_b)); - CL_CHECK(clSetKernelArg(kmc, 11, sizeof(int), &stride_d)); - size_t gws[3] = {64, (size_t)ne01 * (size_t)ne11, 1}; - size_t lws[3] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kmc, 3, gws, lws, dst); - return; - } - kernel = backend_ctx->kernel_mul_mm_f32_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - cl_mem mem_src0 = extra0->data_device; - cl_mem mem_src1 = extra1->data_device; - - cl_ulong nb00_cont = nb00; - cl_ulong nb01_cont = nb01; - cl_ulong nb02_cont = nb02; - cl_ulong nb03_cont = nb03; - - cl_ulong nb10_cont = nb10; - cl_ulong nb11_cont = nb11; - cl_ulong nb12_cont = nb12; - cl_ulong nb13_cont = nb13; - - cl_ulong offset0_cont = offset0; - cl_ulong offset1_cont = offset1; - - if (!ggml_is_contiguous(src0)) { - backend_ctx->prealloc_src0.allocate(backend_ctx->context, ggml_nbytes(src0)); - ggml_cl_copy_to_contiguous(backend, src0, backend_ctx->prealloc_src0.buffer, - nb00_cont, nb01_cont, nb02_cont, nb03_cont); - mem_src0 = backend_ctx->prealloc_src0.buffer; - offset0_cont = 0; - } - - if (!ggml_is_contiguous(src1)) { - backend_ctx->prealloc_src1.allocate(backend_ctx->context, ggml_nbytes(src1)); - ggml_cl_copy_to_contiguous(backend, src1, backend_ctx->prealloc_src1.buffer, - nb10_cont, nb11_cont, nb12_cont, nb13_cont); - mem_src1 = backend_ctx->prealloc_src1.buffer; - offset1_cont = 0; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &mem_src0)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0_cont)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &mem_src1)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1_cont)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_F16: { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (ggml_cl_can_use_adreno_xmem_gemm_f16_f32(backend_ctx, src0, src1, dst)) { - ggml_cl_mul_mat_f16_f32_adreno_xmem(backend, src0, src1, dst); - return; - } -#endif - static const char * mm_narrow_n_env = getenv("GGML_OPENCL_MM_NARROW_N"); - const bool use_narrow_n = (mm_narrow_n_env == nullptr || mm_narrow_n_env[0] != '0') && ne11 >= 2 && ne11 <= 8; - kernel = use_narrow_n ? backend_ctx->kernel_mul_mm_f16_f32_l4_lm_n8 : backend_ctx->kernel_mul_mm_f16_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - cl_mem mem_src0 = extra0->data_device; - cl_mem mem_src1 = extra1->data_device; - - cl_ulong nb00_cont = nb00; - cl_ulong nb01_cont = nb01; - cl_ulong nb02_cont = nb02; - cl_ulong nb03_cont = nb03; - - cl_ulong nb10_cont = nb10; - cl_ulong nb11_cont = nb11; - cl_ulong nb12_cont = nb12; - cl_ulong nb13_cont = nb13; - - cl_ulong offset0_cont = offset0; - cl_ulong offset1_cont = offset1; - - if (!ggml_is_contiguous(src0)) { - backend_ctx->prealloc_src0.allocate(backend_ctx->context, ggml_nbytes(src0)); - ggml_cl_copy_to_contiguous(backend, src0, backend_ctx->prealloc_src0.buffer, - nb00_cont, nb01_cont, nb02_cont, nb03_cont); - mem_src0 = backend_ctx->prealloc_src0.buffer; - offset0_cont = 0; - } - - if (!ggml_is_contiguous(src1)) { - backend_ctx->prealloc_src1.allocate(backend_ctx->context, ggml_nbytes(src1)); - ggml_cl_copy_to_contiguous(backend, src1, backend_ctx->prealloc_src1.buffer, - nb10_cont, nb11_cont, nb12_cont, nb13_cont); - mem_src1 = backend_ctx->prealloc_src1.buffer; - offset1_cont = 0; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &mem_src0)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0_cont)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &mem_src1)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1_cont)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); - - // BN=8/TN=1 keeps 128 threads for small batches, including attention KQ/KQV. - const int bn = use_narrow_n ? 8 : 64; - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, bn)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q1_0: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q1_0_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q1_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q1_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q2_0: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q2_0_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q2_0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q2_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q4_0: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q4_0_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q4_1: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q4_1_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_1->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_1->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_1->m)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q5_0: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q5_0_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q5_1: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q5_1_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_1->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_1->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_1->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_1->m)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q8_0: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q8_0_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q8_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ4_NL: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq4_nl_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_nl->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_nl->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ4_XS: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq4_xs_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_xs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_xs->sl)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq4_xs->sh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq4_xs->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q2_K: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q2_k_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q2_K->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q2_K->sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q2_K->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q3_K: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q3_k_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q3_K->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q3_K->hm)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q3_K->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q3_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ3_S: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq3_s_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_s->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_s->sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_s->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq3_s->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq3_s->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ3_XXS: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq3_xxs_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_xxs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_xxs->sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_xxs->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ1_M: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq1_m_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_m->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_m->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_m->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ1_S: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq1_s_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_s->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_s->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_s->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ2_S: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq2_s_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_s->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_s->sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_s->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq2_s->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq2_s->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ2_XS: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq2_xs_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xs->sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xs->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_IQ2_XXS: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_iq2_xxs_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - offset0 = src0->view_offs; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xxs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xxs->sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xxs->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q4_K: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q4_k_f32_l4_lm; - // (BM*BN)/(TM*TN): Intel uses an 8x8 microtile (WG=64), others 4x8 (WG=128) - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_K->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_K->s)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_K->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_K->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q5_K: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q5_k_f32_l4_lm; - nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; // Intel 8x8 microtile - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_K->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_K->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_K->dm)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - case GGML_TYPE_Q6_K: { - if (ne11 < 32) { - break; - } - if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { - break; - } - - kernel = backend_ctx->kernel_mul_mm_q6_k_f32_l4_lm; - nth0 = 128; // calculated as (BM*BN)/(TM*TN) - - int batch_stride_a = ne00*ne01; - int batch_stride_b = ne10*ne11; - int batch_stride_d = ne0*ne1; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_a - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_b - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne01)); // stride_d - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); - - // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. - size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } - default: - break; - } - } - - if (src0t == GGML_TYPE_F16 && src1t == GGML_TYPE_F32 && - src0->ne[1] > 32 && // M > 32 - src1->ne[1] > 32 && // N > 32 - src0->ne[0] > 32 && // K > 32 - src0->ne[2] == 1 && src0->ne[3] == 1 && - src1->ne[2] == 1 && src1->ne[3] == 1 && - ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && - backend_ctx->kernel_mul_mat_f16_f32_tiled != NULL) { - ggml_cl_mul_mat_f16_f32_tiled(backend, src0, src1, dst); - return; - } - - if (!ggml_is_transposed(src0) && - !ggml_is_transposed(src1) && - src1t == GGML_TYPE_F32 && - ne00%32 == 0 && - ne11 > 2) { -#ifdef GGML_OPENCL_SOA_Q - // Set up kernel. - switch(src0t) { - case GGML_TYPE_Q4_0: - // This should have been satisfied. - GGML_ASSERT(ne11 == ne1); - GGML_ASSERT(ne01 == ne0); - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - - kernel = backend_ctx->kernel_mul_mat_q4_0_f32_1d_16x_flat; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - - kernel = backend_ctx->kernel_mul_mat_q4_0_f32_1d_8x_flat; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); - break; - default: - break; - } - - // Launch kernel. - if (src0t == GGML_TYPE_Q4_0) { - size_t global_work_size[] = {(size_t)(ne01 + 7)/8*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - if (backend_ctx->gpu_family == INTEL) { - // Set global size for Intel. It uses 16x output values. - global_work_size[0] = (size_t)(ne01 + 15)/16*nth0; - global_work_size[1] = (size_t)ne11*nth1; - global_work_size[2] = (size_t)ne12*ne13; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - return; - } -#else // GGML_OPENCL_SOA_Q - // TODO: add block_q4_0 variant. -#endif // GGML_OPENCL_SOA_Q - } - - // use custom matrix x vector kernel - bool use_f16_mrow = false; - switch (src0t) { - case GGML_TYPE_F32: - //GGML_ASSERT(ne02 == ne12); - GGML_ASSERT(src1t == GGML_TYPE_F32); - kernel = backend_ctx->kernel_mul_mat_f32_f32; - nrows = 4; - if (f32_use_mv && ne11 > 1 && backend_ctx->kernel_mul_mv_f32_f32_r2 != nullptr) { - kernel = backend_ctx->kernel_mul_mv_f32_f32_r2; - } - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 32; - nth1 = 1; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); - break; - case GGML_TYPE_F16: - //GGML_ASSERT(ne02 == ne12); - if (backend_ctx->gpu_family == INTEL) { - nth0 = 32; - nth1 = 1; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - if (src1t == GGML_TYPE_F32) { - // heuristic for packing more work for Adreno - const bool adreno_use_lane_split = - backend_ctx->gpu_family == ADRENO && - ne11 == 1 && - ne01 >= 8 && - ne00 % 4 == 0 && - r3 == 1 && r2 >= 1 && r2 <= 8 && - (ne12 % r2) == 0; - - if (ne11 * ne12 < 4) { - // Decode (single token): the legacy _1row runs one 64-lane - // subgroup per WG (one output row), under-utilizing BW. Route the - // wide f16 weight matmuls (attn proj + lm_head) to the multi-row - // variant: MROW rows per WG -> more loads in flight + activation - // staged once in __local. ne00<=8192 bounds the LDS. The mrow WG - // is 64 x MROW = 1024 work-items (> Intel's 512 max) and reduces - // within a 64-wide subgroup, so skip on Intel. - if (backend_ctx->f16_mrow && backend_ctx->gpu_family != INTEL && - backend_ctx->kernel_mul_mat_f16_f32_mrow != nullptr && - ne00 >= 128 && ne01 >= 8 && ne00 % 4 == 0 && ne00 <= 8192) { - // The register-blocked / half8 variants cast the src0 row pointer to - // half4 / half8 (8- and 16-byte loads) with no scalar fallback inside - // the kernel. ne00 % 4 == 0 constrains the element count per row, NOT - // the byte stride between rows: a permuted or strided src0 (or a view - // at an odd offset) can leave nb01/nb02/nb03 unaligned. Only take them - // when every row this dispatch touches is aligned; the base mrow kernel - // re-checks per row and falls back to its scalar loop. - const cl_ulong row_addr_bits = offset0 | nb01 | nb02 | nb03; - const bool aligned8 = (row_addr_bits & 7) == 0; - const bool aligned16 = (row_addr_bits & 15) == 0; - - // Register-blocked variants: each subgroup does RPT rows (more - // weight loads in flight per lane). 8/16 use half8 (128-bit) - // loads, gated on ne00 % 8 == 0. - const int rpt = backend_ctx->f16_mrow_rpt; - if (rpt == 16 && ne00 % 8 == 0 && aligned16 && backend_ctx->kernel_mul_mat_f16_f32_mrow_h8r2 != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_mrow_h8r2; - } else if (rpt == 8 && ne00 % 8 == 0 && aligned16 && backend_ctx->kernel_mul_mat_f16_f32_mrow_h8 != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_mrow_h8; - } else if (rpt == 4 && aligned8 && backend_ctx->kernel_mul_mat_f16_f32_mrow_r4 != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_mrow_r4; - } else if (rpt == 2 && aligned8 && backend_ctx->kernel_mul_mat_f16_f32_mrow_r2 != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_mrow_r2; - } else { - kernel = backend_ctx->kernel_mul_mat_f16_f32_mrow; - } - use_f16_mrow = true; - } else { - kernel = backend_ctx->kernel_mul_mat_f16_f32_1row; - } - } else if (adreno_use_lane_split && ne00 >= 64 && ne00 <= 128) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_dr_lq; - nrows = 1; - } else if (adreno_use_lane_split && r2 >= 2 && ne00 > 128 && ne00 <= 256) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_dr_ls; - nrows = 1; - } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) { - // multi-output decode variants when Q is a single row - static const char * mm_force_l4_env = getenv("GGML_OPENCL_MM_F16_FORCE_L4"); - static const bool mm_force_l4_on = (mm_force_l4_env != nullptr && mm_force_l4_env[0] != '0'); - const bool can_multi_out = !mm_force_l4_on && ne11 == 1 && ne01 >= 64 && ne01 % 8 == 0; - // paired-K-row variant that doubles per-wave-cycle - static const char * mm_kq_pair_env = getenv("GGML_OPENCL_MM_KQ_PAIR"); - static const bool mm_kq_pair_on = (mm_kq_pair_env != nullptr && mm_kq_pair_env[0] != '0'); - // GQA-coalesced variant that reads each K-row once and - // emits gqa_ratio outputs - static const char * mm_kq_gqa_env = getenv("GGML_OPENCL_MM_KQ_GQA"); - static const bool mm_kq_gqa_on = (mm_kq_gqa_env != nullptr && mm_kq_gqa_env[0] != '0'); - // GQA-coalesced KQV variant (DK=128/r2=8/r3=1) that reads - // each V slab once per K-head and emits all r2 Q-heads - static const char * mm_kqv_gqa_env = getenv("GGML_OPENCL_MM_KQV_GQA"); - static const bool mm_kqv_gqa_on = (mm_kqv_gqa_env != nullptr && mm_kqv_gqa_env[0] != '0'); - if (can_multi_out && (ne01 % 16) == 0 && ne00 == 128 && r2 == 8 && r3 == 1 && mm_kq_gqa_on && - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4 != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4; - nrows = 1; - } else if (can_multi_out && ne00 <= 256 && mm_kq_pair_on && - backend_ctx->kernel_mul_mat_f16_f32_l4_x8_pair != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_x8_pair; - nrows = 1; - } else if (can_multi_out && ne00 <= 256 && - backend_ctx->kernel_mul_mat_f16_f32_l4_x8 != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_x8; - nrows = 1; - } else if (can_multi_out && ne01 == 128 && r2 == 8 && r3 == 1 && mm_kqv_gqa_on && - backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa; - nrows = 1; - } else if (can_multi_out && - backend_ctx->kernel_mul_mat_f16_f32_l4_y8 != nullptr) { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_y8; - nrows = 1; - } else if (ne11 == 1) { - // Decode shapes that don't satisfy the x8/y8 row - // constraints (ne01 < 64 or ne01 % 8 != 0) fall back to - // upstream's 4-output _dr kernel. - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4_dr; - nrows = 1; // not used by this kernel - } else { - kernel = backend_ctx->kernel_mul_mat_f16_f32_l4; - nrows = ne11; - } - } else { - kernel = backend_ctx->kernel_mul_mat_f16_f32; - nrows = 4; - } - } else { - kernel = backend_ctx->kernel_mul_mat_f16_f16; - nrows = 4; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); - if (use_f16_mrow) { - const int MROW = 16; // must match MROW in mul_mv_f16_f32_mrow.cl - // rows-per-subgroup multiplier for the selected variant: - // 1/2/4 -> half4 register blocking; 8 -> half8(1 row); 16 -> half8(2 rows) - const int rpt = backend_ctx->f16_mrow_rpt; - int rmul; - if (rpt == 16) rmul = (ne00 % 8 == 0) ? 2 : 1; - else if (rpt == 8) rmul = 1; - else rmul = rpt; // 1,2,4 - const int rows_per_wg = MROW * rmul; - // __local activation buffer: ne00 floats, rounded up for float4 access - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float) * ((ne00 + 3) / 4 * 4), nullptr)); - size_t mrow_global[] = { (size_t)((ne01 + rows_per_wg - 1) / rows_per_wg) * 64, (size_t)ne11 * MROW, (size_t)ne12 * ne13 }; - size_t mrow_local[] = { 64, (size_t)MROW, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, mrow_global, mrow_local, dst); - return; - } - break; - case GGML_TYPE_Q1_0: { -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q1_0_f32_flat; - - // nth0 - subgroup size - // nth1 - number of subgroups per workgroup - // ndst - number of output values per workgroup = output per subgroup * number of subgroups - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = nth1*4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = nth1*4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q1_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q1_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_q1_0_f32; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = nth1*4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = nth1*4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q2_0: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q2_0_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q2_0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q2_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_q2_0_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q4_0: - // This should have been satisfied. - GGML_ASSERT(ne11 == ne1); - GGML_ASSERT(ne01 == ne0); - -#ifdef GGML_OPENCL_SOA_Q - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - - kernel = backend_ctx->kernel_mul_mat_q4_0_f32_8x_flat; - ndst = 8; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - - kernel = backend_ctx->kernel_mul_mat_q4_0_f32_8x_flat; - ndst =8; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#else // GGML_OPENCL_SOA_Q - if (backend_ctx->gpu_family == INTEL) { - // Use 1D local size. Each workgroup is a SIMD group. Each SIMD - // group produces N_DST (4 for Q4_0 kernel) values in the result. - // The number of workgroups on dim 0 (the leading dimension) is - // the nearest multiple of 4 that covers ne0 (equals ne01). - nth0 = 16; - nth1 = 1; - - kernel = backend_ctx->kernel_mul_mat_q4_0_f32; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - - kernel = backend_ctx->kernel_mul_mat_q4_0_f32_v; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - case GGML_TYPE_Q4_1: { -#ifdef GGML_OPENCL_SOA_Q - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - kernel = backend_ctx->kernel_mul_mv_q4_1_f32_flat; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_1->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_1->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_1->m)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r3)); -#else - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - kernel = backend_ctx->kernel_mul_mv_q4_1_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q5_0: { -#ifdef GGML_OPENCL_SOA_Q - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - kernel = backend_ctx->kernel_mul_mv_q5_0_f32_flat; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_0->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_0->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r3)); -#else - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - kernel = backend_ctx->kernel_mul_mv_q5_0_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q5_1: { -#ifdef GGML_OPENCL_SOA_Q - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - kernel = backend_ctx->kernel_mul_mv_q5_1_f32_flat; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_1->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_1->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_1->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_1->m)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r3)); -#else - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - kernel = backend_ctx->kernel_mul_mv_q5_1_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q8_0: { -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q8_0_f32_flat; - - // nth0 - subgroup size - // nth1 - number of subgroups per workgroup - // ndst - number of output values per workgroup = output per subgroup * number of subgroups - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = nth1*4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = nth1*4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q8_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_q8_0_f32; - - // nth0 - subgroup size - // nth1 - number of subgroups per workgroup - // ndst - number of output values per workgroup = output per subgroup * number of subgroups - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = nth1*4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = nth1*4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ4_NL: { -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq4_nl_f32_flat; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 8; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 8; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_nl->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_nl->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq4_nl_f32; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ4_XS: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq4_xs_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_xs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_xs->sl)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq4_xs->sh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq4_xs->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq4_xs_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q2_K: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q2_K_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q2_K->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q2_K->sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q2_K->dm)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_q2_K_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q3_K: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 2; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 2; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q3_K_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q3_K->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q3_K->hm)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q3_K->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q3_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_q3_K_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ3_XXS: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - + switch (op->op) { + case GGML_OP_NONE: + return true; + case GGML_OP_GET_ROWS: + switch (op->src[0]->type) { + case GGML_TYPE_I32: + return op->type == GGML_TYPE_I32; + case GGML_TYPE_F32: + case GGML_TYPE_F16: + return true; + case GGML_TYPE_Q4_0: #ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq3_xxs_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_xxs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_xxs->sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_xxs->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq3_xxs_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); + // We do not support flattened Q4_0 (and possibly other Q's) + return false; +#else // GGML_OPENCL_SOA_Q + return true; #endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ3_S: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + default: + return false; } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq3_s_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_s->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_s->sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_s->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq3_s->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq3_s->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq3_s_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ1_M: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_SET_ROWS: + { + // TODO: add support + // ref: https://github.com/ggml-org/llama.cpp/pull/14274 +#pragma message("TODO: implement BF16, Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, IQ4_NL support (https://github.com/ggml-org/llama.cpp/pull/14661)") + if (op->src[0]->type != GGML_TYPE_F32) { + return false; + } + switch (op->type) { + case GGML_TYPE_F16: + case GGML_TYPE_F32: + case GGML_TYPE_Q8_0: + case GGML_TYPE_Q4_0: + return (op->src[1]->type == GGML_TYPE_I64 || op->src[1]->type == GGML_TYPE_I32); + default: + return false; + } } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq1_m_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_m->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_m->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_m->sc)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq1_m_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ1_S: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_CPY: + case GGML_OP_DUP: + case GGML_OP_CONT: + switch (op->src[0]->type) { + case GGML_TYPE_F32: + switch (op->type) { + case GGML_TYPE_I32: + case GGML_TYPE_F16: + case GGML_TYPE_F32: + return true; + default: + return false; + } + case GGML_TYPE_F16: + switch (op->type) { + case GGML_TYPE_F16: + case GGML_TYPE_F32: + return true; + default: + return false; + } + case GGML_TYPE_I32: + switch (op->type) { + case GGML_TYPE_F32: + case GGML_TYPE_I32: + return true; + default: + return false; + } + default: + return false; } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq1_s_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_s->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_s->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_s->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq1_s_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; + case GGML_OP_SET: { + return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_I32) && + op->type == op->src[0]->type && + op->type == op->src[1]->type; } - case GGML_TYPE_IQ2_S: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_SCALE: + return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && + op->src[0]->type == op->type && ggml_is_contiguous_rows(op->src[0]); + case GGML_OP_ADD: + if (op->type == GGML_TYPE_F16) { + const bool src0_ok = op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_F32; + const bool src1_ok = op->src[1]->type == GGML_TYPE_F16 || op->src[1]->type == GGML_TYPE_F32; + if (src0_ok && src1_ok) { + return true; + } } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq2_s_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_s->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_s->sg)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_s->qh)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq2_s->sc)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq2_s->d)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq2_s_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ2_XS: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_MUL: + case GGML_OP_DIV: + case GGML_OP_SUB: + return (op->src[0]->type == op->src[1]->type) && + (op->src[0]->type == op->type) && + (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); + case GGML_OP_ADD_ID: + return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_LOG: + return op->src[0]->type == op->type && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); + case GGML_OP_SQR: + case GGML_OP_SQRT: + return (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16) && + ggml_is_contiguous(op->src[0]); + case GGML_OP_UNARY: + switch (ggml_get_unary_op(op)) { + case GGML_UNARY_OP_SILU: + return op->src[0]->type == op->type && + (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); + case GGML_UNARY_OP_XIELU: + for (int64_t ne : op->src[0]->ne) { + if (ne > INT_MAX) { + return false; + } + } + return op->src[0]->type == op->type && + (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); + case GGML_UNARY_OP_GELU: + case GGML_UNARY_OP_RELU: + case GGML_UNARY_OP_GELU_ERF: + case GGML_UNARY_OP_GELU_QUICK: + return ggml_is_contiguous(op->src[0]) && op->src[0]->type == GGML_TYPE_F32; + case GGML_UNARY_OP_SIGMOID: + return op->src[0]->type == op->type && + (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_BF16); + case GGML_UNARY_OP_TANH: + case GGML_UNARY_OP_NEG: + case GGML_UNARY_OP_EXP: + // Adreno F16 exp/expm1 overflow even post-half->float convert. + return op->src[0]->type == GGML_TYPE_F32; + case GGML_UNARY_OP_EXPM1: + return op->src[0]->type == GGML_TYPE_F32; + case GGML_UNARY_OP_ABS: + case GGML_UNARY_OP_SGN: + case GGML_UNARY_OP_STEP: + case GGML_UNARY_OP_ELU: + case GGML_UNARY_OP_HARDSWISH: + case GGML_UNARY_OP_HARDSIGMOID: + case GGML_UNARY_OP_FLOOR: + case GGML_UNARY_OP_CEIL: + case GGML_UNARY_OP_ROUND: + case GGML_UNARY_OP_TRUNC: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; + case GGML_UNARY_OP_SOFTPLUS: + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; + default: + return false; } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq2_xs_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xs->sc)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xs->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq2_xs_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_IQ2_XXS: { - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_GLU: + switch (ggml_get_glu_op(op)) { + case GGML_GLU_OP_GEGLU: + case GGML_GLU_OP_REGLU: + case GGML_GLU_OP_SWIGLU: + case GGML_GLU_OP_SWIGLU_OAI: + case GGML_GLU_OP_GEGLU_ERF: + case GGML_GLU_OP_GEGLU_QUICK: + case GGML_GLU_OP_SWIGLU_CLAMP: + return ggml_is_contiguous_1(op->src[0]) && (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16); + default: + return false; } - -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_iq2_xxs_f32_flat; - offset0 = src0->view_offs; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xxs->qs)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xxs->sas)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xxs->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_iq2_xxs_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q4_K: { -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q4_K_f32_flat; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 16; // 8->16 rows per subgroup — matches N_DST in mul_mv_q4_k_f32_flat.cl (32 spills) - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = 16; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_TRI: + return op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); + case GGML_OP_FILL: + return op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); + case GGML_OP_ARANGE: + return op->type == GGML_TYPE_F32; + case GGML_OP_CLAMP: + return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_SOFT_MAX: + case GGML_OP_NORM: + return true; + case GGML_OP_RMS_NORM: + return op->src[0]->type == GGML_TYPE_F32 && op->ne[0] % 4 == 0 && ggml_is_contiguous_rows(op->src[0]); + case GGML_OP_L2_NORM: + return ggml_is_contiguous_rows(op->src[0]); + case GGML_OP_REPEAT: + switch (op->type) { + case GGML_TYPE_F32: + case GGML_TYPE_F16: + case GGML_TYPE_I32: + case GGML_TYPE_I16: + case GGML_TYPE_BF16: + return op->src[0]->type == op->type; + default: + return false; } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_K->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_K->s)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_K->d)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_K->dm)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_q4_K_f32; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_PAD: + // TODO: add circular padding support for opencl, see https://github.com/ggml-org/llama.cpp/pull/16985 + if (ggml_get_op_params_i32(op, 8) != 0) { + return false; } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(int), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; + return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; + case GGML_OP_UPSCALE: { + ggml_scale_mode mode = (ggml_scale_mode)(ggml_get_op_params_i32(op, 0) & 0xFF); + const bool antialias = (ggml_scale_mode)(ggml_get_op_params_i32(op, 0) & GGML_SCALE_FLAG_ANTIALIAS); + return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && + (mode == GGML_SCALE_MODE_NEAREST || mode == GGML_SCALE_MODE_BILINEAR) && !antialias; } - case GGML_TYPE_Q5_K: { -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q5_K_f32_flat; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 8; // 4->8 rows per subgroup (2x activation reuse) - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = 16; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_K->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_K->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_K->dm)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_q5_K_f32; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 1; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 1; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } + case GGML_OP_CONV_2D: + return (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F16 && op->type == GGML_TYPE_F16) || + (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32) || + (op->src[0]->type == GGML_TYPE_F16 && op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32); + case GGML_OP_CONV_2D_DW: + return op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && + op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && + op->src[1]->nb[0] == sizeof(float) && op->nb[0] == sizeof(float) && + (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16); + case GGML_OP_SSM_CONV: + return (op->src[0]->type == GGML_TYPE_F32 && op->src[1]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32); + case GGML_OP_SSM_SCAN: { + if (op->type != GGML_TYPE_F32 || op->src[0]->type != GGML_TYPE_F32 || + op->src[1]->type != GGML_TYPE_F32 || op->src[2]->type != GGML_TYPE_F32 || + op->src[3]->type != GGML_TYPE_F32 || op->src[4]->type != GGML_TYPE_F32 || + op->src[5]->type != GGML_TYPE_F32 || op->src[6]->type != GGML_TYPE_I32) { + return false; + } - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(int), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q6_K: -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_q6_K_f32_flat; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = 16; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + const int64_t d_state = op->src[0]->ne[0]; + return d_state >= 1 && d_state <= 256 && (d_state & (d_state - 1)) == 0; } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r3)); - // The optimizer-barrier arg exists only in the ADRENO_OLD_COMPILER build of - // this kernel; conformant compilers get the original 17-arg signature. - if (backend_ctx->q6_k_flat_old_compiler) { - cl_uchar q6k_mask = 0xFF; // never 0xFE in prod; see the kernel note - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_uchar), &q6k_mask)); + case GGML_OP_GATED_DELTA_NET: + { + // Match the Vulkan backend: only F32 -> F32, S_v in {16, 32, 64, 128}. + if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) { + return false; + } + const int64_t S_v = op->src[2]->ne[0]; + return S_v == 16 || S_v == 32 || S_v == 64 || S_v == 128; } -#else - kernel = backend_ctx->kernel_mul_mv_q6_K_f32; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = 1; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = 1; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_CONCAT: + { + const ggml_type t = op->src[0]->type; + return op->src[1]->type == t && op->type == t && + !ggml_is_quantized(t) && ggml_blck_size(t) == 1 && + (ggml_type_size(t) == 1 || ggml_type_size(t) == 2 || + ggml_type_size(t) == 4 || ggml_type_size(t) == 8); } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); -#endif // GGML_OPENCL_SOA_Q - break; - case GGML_TYPE_MXFP4: { -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_mxfp4_f32_flat; - - cl_mem q; - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = nth1*2; - - q = extra0_mxfp4->q; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = nth1*2; - - q = extra0_mxfp4->q_img; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + case GGML_OP_TIMESTEP_EMBEDDING: + return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; + case GGML_OP_GROUP_NORM: + return ggml_is_contiguous(op->src[0]); + case GGML_OP_MUL_MAT: + if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) { + return false; } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_mxfp4->e)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r3)); -#else - kernel = backend_ctx->kernel_mul_mv_mxfp4_f32; - - if (backend_ctx->gpu_family == INTEL) { - nth0 = 16; - nth1 = 2; - ndst = nth1*2; - } else if (backend_ctx->gpu_family == ADRENO) { - nth0 = 64; - nth1 = 2; - ndst = nth1*2; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + if (ggml_cl_mul_mat_can_use_fwht(backend_ctx, op)) { + return true; } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r3)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(float)*nth0,nullptr)); -#endif - break; - } - default: - GGML_ASSERT(false && "not implemented"); - } - - if (src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_MXFP4 || - src0t == GGML_TYPE_Q4_1 || - src0t == GGML_TYPE_Q5_0 || - src0t == GGML_TYPE_Q5_1 || - src0t == GGML_TYPE_Q8_0 || - src0t == GGML_TYPE_Q1_0 || - src0t == GGML_TYPE_Q2_0 || - src0t == GGML_TYPE_IQ4_NL || - src0t == GGML_TYPE_Q2_K || src0t == GGML_TYPE_Q3_K || src0t == GGML_TYPE_IQ2_S || src0t == GGML_TYPE_IQ2_XS || src0t == GGML_TYPE_IQ2_XXS || src0t == GGML_TYPE_IQ1_S || src0t == GGML_TYPE_IQ1_M || src0t == GGML_TYPE_IQ3_S || src0t == GGML_TYPE_IQ3_XXS || src0t == GGML_TYPE_IQ4_XS) { - // Each SIMD group produces N_DST values in the result. Assuming each - // workgroup has N_SIMDGROUP SIMD groups, then each workgroup will - // produce N_DST*N_SIMDGROUP values in the result. Hence, the grid size - // (number of workgroups) will be a nearest multiple of - // N_DST*N_SIMDGROUP to cover the size of the dimension. Below, 4 is - // N_DST*N_SIMDGROUP (see the kernel for Q4_0 matmul). - size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (src0t == GGML_TYPE_Q4_K) { - size_t global_work_size[] = {(size_t)(ne01+ndst*nth1-1)/(ndst*nth1)*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (src0t == GGML_TYPE_Q5_K) { - size_t global_work_size[] = {(size_t)(ne01+ndst*nth1-1)/(ndst*nth1)*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (src0t == GGML_TYPE_Q6_K) { - size_t global_work_size[] = {(size_t)(ne01+ndst*nth1-1)/(ndst*nth1)*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_x8 || - kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_x8_pair || - kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_y8) { - // multi-output decode variants: each WG processes 8 outputs along ne01, ne11 == 1 - const int64_t n_wg_x = ne01 / 8; - size_t global_work_size[] = {(size_t)n_wg_x*nth0, (size_t)nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_x8_gqa4) { - // GQA-coalesced KQ: one WG per K-head emits N_K_ROWS_GQA=16 K-rows * r2 Q-heads - const int64_t n_wg_x = ne01 / 16; - size_t global_work_size[] = {(size_t)n_wg_x*nth0, (size_t)nth1, (size_t)ne02*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_y8_gqa) { - // GQA-coalesced KQV: one WG per K-head emits 8 DV-rows * r2 Q-heads - const int64_t n_wg_x = ne01 / 8; - size_t global_work_size[] = {(size_t)n_wg_x*nth0, (size_t)nth1, (size_t)ne02*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - if (kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_dr) { - const int NDST_DR = 4; - size_t global_work_size[] = {(size_t)CEIL_DIV(ne01, NDST_DR)*nth0, (size_t)nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_dr_ls) { - size_t global_work_size[] = {(size_t)CEIL_DIV(ne01, 2)*nth0, (size_t)nth1, (size_t)ne02*ne03}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else if (kernel == backend_ctx->kernel_mul_mat_f16_f32_l4_dr_lq) { - size_t global_work_size[] = {(size_t)CEIL_DIV(ne01, 4)*nth0, (size_t)nth1, (size_t)ne02*ne03}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } else { - int64_t ny = (ne11 + nrows - 1)/nrows; - int64_t nx = kernel == backend_ctx->kernel_mul_mv_f32_f32_r2 ? CEIL_DIV(ne01, 2) : ne01; - - size_t global_work_size[] = {(size_t)nx*nth0, (size_t)ny*nth1, (size_t)ne12*ne13}; - size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } - } -} - -static void moe_router_reoerder(ggml_backend_t backend, const ggml_tensor * src, int ne20) { - cl_int err; - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *)src->extra; - cl_ulong offset = extra->offset + src->view_offs; - - const int ne21 = src->ne[1]; - const int nb21 = src->nb[1]; - const int ne02 = nb21 / src->nb[0]; - const int n_tile_size = 32; - const int max_post_router_tile = (ne20 * ne21 / n_tile_size) + ne02; - - cl_buffer_region region; - - backend_ctx->prealloc_post_router.allocate(backend_ctx->context, sizeof(int) * max_post_router_tile * n_tile_size); - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - cl_mem post_router_buf = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - backend_ctx->prealloc_emap.allocate(backend_ctx->context, sizeof(short) * max_post_router_tile); - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - cl_mem emap_buf = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - if (sizeof(int) * ne02 > backend_ctx->prealloc_hist.size) { - backend_ctx->prealloc_hist.allocate(backend_ctx->context, sizeof(int) * ne02); - const int zero = 0; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_hist.buffer, &zero, sizeof(zero), 0, sizeof(int) * ne02, 0, nullptr, nullptr)); - } - region.origin = 0; - region.size = sizeof(int) * ne02; - cl_mem hist_buf = clCreateSubBuffer(backend_ctx->prealloc_hist.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - backend_ctx->prealloc_tile_offset.allocate(backend_ctx->context, sizeof(int) * ne02); - region.origin = 0; - region.size = sizeof(int) * ne02; - cl_mem tile_offset_buf = clCreateSubBuffer(backend_ctx->prealloc_tile_offset.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - backend_ctx->prealloc_slot_counter.allocate(backend_ctx->context, sizeof(int) * ne02); - region.origin = 0; - region.size = sizeof(int) * ne02; - cl_mem slot_counter_buf = clCreateSubBuffer(backend_ctx->prealloc_slot_counter.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - backend_ctx->prealloc_total_tiles.allocate(backend_ctx->context, sizeof(int)); - region.origin = 0; - region.size = sizeof(int); - cl_mem total_tiles_buf = clCreateSubBuffer(backend_ctx->prealloc_total_tiles.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); - CL_CHECK(err); - - // Histogram - cl_kernel kernel = backend_ctx->kernel_moe_histogram; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &hist_buf)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset)); - - size_t histogram_global_size[] = {(size_t)(((ne21 + 63) / 64) * 64), static_cast(ne20), 1}; - size_t histogram_local_size[] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, histogram_global_size, histogram_local_size, src); - - // Scan - kernel = backend_ctx->kernel_moe_scan; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &hist_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &tile_offset_buf)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &total_tiles_buf)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &slot_counter_buf)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_tile_size)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne02)); - - size_t scan_global_size[] = {1}; - size_t scan_local_size[] = {1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 1, scan_global_size, scan_local_size, src); - - // Fill - kernel = backend_ctx->kernel_moe_fill; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &post_router_buf)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &total_tiles_buf)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &n_tile_size)); - - size_t fill_global_size[] = {(size_t)(((max_post_router_tile + 63) / 64) * 64), n_tile_size, 1}; - size_t fill_local_size[] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, fill_global_size, fill_local_size, src); - - // Scatter. The deterministic variant is the default: kernel_moe_scatter derives - // each token's slot from an atomic counter, so the packing inside an expert - and - // with it the output of the ragged prefill GEMM - changes from run to run. Set - // GGML_OPENCL_MOE_STABLE_SCATTER=0 to restore the atomic version. - static const bool stable_scatter = []{ - const char * e = getenv("GGML_OPENCL_MOE_STABLE_SCATTER"); - return !e || e[0] == '\0' || e[0] != '0'; - }(); - - if (stable_scatter) { - kernel = backend_ctx->kernel_moe_scatter_stable; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &post_router_buf)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &emap_buf)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &tile_offset_buf)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset)); - - // one workgroup (one wave) per expert; each ranks its own tokens - size_t scatter_global_size[] = {64, (size_t)ne02}; - size_t scatter_local_size[] = {64, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, scatter_global_size, scatter_local_size, src); - } else { - kernel = backend_ctx->kernel_moe_scatter; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &post_router_buf)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &emap_buf)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &tile_offset_buf)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &slot_counter_buf)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offset)); - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, histogram_global_size, histogram_local_size, src); - } - - // [MOE_TILES] env-gated padding probe: read back total_tiles (= Sum_e - // ceil(k_e/n_tile_size)) and compare to the ideal tile count for the real - // routing count. Quantifies the per-expert tile-padding waste. Blocking - // readback perturbs timing -> diagnostic only. - if (getenv("GGML_OPENCL_MOE_TILES_DEBUG")) { - int h_total = 0; - clFinish(backend_ctx->queue); - CL_CHECK(clEnqueueReadBuffer(backend_ctx->queue, total_tiles_buf, CL_TRUE, 0, sizeof(int), &h_total, 0, NULL, NULL)); - const int routings = ne20 * ne21; - const int ideal = (routings + n_tile_size - 1) / n_tile_size; - const int slots = h_total * n_tile_size; - fprintf(stderr, "[MOE_TILES] routings=%d (ne20=%d ne21=%d nexp=%d) total_tiles=%d ideal=%d slots=%d pad=%.1f%%\n", - routings, ne20, ne21, ne02, h_total, ideal, slots, - routings > 0 ? 100.0 * (slots - routings) / routings : 0.0); - fflush(stderr); - } - - CL_CHECK(clReleaseMemObject(hist_buf)); - CL_CHECK(clReleaseMemObject(tile_offset_buf)); - CL_CHECK(clReleaseMemObject(total_tiles_buf)); - CL_CHECK(clReleaseMemObject(slot_counter_buf)); - CL_CHECK(clReleaseMemObject(post_router_buf)); - CL_CHECK(clReleaseMemObject(emap_buf)); -} - -// Use the per-token MoE GEMV instead of the tiled expert GEMM for small batches. -// The GEMV costs one weight pass per token, the GEMM pads every expert to a -// 32-token tile, so the GEMV wins while tokens rarely share an expert. -// Default on for X2E up to 4 tokens while 2 * tokens * used < experts. -// GGML_OPENCL_MOE_GEMV_MAX_TOK overrides with a plain token limit (1 = decode only). -static bool use_adreno_moe_gemv_small_batch(const ggml_backend_opencl_context * backend_ctx, int n_tokens, int n_used, int n_expert) { - if (n_tokens <= 1) { - return true; - } - static const char * env = getenv("GGML_OPENCL_MOE_GEMV_MAX_TOK"); - if (env) { - return n_tokens <= std::max(1, atoi(env)); - } - return backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && n_tokens <= 4 && - 2 * (int64_t) n_tokens * n_used < (int64_t) n_expert; -} - -static void ggml_cl_mul_mat_id_float(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - cl_kernel kernel = backend_ctx->kernel_mul_mv_id_f32_f32; - const ggml_tensor * src2 = dst->src[2]; - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *) src2->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset0 = extra0->offset + src0->view_offs; - const cl_ulong offset1 = extra1->offset + src1->view_offs; - const cl_ulong offset2 = extra2->offset + src2->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int ncols = src0->ne[0]; - const int ne11 = src1->ne[1]; - const int nrows = dst->ne[0]; - // BF16 tensors are stored as F16 on the device. Activations remain F32. - const int src0_f16 = src0->type == GGML_TYPE_F32 ? 0 : 1; - - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb20 = src2->nb[0]; - const cl_ulong nb21 = src2->nb[1]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - - // The router uses the IDs row stride as its expert count. - const size_t router_experts = src2->nb[1]/sizeof(int32_t); - if (src1->ne[2] >= 16 && ncols >= 64 && nrows >= 32 && ggml_is_contiguous(dst) && - src2->nb[0] == sizeof(int32_t) && src2->nb[1] % sizeof(int32_t) == 0 && - router_experts >= (size_t) src0->ne[2] && router_experts <= 1024 && - dst->ne[1]*dst->ne[2] >= (int64_t) router_experts*4 && - dst->ne[1]*dst->ne[2] >= 16384/nrows && - dst->ne[1]*dst->ne[2] <= INT_MAX - 32*(int64_t) router_experts) { - const int nused = dst->ne[1]; - const size_t max_tiles = (size_t) nused*dst->ne[2]/32 + router_experts; - moe_router_reoerder(backend, src2, nused); - backend_ctx->toggle_reorder = true; - const float zero = 0.0f; - CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, extrad->data_device, &zero, sizeof(zero), offsetd, ggml_nbytes(dst), 0, nullptr, nullptr)); - kernel = backend_ctx->kernel_mul_mm_id_f32_f32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &backend_ctx->prealloc_post_router.buffer)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &backend_ctx->prealloc_emap.buffer)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &backend_ctx->prealloc_total_tiles.buffer)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ncols)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &nrows)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &nused)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &src0_f16)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb2)); - size_t global_work_size[] = {(size_t) ((nrows + 63)/64)*128, max_tiles}; - size_t local_work_size[] = {128, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); - return; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ncols)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &src0_f16)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb20)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &nrows)); - - size_t global_work_size[] = {(size_t) ((dst->ne[0] + 3)/4)*64, (size_t) dst->ne[1], (size_t) dst->ne[2]}; - size_t local_work_size[] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - if (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16) { - ggml_cl_mul_mat_id_float(backend, src0, src1, dst); - return; - } - - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - const ggml_tensor * src2 = dst->src[2]; - GGML_ASSERT(src2); - GGML_ASSERT(src2->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offset2 = extra2->offset + src2->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_UNUSED(offset0); - -#ifdef GGML_OPENCL_SOA_Q - // SoA extra lives on view_src (view->extra is pre-SoA). - const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; - ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)soa0_src->extra; - ggml_tensor_extra_cl_q4_1 * extra0_q4_1 = (ggml_tensor_extra_cl_q4_1 *)soa0_src->extra; - ggml_tensor_extra_cl_q5_0 * extra0_q5_0 = (ggml_tensor_extra_cl_q5_0 *)soa0_src->extra; - ggml_tensor_extra_cl_q5_1 * extra0_q5_1 = (ggml_tensor_extra_cl_q5_1 *)soa0_src->extra; - ggml_tensor_extra_cl_q4_K * extra0_q4_K = (ggml_tensor_extra_cl_q4_K *)soa0_src->extra; - ggml_tensor_extra_cl_q5_K * extra0_q5_K = (ggml_tensor_extra_cl_q5_K *)soa0_src->extra; - ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *)soa0_src->extra; - ggml_tensor_extra_cl_mxfp4 * extra0_mxfp4 = (ggml_tensor_extra_cl_mxfp4 *)soa0_src->extra; - ggml_tensor_extra_cl_q8_0 * extra0_q8_0 = (ggml_tensor_extra_cl_q8_0 *)soa0_src->extra; - -#endif - - // TODO: general MoE for the following types - (void)extra0_q4_1; - (void)extra0_q5_0; - (void)extra0_q5_1; - (void)extra0_q4_K; - (void)extra0_q5_K; - (void)extra0_q6_K; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne10 = src1->ne[0]; - const int ne11 = src1->ne[1]; - const int ne12 = src1->ne[2]; - const int ne13 = src1->ne[3]; - - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const int ne20 = src2->ne[0]; - const int ne21 = src2->ne[1]; - - const cl_ulong nb21 = src2->nb[1]; - const cl_ulong nb20 = src2->nb[0]; - - UNUSED(nb20); - - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - const int ne2 = dst->ne[2]; - - GGML_UNUSED(ne2); - - const int r2 = ne12/ne02; - const int r3 = ne13/ne03; - const int dst_rows = ne20*ne21; // ne20 = n_used_experts, ne21 = n_rows - - GGML_ASSERT(ne00 == ne10); - - // the matmul kernels only write the rows an expert owns, so zero the skipped rows here - { - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - cl_kernel kernel_zero = backend_ctx->kernel_moe_zero_dst; - CL_CHECK(clSetKernelArg(kernel_zero, 0, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel_zero, 1, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel_zero, 2, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel_zero, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel_zero, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel_zero, 5, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel_zero, 6, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel_zero, 7, sizeof(int), &ne0)); - - size_t zero_local[3] = {1, 1, 64}; - size_t zero_global[3] = {(size_t) ne20, (size_t) ne21, 64}; - backend_ctx->enqueue_ndrange_kernel(kernel_zero, 3, zero_global, zero_local, dst); - } - - int sgs = 32; // subgroup size - int nsg = 1; // number of subgroups - int nrows = 1; // number of row in src1 - int ndst = 4; // number of values produced by each subgroup - - const int n_tile_size = 32; - const int max_post_router_tile = (ne20 * ne21 / n_tile_size) + ne02; - - GGML_UNUSED(max_post_router_tile); - - cl_kernel kernel; - - // subgroup mat vec - switch (src0->type) { - case GGML_TYPE_Q4_0: { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_q4_0_f32_ns; - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20 * ne12); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - const int ids_stride = (int) (nb21 / sizeof(int)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - - } else { // for gemm - // dp4a (int8) prefill GEMM variant - static const char * q4_0_moe_dp4a_env = getenv("GGML_OPENCL_Q4_0_MOE_DP4A"); - - // It turns out that the prebuilt kernel only outperforms the dp4a variant (on X2-90) - // at very large routing counts, so we gate its use accordingly using moe_bin_min, - // which can be overridden via the GGML_OPENCL_MOE_BIN_MIN_ROUTINGS environment variable. - // The routing count is ne20 * ne21 (n_expert_used * n_tokens). - static const char * moe_bin_min_env = getenv("GGML_OPENCL_MOE_BIN_MIN_ROUTINGS"); - const int moe_bin_min = moe_bin_min_env ? atoi(moe_bin_min_env) : 4096; - - // whether bin kernels are available - const bool bin_available = backend_ctx->kernel_gemm_moe_q4_0_f32_ns_bin != nullptr; - const bool dp4a_bin_available = backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_bin != nullptr; - - bool use_moe_dp4a = q4_0_moe_dp4a_env - ? (atoi(q4_0_moe_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E - && (dp4a_bin_available || !bin_available - || (int)(ne20 * ne21) < moe_bin_min)); - // dot prod has to be available - use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; - - const bool use_bin_kernel = bin_available && !use_moe_dp4a; - - kernel = use_bin_kernel - ? backend_ctx->kernel_gemm_moe_q4_0_f32_ns_bin - : backend_ctx->kernel_gemm_moe_q4_0_f32_ns; - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; - cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; - cl_mem buf_src2, buf_src2_emap; - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * q4_0_moe_malu_env = getenv("GGML_OPENCL_Q4_0_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!q4_0_moe_malu_env || atoi(q4_0_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin, - { extra0_q4_0->q_img, extra0_q4_0->d }, true, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels - { - static const char * q4_0_moe_coopmat_env = getenv("GGML_OPENCL_Q4_0_MOE_COOPMAT"); - if (!use_moe_dp4a && (q4_0_moe_coopmat_env ? (atoi(q4_0_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_q4_0_f32_ns_coopmat != nullptr) { - unsigned short cp_map_ratio = ne20 / ne11; - GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->kernel_gemm_moe_q4_0_f32_ns_coopmat, - { extra0_q4_0->q_img, extra0_q4_0->d }, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - if (!use_moe_dp4a) { - // Create image for reordered src1 - // Use pre-allocated placeholder - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1; - cl_image_desc image_desc_buf_src1; - image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - if (use_bin_kernel) { - // bin kernel uses slightly different image format - image_format_buf_src1 = {CL_R, CL_FLOAT}; - image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); - } - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - } - - // MoE kernel prepare - // Create sub buffer for dst - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - if (use_moe_dp4a) { - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - - // fused reorder + q8_1 quant straight from the original activations - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - // dp4a GEMM - cl_kernel dk = backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a; - if (backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_bin) { - dk = backend_ctx->kernel_gemm_moe_q4_0_q8_1_dp4a_bin; - } - - int aidx = 0; - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_0->q_img)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); - return; - } - - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->q_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); + if (op->src[0]->type == GGML_TYPE_F16) { + return true; + } else if (op->src[0]->type == GGML_TYPE_BF16) { + return true; + } else if (op->src[0]->type == GGML_TYPE_F32) { + return op->src[1]->type == GGML_TYPE_F32; + } else if (op->src[0]->type == GGML_TYPE_Q1_0) { + return op->src[1]->type == GGML_TYPE_F32; + } else if (op->src[0]->type == GGML_TYPE_Q4_0) { + // Non-contig src0 routes through on-device dequant-to-f16. + return op->src[1]->type == GGML_TYPE_F32; + } else if (op->src[0]->type == GGML_TYPE_IQ2_XXS) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq2_xxs_use_noshuffle(backend_ctx, weight)) { + return false; } - return; - } // fallback to generic Q4_0 MoE kernel - -#endif // GGML_OPENCL_USE_ADRENO_KERNELS - kernel = backend_ctx->kernel_mul_mv_id_q4_0_f32_8x_flat; - - if (backend_ctx->gpu_family == INTEL) { - sgs = 16; - nsg = 1; - ndst = 8; - } else if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - nsg = 1; - ndst = 8; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &r3)); - - break; - } - case GGML_TYPE_Q4_1: { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_q4_1_f32_ns; - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20 * ne12); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - const int ids_stride = (int) (nb21 / sizeof(int)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->q)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->m)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - - } else { // for gemm - kernel = backend_ctx->kernel_gemm_moe_q4_1_f32_ns; - if (backend_ctx->kernel_gemm_moe_q4_1_f32_ns_bin) { - kernel = backend_ctx->kernel_gemm_moe_q4_1_f32_ns_bin; - } - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; - cl_mem buf_src2, buf_src2_emap; - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * q4_1_moe_malu_env = getenv("GGML_OPENCL_Q4_1_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!q4_1_moe_malu_env || atoi(q4_1_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin, - { extra0_q4_1->q_img, extra0_q4_1->d, extra0_q4_1->m }, true, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels - { - static const char * q4_1_moe_coopmat_env = getenv("GGML_OPENCL_Q4_1_MOE_COOPMAT"); - if ((q4_1_moe_coopmat_env ? (atoi(q4_1_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_q4_1_f32_ns_coopmat != nullptr) { - unsigned short cp_map_ratio = ne20 / ne11; - GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->kernel_gemm_moe_q4_1_f32_ns_coopmat, - { extra0_q4_1->q_img, extra0_q4_1->d, extra0_q4_1->m }, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // Create image for reordered src1 - // Use pre-allocated placeholder - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1; - cl_image_desc image_desc_buf_src1; - image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - if (backend_ctx->kernel_gemm_moe_q4_1_f32_ns_bin) { - // bin kernel uses slightly different image format - image_format_buf_src1 = {CL_R, CL_FLOAT}; - image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); - } - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - - // MoE kernel prepare - // Create sub buffer for dst - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->q_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->m)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_IQ2_XS) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq2_xs_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_IQ2_S) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq2_s_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_Q2_0) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_q2_0_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_IQ1_S) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq1_s_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_IQ1_M) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq1_m_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_IQ3_S) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq3_s_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_IQ3_XXS) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq3_xxs_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_IQ4_XS) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_iq4_xs_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_Q3_K) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_q3_k_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_Q2_K) { + const ggml_tensor * weight = op->src[0]->view_src; + if (weight && ggml_cl_q2_k_use_noshuffle(backend_ctx, weight)) { + return false; + } + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous_rows(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_Q4_1 || + op->src[0]->type == GGML_TYPE_Q5_0 || op->src[0]->type == GGML_TYPE_Q5_1 || + op->src[0]->type == GGML_TYPE_MXFP4 || + op->src[0]->type == GGML_TYPE_IQ4_NL || + op->src[0]->type == GGML_TYPE_Q4_K || + op->src[0]->type == GGML_TYPE_Q5_K || + op->src[0]->type == GGML_TYPE_Q6_K) { + // The E031.41 compiler (usually with A7x) miscompiles the flat K-quant + // GEMV kernels (kernel_mul_mv_q*_K_f32_flat) and makes lm_head run much + // slower than it should. So, make it fallback to CPU to preserve performance + // for this compiler series. + static const char * a7x_lmhead_env = getenv("GGML_OPENCL_A7X_LMHEAD_CPU"); + static const bool a7x_lmhead_cpu = (a7x_lmhead_env == nullptr || a7x_lmhead_env[0] != '0'); + if (a7x_lmhead_cpu && + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X && + (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K || + op->src[0]->type == GGML_TYPE_Q6_K) && + op->src[0]->ne[1] >= 32768) { // vocab-scale weight; no FFN/attn weight is this tall + return false; } - return; + return op->src[1]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]); + } else if (op->src[0]->type == GGML_TYPE_Q8_0) { + // ggml_cl_mul_mat_q8_0_f32_adreno now honors src1/dst view_offs (the + // activation sub-buffer starts at offset1 and the kernels take offsetd), + // so a broadcast q8_0 matmul (src1 batch > src0 batch, e.g. Qwen3.5-9B-UD + // / Qwen3.6-35B q8_0 GDN ssm_out) runs on GPU via the per-slice broadcast + // iteration in ggml_cl_mul_mat. No special-casing needed. + return op->src[1]->type == GGML_TYPE_F32; } -#endif //GGML_OPENCL_USE_ADRENO_KERNELS - } - case GGML_TYPE_Q5_0: { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_q5_0_f32_ns; - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20 * ne12); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - const int ids_stride = (int) (nb21 / sizeof(int)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qs)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - - } else { // for gemm - kernel = backend_ctx->kernel_gemm_moe_q5_0_f32_ns; - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; - cl_mem buf_src2, buf_src2_emap; - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Generic dp4a MoE GEMM - { - static const char * q5mdp4a_env = getenv("GGML_OPENCL_Q5_MOE_DP4A"); - const bool q5mdp4a_on = q5mdp4a_env ? (atoi(q5mdp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - const bool use_q5_moe_dp4a = q5mdp4a_on - && backend_ctx->kernel_gemm_moe_q8_1_dp4a_q50 != nullptr - && extra0_q5_0->scale != nullptr; - - if (use_q5_moe_dp4a) { - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - unsigned short map_ratio_q5 = ne20 / ne11; - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio_q5)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - cl_mem dp_sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - cl_image_format dp_ifd = {CL_R, CL_FLOAT}; - cl_image_desc dp_idd = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {dp_sub_buf_dst}}; - cl_mem dp_buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &dp_ifd, &dp_idd, NULL, &status); - CL_CHECK(status); - - int ne00i = (int)ne00, ne01i = (int)ne01; - cl_kernel dk = backend_ctx->kernel_gemm_moe_q8_1_dp4a_q50; - int has_min_q5 = 1; - int aidx = 0; - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->qs_img)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->scale)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->min)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &dp_buf_dst_image)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00i)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01i)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &has_min_q5)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(dp_sub_buf_dst); - clReleaseMemObject(dp_buf_dst_image); - return; - } - } - - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * q5_0_moe_malu_env = getenv("GGML_OPENCL_Q5_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!q5_0_moe_malu_env || atoi(q5_0_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin, - { extra0_q5_0->qs_img, extra0_q5_0->qh, extra0_q5_0->d }, false, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels - { - static const char * q5_0_moe_coopmat_env = getenv("GGML_OPENCL_Q5_0_MOE_COOPMAT"); - if ((q5_0_moe_coopmat_env ? (atoi(q5_0_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_q5_0_f32_ns_coopmat != nullptr) { - unsigned short cp_map_ratio = ne20 / ne11; - GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->kernel_gemm_moe_q5_0_f32_ns_coopmat, - { extra0_q5_0->qs_img, extra0_q5_0->qh, extra0_q5_0->d }, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // Create image for reordered src1 - // Use pre-allocated placeholder - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1; - cl_image_desc image_desc_buf_src1; - image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - - // MoE kernel prepare - // Create sub buffer for dst - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qs_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); - } - return; + return false; + case GGML_OP_MUL_MAT_ID: + if (op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) { + return op->src[1]->type == GGML_TYPE_F32 && op->src[2]->type == GGML_TYPE_I32 && op->type == GGML_TYPE_F32 && + op->src[0]->nb[0] == ggml_type_size(op->src[0]->type) && op->src[1]->nb[0] == sizeof(float) && + op->nb[0] == sizeof(float) && op->src[0]->ne[0] <= INT_MAX - 256 && op->ne[0] <= INT_MAX - 64 && + op->src[1]->ne[1] <= INT_MAX && op->ne[1] <= INT_MAX && op->ne[2] <= INT_MAX - 64; } -#endif //GGML_OPENCL_USE_ADRENO_KERNELS - } - case GGML_TYPE_Q5_1: { #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_q5_1_f32_ns; - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20 * ne12); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - const int ids_stride = (int) (nb21 / sizeof(int)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qs)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->m)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - } else { // for gemm - kernel = backend_ctx->kernel_gemm_moe_q5_1_f32_ns; - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; - cl_mem buf_src2, buf_src2_emap; - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * q5_1_moe_malu_env = getenv("GGML_OPENCL_Q5_1_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!q5_1_moe_malu_env || atoi(q5_1_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin, - { extra0_q5_1->qs_img, extra0_q5_1->qh, extra0_q5_1->d, extra0_q5_1->m }, true, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels - { - static const char * q5_1_moe_coopmat_env = getenv("GGML_OPENCL_Q5_1_MOE_COOPMAT"); - if ((q5_1_moe_coopmat_env ? (atoi(q5_1_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_q5_1_f32_ns_coopmat != nullptr) { - unsigned short cp_map_ratio = ne20 / ne11; - GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->kernel_gemm_moe_q5_1_f32_ns_coopmat, - { extra0_q5_1->qs_img, extra0_q5_1->qh, extra0_q5_1->d, extra0_q5_1->m }, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // Create image for reordered src1 - // Use pre-allocated placeholder - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1; - cl_image_desc image_desc_buf_src1; - image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - - // MoE kernel prepare - // Create sub buffer for dst - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qs_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->m)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); + if ((ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) && + use_adreno_moe_kernels(backend_ctx, op->src[0])) { + return false; + } +#endif + if (op->src[0]->type == GGML_TYPE_Q4_0 || + op->src[0]->type == GGML_TYPE_Q8_0 || + op->src[0]->type == GGML_TYPE_MXFP4) { + if (op->src[1]->type == GGML_TYPE_F32) { + return ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op->src[1]); } - return; } -#endif //GGML_OPENCL_USE_ADRENO_KERNELS - } - case GGML_TYPE_Q8_0: { + // q4_0, q8_0 and mxfp4 have general MUL_MAT_ID support, + // the quantizations here currently do not - they are only supported by Adreno with certain shapes + if (op->src[0]->type == GGML_TYPE_Q4_1 || + op->src[0]->type == GGML_TYPE_Q5_0 || + op->src[0]->type == GGML_TYPE_Q5_1 || + op->src[0]->type == GGML_TYPE_Q4_K || + op->src[0]->type == GGML_TYPE_Q5_K || + op->src[0]->type == GGML_TYPE_Q6_K) { #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - // MoE GEMM for q8_0 at prefill (ne12>1) - // There is no corresponding gemv_moe, so the code path is different here - static const char * moe_gemm_q8_env = getenv("GGML_OPENCL_MOE_GEMM_Q8"); - const bool moe_gemm_q8 = moe_gemm_q8_env - ? (atoi(moe_gemm_q8_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - if (moe_gemm_q8 && use_adreno_moe_kernels(backend_ctx, src0) && ne12 > 1) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - kernel = backend_ctx->kernel_gemm_moe_q8_0_f32_ns; - - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; - cl_mem buf_src2, buf_src2_emap; - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations (group tokens by expert into tiles of 32) - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Generic dp4a MoE GEMM - { - static const char * q8mdp4a_env = getenv("GGML_OPENCL_Q8_MOE_DP4A"); - const bool q8mdp4a_on = q8mdp4a_env ? (atoi(q8mdp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - const bool use_q8_moe_dp4a = q8mdp4a_on - && backend_ctx->kernel_gemm_moe_q8_1_dp4a_q80 != nullptr - && extra0_q8_0->scale != nullptr; - if (use_q8_moe_dp4a) { - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - unsigned short map_ratio_q8 = ne20 / ne11; - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio_q8)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - // dst image - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - cl_mem dp_sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - cl_image_format dp_ifd = {CL_R, CL_FLOAT}; - cl_image_desc dp_idd = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {dp_sub_buf_dst}}; - cl_mem dp_buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &dp_ifd, &dp_idd, NULL, &status); - CL_CHECK(status); - - int ne00i = (int)ne00, ne01i = (int)ne01; - cl_kernel dk = backend_ctx->kernel_gemm_moe_q8_1_dp4a_q80; - int has_min_q8 = 0; - int aidx = 0; - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q8_0->q)); // flat int8 codes [expert][row][K] - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q8_0->scale)); // uniform scale[16] - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q8_0->scale)); // dummy min (has_min=0, unread) - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &dp_buf_dst_image)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00i)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01i)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &has_min_q8)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(dp_sub_buf_dst); - clReleaseMemObject(dp_buf_dst_image); - return; - } + if (op->src[1]->type == GGML_TYPE_F32) { + return use_adreno_moe_kernels(backend_ctx, op->src[0]) + && ggml_is_contiguous(op->src[0]) + && ggml_is_contiguous(op->src[1]); } - - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - - // dst image - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q8_0->q)); // flat q8_0 quants - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q8_0->d)); // flat q8_0 scales - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); - return; +#endif + return false; } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_id_q8_0_f32_flat; - - if (backend_ctx->gpu_family == INTEL) { - sgs = 16; - nsg = 2; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - nsg = 2; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + return false; + case GGML_OP_RESHAPE: + case GGML_OP_VIEW: + case GGML_OP_PERMUTE: + case GGML_OP_TRANSPOSE: + return true; + case GGML_OP_DIAG: + return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_ROPE: { + const int mode = ((const int32_t *) op->op_params)[2]; + if (!ggml_rope_get_truncate(op)) { + return false; } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q8_0->q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); -#else - kernel = backend_ctx->kernel_mul_mv_id_q8_0_f32; - - if (backend_ctx->gpu_family == INTEL) { - sgs = 16; - nsg = 2; - ndst = 4; - } else if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - nsg = 2; - ndst = 4; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; + const bool is_vision = mode == GGML_ROPE_TYPE_VISION; + if (is_mrope && !is_vision) { + if (op->src[0]->type == GGML_TYPE_F32 || + op->src[0]->type == GGML_TYPE_F16) { + return true; + } + return false; } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); -#endif // GGML_OPENCL_SOA_Q - break; - } - case GGML_TYPE_Q4_K: { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_q4_k_f32_ns; - - // Weight-as-texture MoE decode GEMV - static const char * moe_decode_wimg_env = getenv("GGML_OPENCL_MOE_DECODE_WIMG"); - const bool moe_decode_wimg_on = moe_decode_wimg_env - ? (atoi(moe_decode_wimg_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - const bool use_moe_decode_wimg = moe_decode_wimg_on - && backend_ctx->kernel_gemv_moe_q4_k_f32_ns_wimg != nullptr - && extra0_q4_K->q_img != nullptr; - if (use_moe_decode_wimg) { - kernel = backend_ctx->kernel_gemv_moe_q4_k_f32_ns_wimg; - } - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20 * ne12); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - const int ids_stride = (int) (nb21 / sizeof(int)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), use_moe_decode_wimg ? &extra0_q4_K->q_img : &extra0_q4_K->q)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->dm)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->s)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - - } else { // for gemm - kernel = backend_ctx->kernel_gemm_moe_q4_k_f32_ns; - if (backend_ctx->kernel_gemm_moe_q4_k_f32_ns_bin) { - kernel = backend_ctx->kernel_gemm_moe_q4_k_f32_ns_bin; - } - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; - cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; - cl_mem buf_src2, buf_src2_emap; - - // dp4a (int8) prefill GEMM variant - static const char * q4k_moe_dp4a_env = getenv("GGML_OPENCL_Q4K_MOE_DP4A"); - bool use_moe_dp4a = (q4k_moe_dp4a_env != nullptr) - ? (atoi(q4k_moe_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E); - // dot prod has to be available - use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; - // bin kernel takes precedence, dp4a bin kernel has higher priority than normal bin kernel - if (backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_bin == nullptr) { - use_moe_dp4a = use_moe_dp4a && backend_ctx->kernel_gemm_moe_q4_k_f32_ns_bin == nullptr; - } - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * q4_k_moe_malu_env = getenv("GGML_OPENCL_Q4K_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!q4_k_moe_malu_env || atoi(q4_k_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin, - { extra0_q4_K->q_img, extra0_q4_K->d, extra0_q4_K->dm, extra0_q4_K->s }, true, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels - { - static const char * q4_k_moe_coopmat_env = getenv("GGML_OPENCL_Q4K_MOE_COOPMAT"); - if (!use_moe_dp4a && (q4_k_moe_coopmat_env ? (atoi(q4_k_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_q4_k_f32_ns_coopmat != nullptr) { - unsigned short cp_map_ratio = ne20 / ne11; - GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->kernel_gemm_moe_q4_k_f32_ns_coopmat, - { extra0_q4_K->q_img, extra0_q4_K->d, extra0_q4_K->dm, extra0_q4_K->s }, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - if (!use_moe_dp4a) { - // Create image for reordered src1 - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - if (backend_ctx->kernel_gemm_moe_q4_k_f32_ns_bin) { - // bin kernel uses slightly different image format - image_format_buf_src1 = {CL_R, CL_FLOAT}; - image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); - } - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - } - - // MoE kernel prepare - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - if (use_moe_dp4a) { - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - - // fused reorder + q8_1 quant straight from the original - // activations (no intermediate f32 reorder buffer) - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - // dp4a GEMM - cl_kernel dk = backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a; - if (backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_bin) { - dk = backend_ctx->kernel_gemm_moe_q4_k_q8_1_dp4a_bin; - } - - int aidx = 0; - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->q_img)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->d)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->dm)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->s)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); - return; - } - - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->q_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->dm)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->s)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); + if (is_vision) { + if (op->src[0]->type == GGML_TYPE_F32 || + op->src[0]->type == GGML_TYPE_F16) { + return true; } - return; + return false; } -#endif //GGML_OPENCL_USE_ADRENO_KERNELS + return op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16; } - case GGML_TYPE_Q5_K: { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_q5_k_f32_ns; - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20 * ne12); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - const int ids_stride = (int) (nb21 / sizeof(int)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->q)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->dm)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->s)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - - } else { // for gemm - kernel = backend_ctx->kernel_gemm_moe_q5_k_f32_ns; - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; - cl_mem buf_src2, buf_src2_emap; - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Generic dp4a MoE GEMM - { - static const char * q5kmdp4a_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A"); - const bool q5kmdp4a_on = q5kmdp4a_env ? (atoi(q5kmdp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); - bool use_moe_dp4a = q5kmdp4a_on - && backend_ctx->kernel_gemm_moe_q8_1_dp4a_q5k != nullptr - && extra0_q5_K->scale != nullptr; - // dot prod has to be available - use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; - - if (use_moe_dp4a) { - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - unsigned short map_ratio_q5k = ne20 / ne11; - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio_q5k)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - cl_mem dp_sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - cl_image_format dp_ifd = {CL_R, CL_FLOAT}; - cl_image_desc dp_idd = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {dp_sub_buf_dst}}; - cl_mem dp_buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &dp_ifd, &dp_idd, NULL, &status); - CL_CHECK(status); - - int ne00i = (int)ne00, ne01i = (int)ne01; - cl_kernel dk = backend_ctx->kernel_gemm_moe_q8_1_dp4a_q5k; - int has_min_q5k = 1; - int aidx = 0; - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->q_img)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->qh)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->scale)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->min)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &dp_buf_dst_image)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00i)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01i)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &has_min_q5k)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(dp_sub_buf_dst); - clReleaseMemObject(dp_buf_dst_image); - return; - } - } + case GGML_OP_SOLVE_TRI: + return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); + case GGML_OP_IM2COL: + return true; + case GGML_OP_IM2COL_3D: + return true; + case GGML_OP_ARGMAX: + ggml_cl_load_kernels_argmax(backend_ctx); + return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_I32 && + ggml_is_contiguous(op->src[0]) && ggml_is_contiguous(op) && + backend_ctx->get_kernel_workgroup_size(backend_ctx->argmax.kernel_argmax_f32_i32) >= 64; + case GGML_OP_LIGHTNING_INDEXER: + return op->src[0]->type == GGML_TYPE_F32 && + (op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16 || op->src[1]->type == GGML_TYPE_BF16) && + op->src[2]->type == GGML_TYPE_F32 && op->src[3]->type == GGML_TYPE_F16 && + op->src[0]->nb[0] == sizeof(float) && op->src[1]->nb[0] == ggml_type_size(op->src[1]->type) && + op->src[2]->nb[0] == sizeof(float) && op->src[3]->nb[0] == sizeof(ggml_fp16_t); + case GGML_OP_TOP_K: + return op->src[0]->type == GGML_TYPE_F32 && op->type == GGML_TYPE_I32; + case GGML_OP_TOP_K_MASK: + return (op->type == GGML_TYPE_F16 || op->type == GGML_TYPE_F32) && + op->src[0]->type == op->type && + op->src[0]->nb[0] == ggml_type_size(op->type) && op->nb[0] == ggml_type_size(op->type) && + op->src[1]->type == GGML_TYPE_I32 && + (!op->src[2] || op->src[2]->type == GGML_TYPE_F32) && + (!op->src[3] || op->src[3]->type == GGML_TYPE_I32) && + (!op->src[4] || op->src[4]->type == GGML_TYPE_I32); + case GGML_OP_ARGSORT: { + ggml_cl_load_kernels_argsort(backend_ctx); - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * q5_k_moe_malu_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!q5_k_moe_malu_env || atoi(q5_k_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin, - { extra0_q5_K->q_img, extra0_q5_K->qh, extra0_q5_K->s, extra0_q5_K->d, extra0_q5_K->dm }, true, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } + cl_kernel kernel = backend_ctx->argsort.kernel_argsort_f32_i32; + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels - { - static const char * q5_k_moe_coopmat_env = getenv("GGML_OPENCL_Q5K_MOE_COOPMAT"); - if ((q5_k_moe_coopmat_env ? (atoi(q5_k_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_q5_k_f32_ns_coopmat != nullptr) { - unsigned short cp_map_ratio = ne20 / ne11; - GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->kernel_gemm_moe_q5_k_f32_ns_coopmat, - { extra0_q5_K->q_img, extra0_q5_K->qh, extra0_q5_K->s, extra0_q5_K->d, extra0_q5_K->dm }, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } + int cols = 1; + while (cols < op->ne[0]) { + cols *= 2; + } - // Create image for reordered src1 - // Use pre-allocated placeholder - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - - // MoE kernel prepare - // Create sub buffer for dst - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->q_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->s)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->dm)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); + return cols <= max_workgroup_size && op->src[0]->type == GGML_TYPE_F32; + } + case GGML_OP_SUM_ROWS: + case GGML_OP_CUMSUM: + return op->src[0]->type == GGML_TYPE_F32 && ggml_is_contiguous(op->src[0]); + case GGML_OP_DSV4_HC_PRE: + case GGML_OP_DSV4_HC_POST: + for (int i = 0; i < (op->op == GGML_OP_DSV4_HC_PRE ? 2 : 4); ++i) { + if (op->src[i] && op->src[i]->type != GGML_TYPE_F32) { + return false; } - return; } -#endif //GGML_OPENCL_USE_ADRENO_KERNELS - } - case GGML_TYPE_Q6_K: { + return op->type == GGML_TYPE_F32 && ggml_is_contiguous(op); + case GGML_OP_MEAN: + return op->src[0]->type == GGML_TYPE_F32; + case GGML_OP_FLASH_ATTN_EXT: { + // K/V row lists and bias are not supported + if (op->src[5] != nullptr || ggml_flash_attn_ext_has_bias(op)) { + return false; + } #ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_q6_k_f32_ns; - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20 * ne12); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - const int ids_stride = (int) (nb21 / sizeof(int)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->ql)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - - } else { // for gemm - kernel = backend_ctx->kernel_gemm_moe_q6_k_f32_ns; - if (backend_ctx->kernel_gemm_moe_q6_k_f32_ns_bin) { - kernel = backend_ctx->kernel_gemm_moe_q6_k_f32_ns_bin; - } - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; - cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; - cl_mem buf_src2, buf_src2_emap; - - // dp4a (int8) q6_K MoE prefill GEMM - static const char * q6k_moe_dp4a_env = getenv("GGML_OPENCL_Q6K_MOE_DP4A"); - bool use_moe_dp4a = (q6k_moe_dp4a_env != nullptr) - ? (atoi(q6k_moe_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E - || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E); - // dot prod has to be available - use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; - // bin kernel takes precedence, dp4a bin kernel has higher priority than normal bin kernel - if (backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_bin == nullptr) { - use_moe_dp4a = use_moe_dp4a && backend_ctx->kernel_gemm_moe_q6_k_f32_ns_bin == nullptr; - } - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * q6_k_moe_malu_env = getenv("GGML_OPENCL_Q6K_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!q6_k_moe_malu_env || atoi(q6_k_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin, - { extra0_q6_K->ql_img, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, false, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels - { - static const char * q6_k_moe_coopmat_env = getenv("GGML_OPENCL_Q6K_MOE_COOPMAT"); - if (!use_moe_dp4a && (q6_k_moe_coopmat_env ? (atoi(q6_k_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_q6_k_f32_ns_coopmat != nullptr) { - unsigned short cp_map_ratio = ne20 / ne11; - GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->kernel_gemm_moe_q6_k_f32_ns_coopmat, - { extra0_q6_K->ql_img, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - if (!use_moe_dp4a) { - // Create image for reordered src1 - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - if (backend_ctx->kernel_gemm_moe_q6_k_f32_ns_bin) { - // bin kernel uses slightly different image format - image_format_buf_src1 = {CL_R, CL_FLOAT}; - image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); - } - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - } + if (use_fa_bin_kernels_prefill(backend_ctx, op->src[0], op->src[1], op->src[2])) { + return true; + } +#endif + // Some E17 compilers crash while building FA kernels. + if (adreno_e17_compiler_quirks(backend_ctx)) { + return false; + } + const ggml_tensor * q = op->src[0]; + const ggml_tensor * k = op->src[1]; + const ggml_tensor * v = op->src[2]; - // MoE kernel prepare - // Create sub buffer for dst - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - if (use_moe_dp4a) { - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - - // fused reorder + q8_1 quant from the original activations - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - cl_kernel dk = backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a; - if (backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_bin) { - dk = backend_ctx->kernel_gemm_moe_q6_k_q8_1_dp4a_bin; - } + const int dk = q->ne[0]; + const int dv = v->ne[0]; - int qi = 0; - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->ql_img)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(dk, qi++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); - return; - } + const struct { int dk; int dv; } supported_dims[] = { + { 40, 40}, { 64, 64}, { 80, 80}, { 96, 96}, + {112, 112}, {128, 128}, {192, 128}, + {192, 192}, {256, 256}, + {512, 512}, + }; - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->ql_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->qh)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->s)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->d)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - clReleaseMemObject(image_src1_reordered); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); + bool dims_supported = false; + for (size_t i = 0; i < sizeof(supported_dims)/sizeof(supported_dims[0]); ++i) { + if (supported_dims[i].dk == dk && supported_dims[i].dv == dv) { + dims_supported = true; + break; } - return; } -#endif //GGML_OPENCL_USE_ADRENO_KERNELS - } - case GGML_TYPE_MXFP4: { -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - if (use_adreno_moe_kernels(backend_ctx, src0)) { - cl_int status; - - size_t local_size[3] = {64, 2, 1}; - size_t global_size[3] = {64, 2, 1}; - - if (ne12 == 1) { // for gemv - kernel = backend_ctx->kernel_gemv_moe_mxfp4_f32_ns; - - // Weight-as-texture MoE decode GEMV (see q4_K _wimg) - static const char * moe_decode_wimg_env = getenv("GGML_OPENCL_MOE_DECODE_WIMG"); - const bool use_moe_decode_wimg = (moe_decode_wimg_env && (atoi(moe_decode_wimg_env) != 0)) - && backend_ctx->kernel_gemv_moe_mxfp4_f32_ns_wimg != nullptr - && extra0_mxfp4->q_img != nullptr; - if (use_moe_decode_wimg) { - kernel = backend_ctx->kernel_gemv_moe_mxfp4_f32_ns_wimg; - } - - cl_mem src1_sub_buffer, buf_src1_image, buf_src2; - - // create a sub_buffer for src2 - cl_buffer_region region; - region.origin = offset2; - region.size = ne20 * ne21 * sizeof(int); - buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // set thread grid - global_size[0] = static_cast(((ne01 + 63) / 64) * 64); - global_size[1] = 4; - global_size[2] = static_cast(ne20); - local_size[1] = 4; - - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // create image for src1 - cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; - buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), use_moe_decode_wimg ? &extra0_mxfp4->q_img : &extra0_mxfp4->q)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_mxfp4->e)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); - - // launch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - // deallocate sub buffers and images - CL_CHECK(clReleaseMemObject(src1_sub_buffer)); - CL_CHECK(clReleaseMemObject(buf_src1_image)); - CL_CHECK(clReleaseMemObject(buf_src2)); - - } else { // for gemm - kernel = backend_ctx->kernel_gemm_moe_mxfp4_f32_ns; - if (backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_bin) { - kernel = backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_bin; - } - - // Reorder router if called from test-backend-ops or when new router is generated. - // Otherwise reuse the reordered result from previous mul_mat_id call. - if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { - moe_router_reoerder(backend, src2, ne20); - backend_ctx->toggle_reorder = false; - } - - cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; - cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; - cl_mem buf_src2, buf_src2_emap; - - // dp4a (int8) prefill GEMM variant - static const char * mxfp4_moe_dp4a_env = getenv("GGML_OPENCL_MXFP4_MOE_DP4A"); - bool use_moe_dp4a = mxfp4_moe_dp4a_env - ? (atoi(mxfp4_moe_dp4a_env) != 0) - : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E); - // dot prod has to be available - use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; - // bin kernel takes precedence, dp4a bin kernel has higher priority than normal bin kernel - // ldck dp4a bin kernel (X1) has the same priority as normal bin kernel (X2/A8x), they are not expected to coexist. - const bool use_moe_dp4a_ldck = backend_ctx->has_integer_dot && - (!mxfp4_moe_dp4a_env || atoi(mxfp4_moe_dp4a_env) != 0) && - backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_bin == nullptr && - backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_bin == nullptr && - backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin != nullptr; - if (use_moe_dp4a_ldck) { - use_moe_dp4a = true; - } else if (backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_bin == nullptr) { - use_moe_dp4a = use_moe_dp4a && backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_bin == nullptr; - } - - // Priority on A850: coopmat (fp16) > bin kernel > Adreno clc. The dp4a path is chosen by GGML_OPENCL_MXFP4_MOE_DP4A and has its own priority. - static const char * mxfp4_moe_coopmat_env = getenv("GGML_OPENCL_MXFP4_MOE_COOPMAT"); - const bool use_moe_coopmat = !use_moe_dp4a && - (mxfp4_moe_coopmat_env ? (atoi(mxfp4_moe_coopmat_env) != 0) : true) && - backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_coopmat != nullptr; - if (use_moe_coopmat) { - kernel = backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_coopmat; - } - - cl_buffer_region region; - region.origin = 0; - region.size = sizeof(int) * max_post_router_tile * n_tile_size; - GGML_ASSERT(backend_ctx->prealloc_post_router.buffer); - buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - region.origin = 0; - region.size = sizeof(short) * max_post_router_tile; - buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - // Reorder activations - // create a sub_buffer for src1 - region.origin = offset1; - region.size = ne10 * ne11 * ne12 * sizeof(float); - sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); - CL_CHECK(status); - - unsigned short map_ratio = ne20 / ne11; - GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); - - // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var - { - static const char * mxfp4_moe_malu_env = getenv("GGML_OPENCL_MXFP4_MOE_DP4A"); - if (backend_ctx->has_integer_dot && (!mxfp4_moe_malu_env || atoi(mxfp4_moe_malu_env) != 0) && - backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin != nullptr) { - unsigned short malu_map_ratio = ne20 / ne11; - GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); - ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin, - { extra0_mxfp4->q_img, extra0_mxfp4->e }, false, - sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, - ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - return; - } - } - - if (use_moe_coopmat) { - // f16 reordered activations, read by the coopmat kernel as a buffer - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(cl_half); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - - cl_kernel rk = backend_ctx->kernel_moe_reorder_b_f16; - CL_CHECK(clSetKernelArg(rk, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rk, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rk, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(rk, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rk, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(rk, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(rk, 6, sizeof(unsigned int), &n_tile_size)); - - size_t rk_local_size[3] = {256, 1, 1}; - size_t rk_global_size[3] = {static_cast(((ne00 / 8) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - backend_ctx->enqueue_ndrange_kernel(rk, 3, rk_global_size, rk_local_size, dst); - } else if (!use_moe_dp4a) { - // Create image for reordered src1 - // Use pre-allocated placeholder - region.origin = 0; - region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); - backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); - buf_src1_reordered = clCreateSubBuffer( - backend_ctx->prealloc_act_trans.buffer, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - cl_image_format image_format_buf_src1; - cl_image_desc image_desc_buf_src1; - image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; - image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; - if (backend_ctx->kernel_gemm_moe_mxfp4_f32_ns_bin) { - // bin kernel uses slightly different image format - image_format_buf_src1 = {CL_R, CL_FLOAT}; - image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); - } - image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); - CL_CHECK(status); - - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(backend_ctx->kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); - - size_t reorder_b_local_size[3] = {256, 1, 1}; - size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; - - // Dispatch reorder kernel - backend_ctx->enqueue_ndrange_kernel(backend_ctx->kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); - } - - // MoE kernel prepare - // Create sub buffer for dst - region.origin = offsetd; - region.size = ne0 * ne1 * ne2 * sizeof(float); - sub_buf_dst = clCreateSubBuffer( - extrad->data_device, - 0, - CL_BUFFER_CREATE_TYPE_REGION, - ®ion, - &status); - CL_CHECK(status); - // Create image for dst - cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; - cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; - buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); - CL_CHECK(status); - - if (use_moe_dp4a) { - const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; - const size_t n_blocks = tok_slots * (ne00 / 32); - backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); - if (use_moe_dp4a_ldck) { - backend_ctx->prealloc_moe_qa_trans.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); - backend_ctx->prealloc_moe_da_trans.allocate(backend_ctx->context, n_blocks * sizeof(cl_float)); - // matches max_constant_size of src1_a_cm in the ldck kernel - backend_ctx->prealloc_moe_qda_on_chip.allocate(backend_ctx->context, 2304); - } - - // fused reorder + q8_1 quant straight from the original - // activations (no intermediate f32 reorder buffer). mxfp4 has no - // min term so the GEMM ignores sa, but reorder_quant still writes it. - const cl_uint n_kblocks = (cl_uint)(ne00 / 32); - cl_kernel rq = backend_ctx->kernel_moe_reorder_quant_a_q8_1; - CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); - CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); - CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); - CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); - CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); - CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); - size_t rq_local[2] = { 32, 1 }; - size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; - backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); - - // dp4a GEMM - cl_kernel dk = backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a; - if (backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_bin) { - dk = backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_bin; - } else if (use_moe_dp4a_ldck) { - dk = backend_ctx->kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin; - - // per-tile transpose of qa/da for the ldck kernel - cl_kernel tk = backend_ctx->kernel_transpose_activation_q8; - CL_CHECK(clSetKernelArg(tk, 0, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(tk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa_trans.buffer)); - CL_CHECK(clSetKernelArg(tk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - CL_CHECK(clSetKernelArg(tk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da_trans.buffer)); - CL_CHECK(clSetKernelArg(tk, 4, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(tk, 5, sizeof(cl_uint), &ne00)); - size_t tk_local[3] = { 32, 8, 1 }; - size_t tk_global[3] = { 32, (size_t)(ne00 / 4), (size_t)max_post_router_tile }; - backend_ctx->enqueue_ndrange_kernel(tk, 3, tk_global, tk_local, dst); - } - - int aidx = 0; - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_mxfp4->q_img)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_mxfp4->e)); - if (use_moe_dp4a_ldck) { - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa_trans.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da_trans.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qda_on_chip.buffer)); - } else { - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); - } - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); - - size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; - size_t dp_local[3] = { 64, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); - return; - } + if (!dims_supported) { + return false; + } - // Set kernel args - int arg_idx = 0; - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_mxfp4->q_img)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_mxfp4->e)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), use_moe_coopmat ? &buf_src1_reordered : &image_src1_reordered)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); - CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); - - // set thread grid - global_size[1] = static_cast((ne01 + 63) / 64); - global_size[2] = static_cast(max_post_router_tile); - local_size[1] = 1; - local_size[2] = 1; - - // Dispatch kernel - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); - - clReleaseMemObject(sub_buf_src1_pre); - clReleaseMemObject(buf_src1_reordered); - if (image_src1_reordered) { - clReleaseMemObject(image_src1_reordered); - } - clReleaseMemObject(buf_src2); - clReleaseMemObject(buf_src2_emap); - clReleaseMemObject(sub_buf_dst); - clReleaseMemObject(buf_dst_image); - } - return; - } // fallback to generic MoE mxfp4 kernel -#endif // GGML_OPENCL_USE_ADRENO_KERNELS + const bool is_f32_f32 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F32 && + v->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32; + const bool is_f16_f16 = q->type == GGML_TYPE_F16 && k->type == GGML_TYPE_F16 && + v->type == GGML_TYPE_F16 && op->type == GGML_TYPE_F16; + const bool is_f32_f16 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && + v->type == GGML_TYPE_F16 && op->type == GGML_TYPE_F32; -#ifdef GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_id_mxfp4_f32_flat; + const bool is_f32_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && + v->type == GGML_TYPE_Q8_0 && op->type == GGML_TYPE_F32 && + dk % 32 == 0 && dv % 32 == 0; + const bool is_f32_q4_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q4_0 && + v->type == GGML_TYPE_Q4_0 && op->type == GGML_TYPE_F32 && + dk % 32 == 0 && dv % 32 == 0; - cl_mem q; - if (backend_ctx->gpu_family == INTEL) { - sgs = 16; - nsg = 2; - ndst = 2; + // A7X (Adreno 740, compiler E031.41) SIGSEGVs inside clBuildProgram + // building the flash_attn programs whose KV path is mixed-type or + // dequantized - f32_f16, q8_0, q4_0 (reproduced at DK=40 and DK=64; it + // is DK-independent). It is a driver crash, not codegen-wrong-output, so + // it cannot be caught in-process (fatal=false only handles clean compile + // errors). The uniform f16_f16 / f32_f32 programs compile fine on this + // compiler, so decline only the KV-convert variants; ggml then runs + // those (f16-KV / quant-KV) attention layers on the CPU backend. + // Negative compiler carve-out, same idiom as the Intel DK=512 decline + // below and the X1E driver-quirk guards. + if (backend_ctx && backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X && + (is_f32_f16 || is_f32_q8_0 || is_f32_q4_0)) { + return false; + } - q = extra0_mxfp4->q; - } else if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - nsg = 1; - ndst = 4; + // Asymmetric KV: host-dequants both sides to F32, uses f32 kernel. + auto is_kv_type_ok = [](ggml_type t) { + return t == GGML_TYPE_F16 || t == GGML_TYPE_F32 || + t == GGML_TYPE_Q4_0 || t == GGML_TYPE_Q8_0; + }; + const bool is_f32_asym = q->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && + k->type != v->type && + is_kv_type_ok(k->type) && is_kv_type_ok(v->type); - q = extra0_mxfp4->q_img; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + const bool kv_combo_ok = is_f32_f32 || is_f16_f16 || is_f32_f16 || + is_f32_q8_0 || is_f32_q4_0 || is_f32_asym; + if (!kv_combo_ok) { + return false; } - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_mxfp4->e)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); -#else // GGML_OPENCL_SOA_Q - kernel = backend_ctx->kernel_mul_mv_id_mxfp4_f32; - - if (backend_ctx->gpu_family == INTEL) { - sgs = 16; - nsg = 2; - ndst = 2; - } else if (backend_ctx->gpu_family == ADRENO) { - sgs = 64; - nsg = 2; - ndst = 2; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); + // Some compilers for A7x (Adreno 740, compiler E031.41) crashes when + // building FA kernels with mixed or quant types (f32_f16, f32_q8_0, f32_q4_0) + // Here we skip all A7x for these kernels to avoid crash + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X && + (is_f32_f16 || is_f32_q8_0 || is_f32_q4_0)) { + return false; } - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne20)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne21)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb21)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float)*sgs,nullptr)); -#endif // GGML_OPENCL_SOA_Q - break; + if (dk == 512) { + if (backend_ctx->gpu_family == INTEL) { + return false; + } + if (!is_f32_f16) { + return false; + } + if (q->ne[1] == 1) { + const char * decode_env = getenv("GGML_OPENCL_FA_DK512_DECODE"); + const int64_t gqa = k->ne[2] > 0 ? q->ne[2] / k->ne[2] : 0; + // GQA 2 and 16 decode on the X2E MQ kernels (see mq_decode_x2e in ggml_cl_flash_attn) + const bool gqa_ok = gqa == 4 || gqa == 8 || + (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && (gqa == 2 || gqa == 16)); + if ((decode_env && decode_env[0] == '0') || + backend_ctx->gpu_family != ADRENO || k->ne[2] <= 0 || + !gqa_ok || q->ne[2] % k->ne[2] != 0 || + !ggml_opencl_ensure_fa_f32_f16_vec_512(backend_ctx)) { + return false; + } + } else { + // prefill, BM-tile in its own FA_PREFILL_ONLY program + if (!ggml_opencl_ensure_fa_f32_f16_prefill_512(backend_ctx, /*split=*/false)) { + return false; + } + } + } + return true; } default: - GGML_ASSERT(false && "not implemented");; + return false; } +} - int _ne1 = 1; - int ne123 = dst_rows; - - size_t global_work_size[] = {(size_t)(ne01+ndst*nsg-1)/(ndst*nsg)*sgs, (size_t)(_ne1+nrows-1)/nrows*nsg, (size_t)ne123}; - size_t local_work_size[] = {(size_t)sgs, (size_t)nsg, 1}; +// Forward declaration - implementation appears later in the file. +static const char * ggml_backend_opencl_buffer_type_get_name(ggml_backend_buffer_type_t buffer_type); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +static ggml_guid_t ggml_backend_opencl_guid() { + static ggml_guid guid = { 0xde, 0xe0, 0x70, 0xa2, 0x73, 0x4e, 0x4d, 0xbc, 0xb0, 0xc7, 0x4f, 0xd4, 0x6d, 0x4e, 0x90, 0xfe }; + return &guid; } -static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - const ggml_tensor * ids = dst->op == GGML_OP_MUL_MAT_ID ? dst->src[2] : nullptr; - if (ids) { - ggml_cl_mul_mat_id(backend, src0, src1, dst); - } else { - ggml_cl_mul_mat(backend, src0, src1, dst); - } +static ggml_backend_i ggml_backend_opencl_i = { + /* .get_name = */ ggml_backend_opencl_name, + /* .free = */ ggml_backend_opencl_free, + /* .set_tensor_async = */ NULL, /* ggml_backend_opencl_set_tensor_async */ + /* .get_tensor_async = */ NULL, /* ggml_backend_opencl_get_tensor_async */ + /* .set_tensor_2d_async = */ NULL, + /* .get_tensor_2d_async = */ NULL, + /* .cpy_tensor_async = */ NULL, /* ggml_backend_opencl_cpy_tensor_async */ + /* .synchronize = */ ggml_backend_opencl_synchronize, + /* .graph_plan_create = */ NULL, + /* .graph_plan_free = */ NULL, + /* .graph_plan_update = */ NULL, + /* .graph_plan_compute = */ NULL, + /* .graph_compute = */ ggml_backend_opencl_graph_compute, + /* .event_record = */ NULL, + /* .event_wait = */ NULL, + /* .graph_optimize = */ NULL, +}; - const ggml_tensor * scale = ggml_get_src_scale(dst, 0); - if (!scale) { - return; - } - GGML_ASSERT(ggml_is_contiguous(dst) && dst->type == GGML_TYPE_F32 && scale->type == GGML_TYPE_F32); +ggml_backend_t ggml_backend_opencl_init(void) { + ggml_backend_dev_t dev = ggml_backend_reg_dev_get(ggml_backend_opencl_reg(), 0); + ggml_backend_opencl_context *backend_ctx = ggml_cl_init(dev); + backend_ctx->ref_count++; - cl_ulong channel_stride = 0; - cl_ulong expert_stride = 0; - if (!ggml_is_scalar(scale)) { - if (ids && ggml_is_vector(scale) && scale->ne[0] == src0->ne[2]) { - expert_stride = scale->nb[0]; - } else { - channel_stride = scale->nb[0]; - expert_stride = ids ? scale->nb[1] : 0; - } - } + ggml_backend_t backend = new ggml_backend { + /* .guid = */ ggml_backend_opencl_guid(), + /* .iface = */ ggml_backend_opencl_i, + /* .device = */ dev, + /* .context = */ backend_ctx + }; - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - auto * ed = (ggml_tensor_extra_cl *) dst->extra; - auto * es = (ggml_tensor_extra_cl *) scale->extra; - auto * ei = ids ? (ggml_tensor_extra_cl *) ids->extra : nullptr; - const cl_ulong offsetd = ed->offset + dst->view_offs; - const cl_ulong offsets = es->offset + scale->view_offs; - const cl_mem ids_buf = ids ? ei->data_device : nullptr; - const cl_ulong offseti = ids ? ei->offset + ids->view_offs : 0; - const cl_ulong ids_nb0 = ids ? ids->nb[0] : 0; - const cl_ulong ids_nb1 = ids ? ids->nb[1] : 0; - const cl_long n_expert = src0->ne[2]; - const int ne0 = dst->ne[0]; - const int ne1 = dst->ne[1]; - - cl_kernel kernel = backend_ctx->kernel_mul_mat_scale; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &ed->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &es->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsets)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &channel_stride)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &expert_stride)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &ids_buf)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offseti)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &ids_nb0)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &ids_nb1)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &n_expert)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); - - // few rows (decode): 1 element per work-item to keep enough work-items, else 8 - const size_t nth = 128; - const size_t nrows = (size_t) ne1*dst->ne[2]*dst->ne[3]; - const size_t elems_per_item = nrows < 32 ? 1 : 8; - const size_t nwg = CEIL_DIV((size_t) ne0, nth*elems_per_item); - size_t global_work_size[] = { nwg*nth, (size_t) ne1, (size_t) (dst->ne[2]*dst->ne[3]) }; - size_t local_work_size[] = { nth, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return backend; } -static void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0 && src0->extra); - GGML_ASSERT(dst && dst->extra); - GGML_UNUSED(src1); - - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; - const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset0 = extra0->offset + src0->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - const float scale = ggml_get_op_params_f32(dst, 0); - const float bias = ggml_get_op_params_f32(dst, 1); - const bool is_f16 = src0->type == GGML_TYPE_F16; - - cl_kernel kernel; - - if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) { - size_t n = ggml_nelements(dst); - const size_t alignment = 4 * ggml_element_size(src0); - if (n % 4 == 0 && offset0 % alignment == 0 && offsetd % alignment == 0) { - kernel = is_f16 ? backend_ctx->kernel_scale_f16_4 : backend_ctx->kernel_scale_f32_4; - n /= 4; - } else { - kernel = is_f16 ? backend_ctx->kernel_scale_f16 : backend_ctx->kernel_scale_f32; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); - - size_t global_work_size[] = {n, 1, 1}; - size_t local_work_size[] = {64, 1, 1}; - size_t * local_work_size_ptr = local_work_size; - if (n % local_work_size[0] != 0 && !backend_ctx->non_uniform_workgroups) { - local_work_size_ptr = nullptr; - } - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); - } else { - kernel = is_f16 ? backend_ctx->kernel_scale_f16_nc : backend_ctx->kernel_scale_f32_nc; - const cl_ulong ne00 = src0->ne[0]; - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb3)); - - const size_t nth = 64; - size_t global_work_size[] = {(size_t)src0->ne[1] * nth, (size_t)src0->ne[2], (size_t)src0->ne[3]}; - size_t local_work_size[] = {nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - } +bool ggml_backend_is_opencl(ggml_backend_t backend) { + return backend && backend->iface.get_name == ggml_backend_opencl_name; } -static void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - - // GGML_OP_CPY happens between src0 and src1. - // GGML_OP_DUP and GGML_OP_CONT happen between src0 and dst. - UNUSED(dst); - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(int, ne1, src1, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); - - const enum ggml_type src0t = src0->type; - const enum ggml_type src1t = src1->type; - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - - // A contiguous f32 -> f32 copy is a linear move. The kernel below maps one workgroup to - // each row, so a tensor with few long rows runs on a single compute unit; dispatch those - // over the whole device instead. GGML_OPENCL_CPY_FLAT=0 restores the row-mapped path. - static const bool cpy_flat_on = []{ - const char * e = getenv("GGML_OPENCL_CPY_FLAT"); - return !(e && e[0] == '0'); - }(); - if (cpy_flat_on && backend_ctx->kernel_cpy_f32_f32_flat != nullptr && - src0t == GGML_TYPE_F32 && src1t == GGML_TYPE_F32 && - ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && - ggml_nelements(src0) == ggml_nelements(src1)) { - cl_kernel k = backend_ctx->kernel_cpy_f32_f32_flat; - const cl_ulong nelem = (cl_ulong) ggml_nelements(src0); - const cl_ulong n4 = nelem / 4; - - CL_CHECK(clSetKernelArg(k, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(k, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(k, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(k, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(k, 4, sizeof(cl_ulong), &nelem)); - CL_CHECK(clSetKernelArg(k, 5, sizeof(cl_ulong), &n4)); - - // one work item per float4, plus one for the trailing scalars - const size_t items = (size_t) n4 + ((nelem % 4) ? 1 : 0); - const size_t lsz = MIN((size_t) 64, backend_ctx->max_workgroup_size); - size_t global_work_size[] = { ((items + lsz - 1) / lsz) * lsz, 1, 1 }; - size_t local_work_size[] = { lsz, 1, 1 }; - - backend_ctx->enqueue_ndrange_kernel(k, 1, global_work_size, local_work_size, src1); - return; - } - - cl_kernel kernel; - - switch (src0t) { - case GGML_TYPE_F32: - switch (src1t) { - case GGML_TYPE_I32: - kernel = backend_ctx->kernel_cpy_f32_i32; - break; - case GGML_TYPE_F16: - kernel = backend_ctx->kernel_cpy_f32_f16; - break; - case GGML_TYPE_F32: - kernel = (ne00 < 32 && backend_ctx->kernel_cpy_f32_f32_pack) - ? backend_ctx->kernel_cpy_f32_f32_pack - : backend_ctx->kernel_cpy_f32_f32; - break; - default: - GGML_ASSERT(false && "not implemented"); - } - break; - case GGML_TYPE_F16: - switch (src1t) { - case GGML_TYPE_F16: - kernel = backend_ctx->kernel_cpy_f16_f16; - break; - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_cpy_f16_f32; - break; - default: - GGML_ASSERT(false && "not implemented"); - } - break; - case GGML_TYPE_I32: - switch (src1t) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_cpy_i32_f32; - break; - case GGML_TYPE_I32: - kernel = backend_ctx->kernel_cpy_i32_i32; - break; - default: - GGML_ASSERT(false && "not implemented"); - } - break; - default: - GGML_ASSERT(false && "not implemented"); - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); - - if (kernel == backend_ctx->kernel_cpy_f32_f32_pack) { - const int maxwg = (int)backend_ctx->get_kernel_workgroup_size(kernel); - const int base = MIN(64, maxwg); - const int tpr = MIN(ne00, base); // threads per row - const int rpw = MAX(1, base / tpr); // rows per workgroup - const int lsz = tpr * rpw; // <= base <= maxwg - const int nrows = ne01*ne02*ne03; - const int nwg = (nrows + rpw - 1) / rpw; - - size_t global_work_size[] = {(size_t)nwg*lsz, 1, 1}; - size_t local_work_size[] = {(size_t)lsz, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, src1); - } else { - const int nth = MIN(64, ne00); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; +// +// buffer +// - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, src1); - } +static void ggml_backend_opencl_buffer_free_buffer(ggml_backend_buffer_t buffer) { + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + delete ctx; } -static void ggml_cl_dup(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_cl_cpy(backend, src0, dst, nullptr); - UNUSED(src1); +static void * ggml_backend_opencl_buffer_get_base(ggml_backend_buffer_t buffer) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; + return (void *) (uintptr_t) dev_ctx->backend_ctx->alignment; } -static void ggml_cl_set(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - GGML_ASSERT((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_I32) && - src1->type == src0->type && dst->type == src0->type); - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(int, ne1, src1, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); - GGML_TENSOR_LOCALS(int, ne, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const cl_ulong pnb1 = ((const int32_t *)dst->op_params)[0]; - const cl_ulong pnb2 = ((const int32_t *)dst->op_params)[1]; - const cl_ulong pnb3 = ((const int32_t *)dst->op_params)[2]; - const cl_ulong offs = ((const int32_t *)dst->op_params)[3]; - const bool inplace = (bool)((const int32_t *)dst->op_params)[4]; +static enum ggml_status ggml_backend_opencl_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) { + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; - cl_kernel kernel = nullptr; + if (tensor->view_src != nullptr) { + GGML_ASSERT(tensor->view_src->buffer->buft == buffer->buft); - // for inplace case, dst is a view of src0 and is updated on top of it - // so for non-inplace case, copy src0 to dst first - if (!inplace) { - ggml_cl_cpy(backend, src0, dst, nullptr); - } + ggml_tensor_extra_cl * view_extra = (ggml_tensor_extra_cl *) tensor->view_src->extra; + GGML_ASSERT(view_extra && "view_extra is nullptr?"); - // then copy src1 to dst with specified offset - if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_cpy_f32_f32; - } else if (src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) { - kernel = backend_ctx->kernel_cpy_i32_i32; + // Reuse extra of the parent tensor. The offset of this view tensor + // becomes `extra->offset + view_offs` and needs to be calculated when + // it is used. This changes is needed because of the change to + // ggml_alloc.c in https://github.com/ggml-org/llama.cpp/pull/7640. + // `buffer` passed in here will always be `tensor->buffer`. It is OK + // to allocate extras from the same buffer context for ordinary + // intermediate tensors. But for views into kv cache tensors, doing so + // would mess up the extras used by kv cache. + // Before #7640, `buffer` is for intermediate tensors, which is always + // different from that of kv cache tensors. + // + // NB: now extra->offset no longer accounts for view_offs. + // NB: this should not apply to weight tensors (for end-to-end runs, but + // may apply for test-backend-ops). + // FIXME: if any unexpected results are seen, double check the offset - + // there could be other places that need fix. + tensor->extra = view_extra; } else { - GGML_ASSERT(false && "not implemented"); - } - - offsetd += offs; - cl_ulong nb = ggml_element_size(dst); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb10)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &pnb1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &pnb2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &pnb3)); - - int max_local_size = backend_ctx->get_kernel_workgroup_size(kernel); - - const int nth = MIN(max_local_size, ne00); - - size_t global_work_size[] = {(size_t)ne11*nth, (size_t)ne12, (size_t)ne13}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_diag(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - UNUSED(src1); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - GGML_TENSOR_LOCALS(int, ne, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); - - cl_kernel kernel = backend_ctx->kernel_diag_f32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb3)); - - int nth = 64; - - size_t global_work_size[] = {(size_t)ne1*nth, (size_t)ne2, (size_t)ne3}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} + { + size_t offset = (char *) tensor->data - (char *) ggml_backend_opencl_buffer_get_base(buffer); -static void ggml_cl_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - // Softmax can now fuse KQ mask and KQ scale, which used to be two additional - // ops before softmax. It now also fuses alibi if `max_bias > 0`. For llama, - // alibi is not used; however, for some other models, it is used. - // KQ_mask - if (src1) { - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - } + ggml_tensor_extra_cl * extra = ctx->ggml_opencl_alloc_temp_tensor_extra(); + extra->offset = offset; + extra->data_device = ctx->buffer[0]; + extra->actual_size = ggml_nbytes(tensor); - const ggml_tensor * src2 = dst->src[2]; - if (src2) { - GGML_ASSERT(src2->extra); + tensor->extra = extra; + } } + return GGML_STATUS_SUCCESS; +} - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - ggml_tensor_extra_cl * extra1 = src1 ? (ggml_tensor_extra_cl *)src1->extra : nullptr; - ggml_tensor_extra_cl * extra2 = src2 ? (ggml_tensor_extra_cl *)src2->extra : nullptr; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_ulong offset1 = extra1 ? extra1->offset + src1->view_offs : offset0; - cl_ulong offset2 = extra2 ? extra2->offset + src2->view_offs : offset0; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_long nb01 = src0->nb[1]; - const cl_long nb02 = src0->nb[2]; - const cl_long nb03 = src0->nb[3]; - - const int ne12 = src1 ? src1->ne[2] : 0; - const int ne13 = src1 ? src1->ne[3] : 0; - - const cl_long nb11 = src1 ? src1->nb[1] : 0; - const cl_long nb12 = src1 ? src1->nb[2] : 0; - const cl_long nb13 = src1 ? src1->nb[3] : 0; - - const cl_long nb1 = dst->nb[1]; - const cl_long nb2 = dst->nb[2]; - const cl_long nb3 = dst->nb[3]; - - float scale, max_bias; - memcpy(&scale, dst->op_params + 0, sizeof(float)); - memcpy(&max_bias, dst->op_params + 1, sizeof(float)); - - const int n_head = src0->ne[2]; - const int n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head)); - - const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); - const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); - - const bool use_f16 = (src1 && src1->type == GGML_TYPE_F16); - - // Local size must be wave size. Each workgroup is a wave, working on a row, - // where a row corresponds to leading dimension. - int nth = MIN(32, ne00); - - if (backend_ctx->gpu_family == INTEL) { - // This is the same as the initial value. - nth = MIN(32, ne00); - } - else if (backend_ctx->gpu_family == ADRENO) { - nth = 64; - } else { - GGML_ASSERT(false && "TODO: Unknown GPU"); - } +static void ggml_backend_opencl_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; + ggml_backend_opencl_context * backend_ctx = dev_ctx->backend_ctx; - cl_kernel kernel; + cl_command_queue queue = backend_ctx->queue; - if (ne00%4 == 0) { - if (use_f16) { - kernel = backend_ctx->kernel_soft_max_4_f16; - } else { - kernel = backend_ctx->kernel_soft_max_4; - } - } else { - if (use_f16) { - kernel = backend_ctx->kernel_soft_max_f16; - } else { - kernel = backend_ctx->kernel_soft_max; - } + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + for (cl_mem buf : ctx->buffer) { + CL_CHECK(clEnqueueFillBuffer(queue, buf, &value, sizeof(value), 0, buffer->size, 0, NULL, NULL)); } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), extra1 ? &extra1->data_device : &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), extra2 ? &extra2->data_device : &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &n_head_log2)); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + CL_CHECK(clFinish(queue)); } -// Softmax for the decomposed flash attention: like ggml_cl_soft_max, but dst keeps -// exp(x - max) and the row sums go to `sums`, one float per (row, head). src2 is the -// optional sinks tensor. -static void ggml_cl_fa_decompose_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, cl_mem sums) { - GGML_ASSERT(src0 && src0->extra); - GGML_ASSERT(src1 && src1->extra && src1->type == GGML_TYPE_F16); - GGML_ASSERT(dst && dst->extra); - GGML_ASSERT(sums != nullptr); - GGML_ASSERT(src0->ne[0] % 4 == 0); - - if (src2) { - GGML_ASSERT(src2->extra); - } +static void ggml_backend_opencl_buffer_reset(ggml_backend_buffer_t buffer) { + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ctx->reset(); +} - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; +static ggml_backend_buffer_i ggml_backend_opencl_buffer_interface = { + /* .free_buffer = */ ggml_backend_opencl_buffer_free_buffer, + /* .get_base = */ ggml_backend_opencl_buffer_get_base, + /* .init_tensor = */ ggml_backend_opencl_buffer_init_tensor, + /* .memset_tensor = */ NULL, + /* .set_tensor = */ ggml_backend_opencl_buffer_set_tensor, + /* .get_tensor = */ ggml_backend_opencl_buffer_get_tensor, + /* .set_tensor_2d = */ NULL, + /* .get_tensor_2d = */ NULL, + /* .cpy_tensor = */ NULL, + /* .clear = */ ggml_backend_opencl_buffer_clear, + /* .reset = */ ggml_backend_opencl_buffer_reset, + /* .set_tensor_n = */ NULL, + /* .get_tensor_n = */ NULL, + /* .cpy_tensor_n = */ NULL, +}; - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extra2 = src2 ? (ggml_tensor_extra_cl *)src2->extra : nullptr; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offset2 = extra2 ? extra2->offset + src2->view_offs : offset0; - cl_ulong offsetd = extrad->offset + dst->view_offs; - cl_ulong offsets = 0; - - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; - - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const int ne12 = src1->ne[2]; - const int ne13 = src1->ne[3]; - - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - float scale, max_bias; - memcpy(&scale, dst->op_params + 0, sizeof(float)); - memcpy(&max_bias, dst->op_params + 1, sizeof(float)); - - const int n_head = src0->ne[2]; - const int n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head)); - - const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); - const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); - - // one wave per row, same as ggml_cl_soft_max on Adreno - const int nth = 64; - - cl_kernel kernel = backend_ctx->kernel_fa_decompose_soft_max_4_f16; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), extra2 ? &extra2->data_device : &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &sums)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsets)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne13)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb13)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(float), &max_bias)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float), &m0)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(float), &m1)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &n_head_log2)); - - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} +// +// buffer type +// -static void ggml_cl_rope(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); +static const char * ggml_backend_opencl_buffer_type_get_name(ggml_backend_buffer_type_t buffer_type) { + return "OpenCL"; - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + GGML_UNUSED(buffer_type); +} - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - ggml_tensor * src2 = dst->src[2]; - ggml_tensor_extra_cl * extra2 = src2 ? (ggml_tensor_extra_cl *)src2->extra : nullptr; - - cl_ulong offset2 = extra2 ? extra2->offset + src2->view_offs : offset0; - - const int ne00 = src0 ? src0->ne[0] : 0; - const int ne01 = src0 ? src0->ne[1] : 0; - const int ne02 = src0 ? src0->ne[2] : 0; - const int ne03 = src0 ? src0->ne[3] : 0; - - const cl_ulong nb00 = src0 ? src0->nb[0] : 0; - const cl_ulong nb01 = src0 ? src0->nb[1] : 0; - const cl_ulong nb02 = src0 ? src0->nb[2] : 0; - const cl_ulong nb03 = src0 ? src0->nb[3] : 0; - - const int ne10 = src1 ? src1->ne[0] : 0; - const int ne11 = src1 ? src1->ne[1] : 0; UNUSED(ne11); - const int ne12 = src1 ? src1->ne[2] : 0; UNUSED(ne12); - const int ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13); - - const int ne0 = dst ? dst->ne[0] : 0; - const int ne1 = dst ? dst->ne[1] : 0; - const int ne2 = dst ? dst->ne[2] : 0; - const int ne3 = dst ? dst->ne[3] : 0; - - const cl_ulong nb0 = dst ? dst->nb[0] : 0; - const cl_ulong nb1 = dst ? dst->nb[1] : 0; - const cl_ulong nb2 = dst ? dst->nb[2] : 0; - const cl_ulong nb3 = dst ? dst->nb[3] : 0; - - GGML_ASSERT(ne10 % ne02 == 0); - GGML_ASSERT(ne10 >= ne02); - - int nth = MIN(64, ne00); - - const int n_past = ((int *) dst->op_params)[0]; - const int n_dims = ((int *) dst->op_params)[1]; - const int mode = ((int *) dst->op_params)[2]; - const int n_ctx_orig = ((int32_t *) dst->op_params)[4]; - const int n_offs = ((int32_t *) dst->op_params)[15]; - - float freq_base; - float freq_scale; - float ext_factor; - float attn_factor; - float beta_fast; - float beta_slow; - int32_t sections[4]; - - memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float)); - memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float)); - memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float)); - memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float)); - memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float)); - memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float)); - memcpy(§ions, (int32_t *) dst->op_params + 11, sizeof(int32_t)*4); - - const bool is_neox = mode & 2; - const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; - const bool is_vision = mode == GGML_ROPE_TYPE_VISION; - const int is_imrope = mode == GGML_ROPE_TYPE_IMROPE; - - if (is_mrope) { - GGML_ASSERT(sections[0] > 0 || sections[1] > 0 || sections[2] > 0); - } +static ggml_backend_buffer_t ggml_backend_opencl_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buffer_type, size_t size) { + ggml_backend_opencl_context *backend_ctx = ggml_cl_init(buffer_type->device); - if (is_vision) { - GGML_ASSERT(n_dims == ne00/2); - GGML_ASSERT(n_offs == 0); // offset not supported for vision, as the rotated pairs span the whole row + if (!backend_ctx->program_cache_initialized) { + backend_ctx->program_cache = cl_program_cache_init(backend_ctx->device); + backend_ctx->program_cache_initialized = true; } + load_cl_kernels(backend_ctx); - cl_kernel kernel; + // clCreateBuffer returns -61 for size 0 + size = std::max(size, (size_t)1); - if (is_neox) { - switch (src0->type) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_rope_neox_f32; - break; - case GGML_TYPE_F16: - kernel = backend_ctx->kernel_rope_neox_f16; - break; - default: - GGML_ASSERT(false); - }; - } else if (is_mrope && !is_vision) { - switch (src0->type) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_rope_multi_f32; - break; - case GGML_TYPE_F16: - kernel = backend_ctx->kernel_rope_multi_f16; - break; - default: - GGML_ASSERT(false); - }; - } else if (is_vision) { - switch (src0->type) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_rope_vision_f32; - break; - case GGML_TYPE_F16: - kernel = backend_ctx->kernel_rope_vision_f16; - break; - default: - GGML_ASSERT(false); - } - } else { - switch (src0->type) { - case GGML_TYPE_F32: - kernel = backend_ctx->kernel_rope_norm_f32; - break; - case GGML_TYPE_F16: - kernel = backend_ctx->kernel_rope_norm_f16; - break; - default: - GGML_ASSERT(false); - }; + cl_int err; + cl_mem mem = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size, NULL, &err); + // On Adreno X1-85 the device pool intermittently fails at hundreds of MB + // once the heap fragments (e.g. graph-allocator compute-buffer reserve + // after model load). Four-step retry: + // 1. normal alloc (fast path) + // 2. clFinish + retry (drains in-flight allocs) + // 3. cl_qcom_large_buffer (X2-class driver only, OpenCL 3.0 only) + // 4. ALLOC_HOST_PTR (host-pinned pool) - last-resort fallback. This + // buffer backs compute scratch read/written by every kernel in the + // graph, so kernel accesses fall to host memory and runtime perf + // degrades meaningfully. Better than failing to load, but the user + // should see the warning and consider -ngl reduction. + if (err != CL_SUCCESS) { + clFinish(backend_ctx->queue); + mem = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size, NULL, &err); } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), extra2 ? &extra2->data_device : &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne3)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb0)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &nb3)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &n_past)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &n_dims)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &n_ctx_orig)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(float), &freq_base)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(float), &freq_scale)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(float), &ext_factor)); - CL_CHECK(clSetKernelArg(kernel, 30, sizeof(float), &attn_factor)); - CL_CHECK(clSetKernelArg(kernel, 31, sizeof(float), &beta_fast)); - CL_CHECK(clSetKernelArg(kernel, 32, sizeof(float), &beta_slow)); - // both mrope and vision kernels have sections - if (is_mrope || is_vision) { - CL_CHECK(clSetKernelArg(kernel, 33, sizeof(int32_t)*4, §ions)); +#if GGML_OPENCL_TARGET_VERSION >= 300 + // clCreateBufferWithProperties and cl_mem_properties are OpenCL 3.0. Drivers older than + // that do not export the symbol, so a build targeting them fails to link. The large + // buffer extension is only ever enabled on drivers that are well past 3.0, so this path + // is dead there anyway. + if (err != CL_SUCCESS && backend_ctx->adreno_use_large_buffer) { + cl_mem_properties props[] = { 0x41A6 /* CL_LARGE_BUFFER_QCOM */, 1, 0 }; + mem = clCreateBufferWithProperties(backend_ctx->context, props, CL_MEM_READ_WRITE, size, NULL, &err); } - // only mrope has is_imrope - if (is_mrope && !is_vision) { - CL_CHECK(clSetKernelArg(kernel, 34, sizeof(int), &is_imrope)); +#endif + if (err != CL_SUCCESS) { + mem = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, size, NULL, &err); + if (err == CL_SUCCESS) { + GGML_LOG_WARN("%s: %.2f MiB allocated via CL_MEM_ALLOC_HOST_PTR fallback - " + "device pool exhausted; runtime perf will be degraded. " + "Consider lowering -ngl or context size.\n", + __func__, size / 1024.0 / 1024.0); + } } - // norm and neox have n_offs after beta_slow, mrope has it after is_imrope - if (!is_mrope && !is_vision) { - CL_CHECK(clSetKernelArg(kernel, 33, sizeof(int), &n_offs)); - } else if (is_mrope && !is_vision) { - CL_CHECK(clSetKernelArg(kernel, 35, sizeof(int), &n_offs)); + + if (err != CL_SUCCESS) { + GGML_LOG_ERROR("%s: failed to allocate %.2f MiB (err=%d). " + "Consider reducing -ngl, lowering -c / -ub, or using quantized KV cache.\n", + __func__, size / 1024.0 / 1024.0, err); + return nullptr; } - size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)nth, 1, 1}; + ggml_backend_opencl_buffer_context * ctx = new ggml_backend_opencl_buffer_context(mem); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return ggml_backend_buffer_init(buffer_type, ggml_backend_opencl_buffer_interface, ctx, size); } -static void ggml_cl_solve_tri(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_kernel kernel = backend_ctx->kernel_solve_tri_f32; - GGML_ASSERT(kernel != nullptr); - - const int n = src0->ne[0]; - const int k = src1->ne[0]; - - const cl_ulong nb00 = src0->nb[0]; - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; - - const cl_ulong nb10 = src1->nb[0]; - const cl_ulong nb11 = src1->nb[1]; - const cl_ulong nb12 = src1->nb[2]; - const cl_ulong nb13 = src1->nb[3]; - - const cl_ulong nb0 = dst->nb[0]; - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong),&nb02)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong),&nb03)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong),&nb10)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong),&nb11)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong),&nb12)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong),&nb13)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong),&nb0)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong),&nb1)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong),&nb2)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong),&nb3)); - - size_t global_work_size[3]= { (size_t)k, (size_t)dst->ne[2], (size_t)dst->ne[3]}; - size_t local_work_size[] = {16, 4, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +static size_t ggml_backend_opencl_buffer_type_get_alignment(ggml_backend_buffer_type_t buffer_type) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer_type->device->context; + return dev_ctx->backend_ctx->alignment; } -static void ggml_cl_im2col(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - // src0 - filter, src1 - input - GGML_ASSERT(src1->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F32); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int32_t s0 = ((const int32_t*)(dst->op_params))[0]; - const int32_t s1 = ((const int32_t*)(dst->op_params))[1]; - const int32_t p0 = ((const int32_t*)(dst->op_params))[2]; - const int32_t p1 = ((const int32_t*)(dst->op_params))[3]; - const int32_t d0 = ((const int32_t*)(dst->op_params))[4]; - const int32_t d1 = ((const int32_t*)(dst->op_params))[5]; - - const bool is_2D = ((const int32_t*)(dst->op_params))[6] == 1; - - const cl_long IC = src1->ne[is_2D ? 2 : 1]; - const cl_long IH = is_2D ? src1->ne[1] : 1; - const cl_long IW = src1->ne[0]; +static size_t ggml_backend_opencl_buffer_type_get_max_size(ggml_backend_buffer_type_t buffer_type) { + static size_t max_size = -1; + if (max_size == (size_t)-1) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer_type->device->context; + max_size = dev_ctx->backend_ctx->max_alloc_size; + } + return max_size; +} - const cl_long KH = is_2D ? src0->ne[1] : 1; - const cl_long KW = src0->ne[0]; +static bool ggml_backend_opencl_buffer_type_supports_backend(ggml_backend_buffer_type_t buft, ggml_backend_t backend) { + return ggml_backend_is_opencl(backend); - const cl_long OH = is_2D ? dst->ne[2] : 1; - const cl_long OW = dst->ne[1]; + UNUSED(buft); +} - // nb is byte offset, src is type float32 - const cl_ulong delta_offset = src1->nb[is_2D ? 2 : 1]/4; - const cl_long batch = src1->ne[is_2D ? 3 : 2]; - const cl_ulong batch_offset = src1->nb[is_2D ? 3 : 2]/4; +static size_t ggml_backend_opencl_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) { + size_t size = ggml_nbytes(tensor); +#ifdef GGML_OPENCL_SOA_Q + // set_tensor carves quantized weights into per-component subbuffers (d/q, + // ql/qh/s/d, ...) whose origins are each rounded up to the device base + // alignment. When a component's size is not a multiple of the alignment + // (e.g. q6_K [1536,49155]: size_s = 49155*96 leaves a 96-byte gap at 128-byte + // alignment), the aligned carve extends past ggml_nbytes and the last + // subbuffer would overlap the next tensor in the pool. Reserve the worst-case + // carve slack: at most 5 components (q5_K), i.e. 4 aligned gaps. + if (ggml_is_quantized(tensor->type)) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buft->device->context; + size += 4 * dev_ctx->backend_ctx->alignment; + } +#endif // GGML_OPENCL_SOA_Q + return size; +} - const cl_long pelements = OW*KW*KH; - const cl_long CHW = IC*KH*KW; +static ggml_backend_buffer_type_i ggml_backend_opencl_buffer_type_interface = { + /* .get_name = */ ggml_backend_opencl_buffer_type_get_name, + /* .alloc_buffer = */ ggml_backend_opencl_buffer_type_alloc_buffer, + /* .alloc_buffer_n = */ NULL, + /* .get_alignment = */ ggml_backend_opencl_buffer_type_get_alignment, + /* .get_max_size = */ ggml_backend_opencl_buffer_type_get_max_size, + /* .get_alloc_size = */ ggml_backend_opencl_buffer_type_get_alloc_size, + /* .get_alloc_size_n = */ NULL, + /* .is_host = */ NULL, +}; - cl_kernel kernel; +// +// backend device +// - if(dst->type == GGML_TYPE_F16) { - kernel = backend_ctx->kernel_im2col_f16; - } else { - kernel = backend_ctx->kernel_im2col_f32; - } +static const char * ggml_backend_opencl_device_get_name(ggml_backend_dev_t dev) { + return "GPUOpenCL"; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &batch_offset)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &delta_offset)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_long), &IW)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_long), &IH)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_long), &IC)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_long), &OW)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &OH)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_long), &KW)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_long), &KH)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_long), &pelements)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_long), &CHW)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &s0)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &s1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &p0)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &p1)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &d0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &d1)); - - const int num_blocks = (pelements + 256 - 1) / 256; - size_t global_work_size[] = {(size_t)num_blocks*256, (size_t)OH, (size_t)batch*IC}; - size_t local_work_size[] = {256, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + GGML_UNUSED(dev); } -static void ggml_cl_im2col_3d(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); +static const char * ggml_backend_opencl_device_get_description(ggml_backend_dev_t dev) { + ggml_backend_opencl_device_context *dev_ctx = (ggml_backend_opencl_device_context *) dev->context; + return dev_ctx->device_name.c_str(); +} - GGML_ASSERT(src1->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F32); +static void ggml_backend_opencl_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + static const size_t opencl_extra_margin = 1024ull*1024ull*1024ull; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + // OpenCL does not provide reliable currently-free device memory. + // Use total/global memory as a best-effort upper bound. + // Improved safety: Reduce by a 1GiB extra margin for common --fit + *total = dev_ctx->global_mem_size; + *free = *total > opencl_extra_margin ? *total - opencl_extra_margin : 0; +} - cl_ulong offset1 = extra1->offset + src1->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; +static enum ggml_backend_dev_type ggml_backend_opencl_device_get_type(ggml_backend_dev_t dev) { + return GGML_BACKEND_DEVICE_TYPE_GPU; - const int32_t s0 = ((const int32_t*)(dst->op_params))[0]; - const int32_t s1 = ((const int32_t*)(dst->op_params))[1]; - const int32_t s2 = ((const int32_t*)(dst->op_params))[2]; - const int32_t p0 = ((const int32_t*)(dst->op_params))[3]; - const int32_t p1 = ((const int32_t*)(dst->op_params))[4]; - const int32_t p2 = ((const int32_t*)(dst->op_params))[5]; - const int32_t d0 = ((const int32_t*)(dst->op_params))[6]; - const int32_t d1 = ((const int32_t*)(dst->op_params))[7]; - const int32_t d2 = ((const int32_t*)(dst->op_params))[8]; - const cl_long IC = ((const int32_t*)(dst->op_params))[9]; + GGML_UNUSED(dev); +} - const cl_long N = src1->ne[3] / IC; - const cl_long ID = src1->ne[2]; - const cl_long IH = src1->ne[1]; - const cl_long IW = src1->ne[0]; +static void ggml_backend_opencl_device_get_props(ggml_backend_dev_t dev, struct ggml_backend_dev_props * props) { + props->name = ggml_backend_opencl_device_get_name(dev); + props->description = ggml_backend_opencl_device_get_description(dev); + props->type = ggml_backend_opencl_device_get_type(dev); + ggml_backend_opencl_device_get_memory(dev, &props->memory_free, &props->memory_total); + props->caps = ggml_backend_dev_caps { + /* .async = */ false, + /* .host_buffer = */ false, + /* .buffer_from_host_ptr = */ false, + /* .events = */ false, + /* .mmap_support = */ false, + /* .fast_async_host_input = */ false, + }; +} - const cl_long KD = src0->ne[2]; - const cl_long KH = src0->ne[1]; - const cl_long KW = src0->ne[0]; +static ggml_backend_t ggml_backend_opencl_device_init(ggml_backend_dev_t dev, const char * params) { + ggml_backend_opencl_context * backend_ctx = ggml_cl_init(dev); + // Getting a new reference to the backend, increase ref_count + backend_ctx->ref_count++; - const cl_long OD = dst->ne[3] / N; - const cl_long OH = dst->ne[2]; - const cl_long OW = dst->ne[1]; + ggml_backend_t backend = new ggml_backend { + /* .guid = */ ggml_backend_opencl_guid(), + /* .interface = */ ggml_backend_opencl_i, + /* .device = */ dev, + /* .context = */ backend_ctx, + }; - const size_t es = ggml_element_size(src1); - const cl_long stride_x = src1->nb[0] / es; - const cl_long stride_y = src1->nb[1] / es; - const cl_long stride_z = src1->nb[2] / es; - const cl_long stride_q = src1->nb[3] / es; + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) dev->context; + ggml_opencl_print_backend_info(dev_ctx); + return backend; - const cl_long IC_KD_KH_KW = IC * KD * KH * KW; + GGML_UNUSED(params); +} - cl_kernel kernel; +static ggml_backend_buffer_type_t ggml_backend_opencl_device_get_buffer_type(ggml_backend_dev_t dev) { + auto * dev_ctx = static_cast(dev->context); - if (dst->type == GGML_TYPE_F16) { - kernel = backend_ctx->kernel_im2col_3d_f16; - } else { - kernel = backend_ctx->kernel_im2col_3d_f32; - } + dev_ctx->buffer_type = ggml_backend_buffer_type{ + /* .iface = */ ggml_backend_opencl_buffer_type_interface, + /* .device = */ dev, + /* .context = */ nullptr, + }; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_long), &IC)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_long), &ID)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_long), &IH)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_long), &IW)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_long), &KD)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_long), &KH)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &KW)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_long), &OD)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_long), &OH)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_long), &OW)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_long), &N)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_long), &stride_x)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_long), &stride_y)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_long), &stride_z)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_long), &stride_q)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &s0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &s1)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &s2)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &p0)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &p1)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &p2)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &d0)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &d1)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(int), &d2)); - - const size_t local_col = 64; - const size_t num_blocks = (IC_KD_KH_KW + local_col - 1) / local_col; - size_t global_work_size[] = { num_blocks * local_col, (size_t)OW, (size_t)(N * OD * OH) }; - size_t local_work_size[] = { local_col, 1, 1 }; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return &dev_ctx->buffer_type; } -static void ggml_cl_argmax(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_UNUSED(src1); - - GGML_ASSERT(src0->type == GGML_TYPE_F32); - GGML_ASSERT(dst->type == GGML_TYPE_I32); - GGML_ASSERT(ggml_is_contiguous(src0)); - GGML_ASSERT(ggml_is_contiguous(dst)); - - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset0 = extra0->offset + src0->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - const int ne00 = src0->ne[0]; - const int nrows = ggml_nrows(src0); - constexpr int nth = 64; - - cl_kernel kernel = backend_ctx->kernel_argmax_f32_i32; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &nrows)); - - size_t global_work_size[] = { (size_t) nth, (size_t) CEIL_DIV(nrows, 2), 1 }; - size_t local_work_size[] = { (size_t) nth, 1, 1 }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +static ggml_backend_buffer_t ggml_backend_opencl_device_buffer_from_ptr(ggml_backend_dev_t dev, void * ptr, size_t size, size_t max_tensor_size) { + GGML_UNUSED(dev); + GGML_UNUSED(ptr); + GGML_UNUSED(size); + GGML_UNUSED(max_tensor_size); + return nullptr; } -static void ggml_cl_lightning_indexer(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - cl_kernel kernel = backend_ctx->kernel_lightning_indexer; - const ggml_tensor * src2 = dst->src[2]; - const ggml_tensor * src3 = dst->src[3]; - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; - ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; - ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *) src2->extra; - ggml_tensor_extra_cl * extra3 = (ggml_tensor_extra_cl *) src3->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset0 = extra0->offset + src0->view_offs; - const cl_ulong offset1 = extra1->offset + src1->view_offs; - const cl_ulong offset2 = extra2->offset + src2->view_offs; - const cl_ulong offset3 = extra3->offset + src3->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - - const int head_size = src0->ne[0]; - const int n_heads = src0->ne[1]; - const int n_tokens = src0->ne[2]; - const int n_keys = src1->ne[2]; - const int n_masks = src3->ne[3]; - // Keep the local-memory reduction for small grids or few heads. - const int use_shuffle = head_size == 128 && backend_ctx->has_khr_subgroup_shuffle && n_heads >= 32 && ggml_nelements(dst) >= 1024; - // BF16 tensors are stored as F16 on the device. - const int type_k = src1->type == GGML_TYPE_F32 ? 0 : 1; - - const cl_ulong nbq1 = src0->nb[1]; - const cl_ulong nbq2 = src0->nb[2]; - const cl_ulong nbq3 = src0->nb[3]; - const cl_ulong nbk2 = src1->nb[2]; - const cl_ulong nbk3 = src1->nb[3]; - const cl_ulong nbw1 = src2->nb[1]; - const cl_ulong nbw3 = src2->nb[3]; - const cl_ulong nbm1 = src3->nb[1]; - const cl_ulong nbm3 = src3->nb[3]; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra3->data_device)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset3)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &head_size)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &n_heads)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &n_tokens)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &n_keys)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &n_masks)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &type_k)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nbq1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nbq2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nbq3)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nbk2)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nbk3)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nbw1)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nbw3)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &nbm1)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &nbm3)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &use_shuffle)); - - const int keys_per_group = use_shuffle ? 16 : 4; - size_t global_work_size[] = {(size_t) ((src1->ne[2] + keys_per_group - 1)/keys_per_group)*64, (size_t) src0->ne[2], (size_t) src0->ne[3]}; - size_t local_work_size[] = {64, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +static bool ggml_backend_opencl_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) { + ggml_cl_init(dev); + return ggml_opencl_supports_op(dev, op); } -static void ggml_cl_top_k(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_UNUSED(src1); - - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong offset0 = extra0->offset + src0->view_offs; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - - const int k = dst->ne[0]; - cl_kernel kernel = backend_ctx->kernel_top_k_f32; - const int max_wg = backend_ctx->get_kernel_workgroup_size(kernel); - - int nth = 1; - const int target = MIN(512, MAX(32, ne00/4)); - while (2*nth <= MIN(target, max_wg)) { - nth *= 2; +static bool ggml_backend_opencl_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) { + // Check 'dev' and 'buffer_type' are not objects belonging to this backend. + if (dev->iface.get_name != ggml_backend_opencl_device_get_name || + buft->iface.get_name != ggml_backend_opencl_buffer_type_get_name) { + return false; } - const size_t n_rows = ggml_nrows(src0); - const bool tiled = ne00 > 32768 && k > 0 && k <= 256 && n_rows <= 4; - const int tile_width = tiled ? 4096 : ne00; - const int n_tiles = tiled ? 1 + (ne00 - 1)/tile_width : 1; - const int n_candidates = (n_tiles - 1)*k + MIN(k, ne00 - (n_tiles - 1)*tile_width); - cl_mem candidates = nullptr; - if (tiled) { - GGML_ASSERT(n_rows <= SIZE_MAX/sizeof(cl_uint2)/(size_t) n_candidates); - backend_ctx->prealloc_top_k.allocate(backend_ctx->context, n_rows*(size_t) n_candidates*sizeof(cl_uint2)); - candidates = backend_ctx->prealloc_top_k.buffer; - } + // Check cl_context is the same. clEnqueue* commands may not use + // buffers from another cl_context. + ggml_backend_opencl_context * backend_ctx0 = ggml_cl_init(dev); + ggml_backend_opencl_context * backend_ctx1 = ggml_cl_init(buft->device); + return backend_ctx0->context == backend_ctx1->context; +} - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 12, MAX(259, 2*nth)*sizeof(cl_uint), nullptr)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_mem), &candidates)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &tile_width)); - - size_t global_work_size[] = {(size_t) nth*n_tiles, n_rows, 1}; - size_t local_work_size[] = {(size_t) nth, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); - - if (tiled) { - // The global top-k is contained in the top-k of each tile. - kernel = backend_ctx->kernel_top_k_merge_f32; - const int max_wg_merge = backend_ctx->get_kernel_workgroup_size(kernel); - - int nth_merge = 1; - const int target_merge = MIN(512, MAX(32, n_candidates/4)); - while (2*nth_merge <= MIN(target_merge, max_wg_merge)) { - nth_merge *= 2; - } +struct ggml_backend_device_i ggml_backend_opencl_device_i = { + /* .get_name = */ ggml_backend_opencl_device_get_name, + /* .get_description = */ ggml_backend_opencl_device_get_description, + /* .get_memory = */ ggml_backend_opencl_device_get_memory, + /* .get_type = */ ggml_backend_opencl_device_get_type, + /* .get_props = */ ggml_backend_opencl_device_get_props, + /* .init_backend = */ ggml_backend_opencl_device_init, + /* .get_buffer_type = */ ggml_backend_opencl_device_get_buffer_type, + /* .get_host_buffer_type = */ NULL, + /* .buffer_from_host_ptr = */ ggml_backend_opencl_device_buffer_from_ptr, + /* .supports_op = */ ggml_backend_opencl_device_supports_op, + /* .supports_buft = */ ggml_backend_opencl_device_supports_buft, + /* .offload_op = */ NULL, + /* .event_new = */ NULL, + /* .event_free = */ NULL, + /* .event_synchronize = */ NULL, +}; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &candidates)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &n_candidates)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &k)); - CL_CHECK(clSetKernelArg(kernel, 5, MAX(259, 2*nth_merge)*sizeof(cl_uint), nullptr)); +// Backend registry - global_work_size[0] = nth_merge; - local_work_size[0] = nth_merge; +static const char * ggml_backend_opencl_reg_get_name(ggml_backend_reg_t reg) { + return "OpenCL"; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); - } + GGML_UNUSED(reg); } -static void ggml_cl_top_k_mask(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const ggml_tensor * score = dst->src[2]; - const ggml_tensor * blocks = dst->src[3]; - const ggml_tensor * extra = dst->src[4]; - const int type = dst->type == GGML_TYPE_F16 ? 0 : 1; - cl_kernel kernel = backend_ctx->kernel_top_k_mask[type]; - - const ggml_tensor_extra_cl * extram = (const ggml_tensor_extra_cl *) src0->extra; - const ggml_tensor_extra_cl * extrak = (const ggml_tensor_extra_cl *) src1->extra; - const ggml_tensor_extra_cl * extras = score ? (const ggml_tensor_extra_cl *) score->extra : nullptr; - const ggml_tensor_extra_cl * extrab = blocks ? (const ggml_tensor_extra_cl *) blocks->extra : nullptr; - const ggml_tensor_extra_cl * extrae = extra ? (const ggml_tensor_extra_cl *) extra->extra : nullptr; - const ggml_tensor_extra_cl * extrad = (const ggml_tensor_extra_cl *) dst->extra; - - const cl_mem buffer_s = extras ? extras->data_device : nullptr; - const cl_mem buffer_b = extrab ? extrab->data_device : nullptr; - const cl_mem buffer_e = extrae ? extrae->data_device : nullptr; - - const cl_ulong offsetm = extram->offset + src0->view_offs; - const cl_ulong offsetk = extrak->offset + src1->view_offs; - const cl_ulong offsets = extras ? extras->offset + score->view_offs : 0; - const cl_ulong offsetb = extrab ? extrab->offset + blocks->view_offs : 0; - const cl_ulong offsete = extrae ? extrae->offset + extra->view_offs : 0; - const cl_ulong offsetd = extrad->offset + dst->view_offs; - - // single launch: fill == true, two launches: fill = false - // X2 benefits from a parallel fill for long single rows; mobile Adreno favors one launch. - const cl_int fill = !(backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && - ggml_nrows(dst) == 1 && dst->ne[0] >= 65536 && ggml_is_contiguous(dst)); - - if (!fill) { - GGML_ASSERT(ggml_is_contiguous(dst)); - - cl_kernel kernel_fill = backend_ctx->kernel_top_k_mask_fill[type]; - - const cl_ulong n = ggml_nelements(dst); - const size_t nv = 16/ggml_type_size(dst->type); - const size_t nth = MIN((size_t) 256, backend_ctx->get_kernel_workgroup_size(kernel_fill)); - - CL_CHECK(clSetKernelArg(kernel_fill, 0, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel_fill, 1, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel_fill, 2, sizeof(cl_ulong), &n)); - - size_t global[] = {((n + nv - 1)/nv + nth - 1)/nth*nth}; - size_t local[] = {nth}; - backend_ctx->enqueue_ndrange_kernel(kernel_fill, 1, global, local, dst); - } +static size_t ggml_backend_opencl_reg_device_count(ggml_backend_reg_t reg) { + return g_ggml_backend_opencl_devices.size(); - GGML_TENSOR_LOCALS(cl_ulong, nem, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nbm, src0, nb); - GGML_TENSOR_LOCALS(cl_ulong, nek, src1, ne); - GGML_TENSOR_LOCALS(cl_ulong, nbk, src1, nb); - GGML_TENSOR_LOCALS(cl_ulong, nes, score, ne); - GGML_TENSOR_LOCALS(cl_ulong, nbs, score, nb); - GGML_TENSOR_LOCALS(cl_ulong, neb, blocks, ne); - GGML_TENSOR_LOCALS(cl_ulong, nbb, blocks, nb); - GGML_TENSOR_LOCALS(cl_ulong, nee, extra, ne); - GGML_TENSOR_LOCALS(cl_ulong, nbe, extra, nb); - GGML_TENSOR_LOCALS(cl_ulong, ned, dst, ne); - GGML_TENSOR_LOCALS(cl_ulong, nbd, dst, nb); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extram->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetm)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrak->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetk)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buffer_s)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsets)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &buffer_b)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetb)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &buffer_e)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsete)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nem0)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nem1)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nem2)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nem3)); - CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nbm1)); - CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nbm2)); - CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nbm3)); - CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nek0)); - CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nbk0)); - CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nbk1)); - CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nbk2)); - CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &nbk3)); - CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &nes0)); - CL_CHECK(clSetKernelArg(kernel, 25, sizeof(cl_ulong), &nbs0)); - CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nbs1)); - CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nbs2)); - CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nbs3)); - CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &neb0)); - CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_ulong), &neb1)); - CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_ulong), &nbb0)); - CL_CHECK(clSetKernelArg(kernel, 32, sizeof(cl_ulong), &nbb1)); - CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_ulong), &nee0)); - CL_CHECK(clSetKernelArg(kernel, 34, sizeof(cl_ulong), &nbe0)); - CL_CHECK(clSetKernelArg(kernel, 35, sizeof(cl_ulong), &nbe1)); - CL_CHECK(clSetKernelArg(kernel, 36, sizeof(cl_ulong), &nbe2)); - CL_CHECK(clSetKernelArg(kernel, 37, sizeof(cl_ulong), &nbe3)); - CL_CHECK(clSetKernelArg(kernel, 38, sizeof(cl_ulong), &ned1)); - CL_CHECK(clSetKernelArg(kernel, 39, sizeof(cl_ulong), &ned2)); - CL_CHECK(clSetKernelArg(kernel, 40, sizeof(cl_ulong), &nbd1)); - CL_CHECK(clSetKernelArg(kernel, 41, sizeof(cl_ulong), &nbd2)); - CL_CHECK(clSetKernelArg(kernel, 42, sizeof(cl_ulong), &nbd3)); - CL_CHECK(clSetKernelArg(kernel, 43, sizeof(cl_int), &fill)); - - const size_t nth = MIN((size_t) 512, backend_ctx->get_kernel_workgroup_size(kernel)); - size_t global[] = {nth, (size_t) ggml_nrows(dst)}; - size_t local[] = {nth, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst); + GGML_UNUSED(reg); } -static void ggml_cl_argsort(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_UNUSED(src1); - - GGML_ASSERT(src0->type == GGML_TYPE_F32); - GGML_ASSERT( dst->type == GGML_TYPE_I32); - GGML_ASSERT(ggml_is_contiguous(src0)); +static ggml_backend_dev_t ggml_backend_opencl_reg_device_get(ggml_backend_reg_t reg, size_t index) { + GGML_ASSERT(index < ggml_backend_opencl_reg_device_count(reg)); - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + return &g_ggml_backend_opencl_devices[index]; - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + GGML_UNUSED(reg); + GGML_UNUSED(index); +} - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; +static struct ggml_backend_reg_i ggml_backend_opencl_reg_i = { + /* .get_name = */ ggml_backend_opencl_reg_get_name, + /* .device_count = */ ggml_backend_opencl_reg_device_count, + /* .device_get = */ ggml_backend_opencl_reg_device_get, + /* .get_proc_address = */ NULL, +}; - const int ne00 = src0->ne[0]; - const int nrows = ggml_nrows(src0); +ggml_backend_reg_t ggml_backend_opencl_reg(void) { + static std::mutex mutex; + static ggml_backend_reg reg; + static bool initialized = false; + std::lock_guard lock(mutex); - int ne00_padded = 1; - while (ne00_padded < ne00) { - ne00_padded *= 2; + if (initialized) { + return ® } + initialized = true; - int order = (enum ggml_sort_order) dst->op_params[0]; - - cl_kernel kernel = backend_ctx->kernel_argsort_f32_i32; - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00_padded)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &order)); - CL_CHECK(clSetKernelArg(kernel, 7, ne00_padded*sizeof(int), NULL)); - - size_t global_work_size[] = {(size_t)ne00_padded, (size_t)nrows, (size_t)1}; - size_t local_work_size[] = {(size_t)ne00_padded, 1, 1}; + g_ggml_backend_opencl_devices = ggml_opencl_probe_devices(®); - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + reg = ggml_backend_reg{ + /* .api_version = */ GGML_BACKEND_API_VERSION, + /* .iface = */ ggml_backend_opencl_reg_i, + /* .context = */ NULL, + }; -#ifdef GGML_OPENCL_USE_ADRENO_KERNELS - const int ne21 = dst->ne[1]; - if ((strstr(src0->name, "_moe") != NULL) && (ne21 != 1)) { - backend_ctx->toggle_reorder = true; - } -#endif // GGML_OPENCL_USE_ADRENO_KERNELS + return ® } -static void ggml_cl_dsv4_hc(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; - const bool pre = dst->op == GGML_OP_DSV4_HC_PRE; - const bool vec = !pre && src0->ne[0] % 4 == 0 && src0->nb[0] == sizeof(float) && src1->nb[0] == sizeof(float); - cl_kernel kernel = pre ? backend_ctx->kernel_dsv4_hc_pre : backend_ctx->kernel_dsv4_hc_post[vec]; - - cl_uint arg = 0; - for (int i = 0; i < (pre ? 2 : 4); ++i) { - const ggml_tensor * src = dst->src[i]; - auto * extra = src ? (ggml_tensor_extra_cl *) src->extra : nullptr; - const cl_mem buffer = extra ? extra->data_device : nullptr; - const cl_ulong offset = src ? extra->offset + src->view_offs : 0; - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &buffer)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &offset)); - for (int j = 0; j < 3; ++j) { - const cl_ulong stride = src ? src->nb[j] : 0; - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &stride)); - } - } +GGML_BACKEND_DL_IMPL(ggml_backend_opencl_reg) - auto * extra = (ggml_tensor_extra_cl *) dst->extra; - const cl_ulong offset = extra->offset + dst->view_offs; - const cl_long n_embd = src0->ne[0]; - const cl_long n_hc = pre ? src0->ne[1] : src1->ne[1]; - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &extra->data_device)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &offset)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_long), &n_embd)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_long), &n_hc)); - if (pre) { - const float scale = ggml_get_op_params_f32(dst, 0); - const cl_int gated = ggml_get_op_params_i32(dst, 1); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &scale)); - CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_int), &gated)); - } +//------------------------------------------------------------------------------ +// Debugging utils +//------------------------------------------------------------------------------ +#if 0 +#define QK4_0 32 +typedef struct { + ggml_fp16_t d; // delta + uint8_t qs[QK4_0 / 2]; // nibbles / quants +} block_q4_0; +static_assert(sizeof(block_q4_0) == sizeof(ggml_fp16_t) + QK4_0 / 2, + "wrong q4_0 block size/padding"); - const size_t n_work = (size_t) n_embd / (vec ? 4 : 1); - size_t local_work_size[] = { pre ? backend_ctx->local_dsv4_hc_pre : backend_ctx->local_dsv4_hc_post[vec], 1, 1 }; - size_t global_work_size[] = { CEIL_DIV(n_work, local_work_size[0]) * local_work_size[0], (size_t) dst->ne[1], (size_t) dst->ne[2] }; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} +#define QK_MXFP4 32 -static void ggml_cl_sum_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_UNUSED(src1); +#include +#ifdef __cplusplus +#include "half.hpp" +#endif - GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type)); +static void dump_tensor(ggml_backend_t backend, const struct ggml_tensor * tensor) { + void * buf = malloc(ggml_nbytes(tensor)); ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + cl_command_queue queue = backend_ctx->queue; +#ifdef GGML_OPENCL_SOA_Q + void * buf_q; + void * buf_d; +#endif - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; + // Make sure everything is done. + CL_CHECK(clFinish(queue)); - const int ne00 = src0->ne[0]; - const int ne01 = src0->ne[1]; - const int ne02 = src0->ne[2]; - const int ne03 = src0->ne[3]; +#ifdef GGML_OPENCL_SOA_Q + if (tensor->type == GGML_TYPE_Q4_0) { + ggml_tensor_extra_cl_q4_0 * extra = (ggml_tensor_extra_cl_q4_0 *) tensor->extra; + GGML_ASSERT(extra); - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb02 = src0->nb[2]; - const cl_ulong nb03 = src0->nb[3]; + size_t size_q = ggml_nelements(tensor)/QK4_0 * QK4_0/2; + size_t size_d = ggml_nelements(tensor)/QK4_0 * sizeof(ggml_fp16_t); + GGML_ASSERT(size_q + size_d == ggml_nbytes(tensor)); + buf_q = malloc(size_q); + buf_d = malloc(size_d); - const cl_ulong nb1 = dst->nb[1]; - const cl_ulong nb2 = dst->nb[2]; - const cl_ulong nb3 = dst->nb[3]; + CL_CHECK(clEnqueueReadBuffer(queue, extra->q, CL_TRUE, 0, size_q, buf_q, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->d, CL_TRUE, 0, size_d, buf_d, 0, NULL, NULL)); + CL_CHECK(clFinish(queue)); + } else if (tensor->type == GGML_TYPE_MXFP4) { + ggml_tensor_extra_cl_mxfp4 * extra = (ggml_tensor_extra_cl_mxfp4 *) tensor->extra; + GGML_ASSERT(extra); - cl_kernel kernel; + size_t size_q = ggml_nelements(tensor)/QK_MXFP4 * QK_MXFP4/2; + size_t size_e = ggml_nelements(tensor)/QK_MXFP4 * sizeof(char); + GGML_ASSERT(size_q + size_e == ggml_nbytes(tensor)); + buf_q = malloc(size_q); + buf_d = malloc(size_e); - const bool is_c4 = ne00 % 4 == 0; - if (is_c4) { - kernel = backend_ctx->kernel_sum_rows_f32_4; + CL_CHECK(clEnqueueReadBuffer(queue, extra->q, CL_TRUE, 0, size_q, buf_q, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->e, CL_TRUE, 0, size_e, buf_d, 0, NULL, NULL)); + CL_CHECK(clFinish(queue)); } else { - kernel = backend_ctx->kernel_sum_rows_f32; - } - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb2)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb3)); - - size_t global_work_size[] = {64 * (size_t)ne01, (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = {(size_t)64, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); -} - -static void ggml_cl_cumsum(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - GGML_UNUSED(src1); - - GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type)); - GGML_ASSERT(ggml_is_contiguous(src0)); - - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - GGML_TENSOR_LOCALS(int, ne0, src0, ne); - GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); - - cl_kernel kernel = backend_ctx->kernel_cumsum_blk; - - int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); - int nth = 1; - while (nth < ne00 && 2*nth <= max_workgroup_size) { - nth *= 2; - } + // Read out the tensor from GPU memory. + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; + GGML_ASSERT(extra); - GGML_ASSERT(ne00 <= nth*nth); - - const int net0 = CEIL_DIV(ne00, nth); - const int net1 = ne01; - const int net2 = ne02; - const int net3 = ne03; - - const cl_ulong nbt0 = sizeof(float); - const cl_ulong nbt1 = net0*nbt0; - const cl_ulong nbt2 = net1*nbt1; - const cl_ulong nbt3 = net2*nbt2; - - static ggml_cl_buffer tmp_buffer; - tmp_buffer.allocate(backend_ctx->context, net0*ne01*ne02*ne03*sizeof(float)); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &tmp_buffer.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb00)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &net0)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &net1)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &net2)); - - size_t global_work_size[] = { (size_t)(nth*net0*ne01), (size_t)ne02, (size_t)ne03}; - size_t local_work_size[] = { (size_t)nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); - - if(ne00 > nth) { - // if a single workgroup cannot handle an entire row, each workgroup - // computes a partial sum and stores to dst, tmp_buffer contains the sum - // of the each workgroup; cumsum this buffer and add to the partial sums in dst - cl_ulong offsett = 0; - kernel = backend_ctx->kernel_cumsum_blk; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &tmp_buffer.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsett)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &tmp_buffer.buffer)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &tmp_buffer.buffer)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsett)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &net0)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nbt0)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nbt1)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nbt2)); - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nbt3)); - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &net0)); - CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &net1)); - CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &net2)); - - size_t global_work_size_1[] = { (size_t)net1*nth, (size_t)net2, (size_t)net3}; - size_t local_work_size_1[] = { (size_t)nth, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size_1, local_work_size_1, dst); - - kernel = backend_ctx->kernel_cumsum_add; - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &tmp_buffer.buffer)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne00)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne01)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne02)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne03)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &nbt0)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &nbt1)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &nbt2)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &nbt3)); - - size_t global_work_size_2[] = { (size_t)(nth*net0*ne01), (size_t)ne02, (size_t)ne03}; - size_t local_work_size_2[] = { (size_t)nth, 1, 1}; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size_2, local_work_size_2, dst); + CL_CHECK(clEnqueueReadBuffer(queue, extra->data_device, CL_TRUE, + extra->offset, ggml_nbytes(tensor), buf, 0, NULL, NULL)); + CL_CHECK(clFinish(queue)); } -} - -static void ggml_cl_glu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { - GGML_ASSERT(src0); - GGML_ASSERT(src0->extra); - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); +#else + // Read out the tensor from GPU memory. + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; + GGML_ASSERT(extra); - GGML_ASSERT(ggml_is_contiguous_1(src0)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->data_device, CL_TRUE, + extra->offset, ggml_nbytes(tensor), buf, 0, NULL, NULL)); + CL_CHECK(clFinish(queue)); +#endif // GGML_OPENCL_SOA_Q - if (src1) { - GGML_ASSERT(src1); - GGML_ASSERT(src1->extra); - GGML_ASSERT(ggml_are_same_shape(src0, src1)); + // Open file and dump. + char fname[512]; + snprintf(fname, sizeof(fname), "./tensor-dumps/%s.txt", tensor->name); + FILE * f = fopen(fname, "w"); + if (!f) { + printf("Failed to open %s\n", fname); + return; } - ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; - - cl_kernel kernel; - switch (ggml_get_glu_op(dst)) { - case GGML_GLU_OP_GEGLU: - if (dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_geglu; - } else { - kernel = backend_ctx->kernel_geglu_f16; - } - break; - case GGML_GLU_OP_REGLU: - if (dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_reglu; - } else { - kernel = backend_ctx->kernel_reglu_f16; - } - break; - case GGML_GLU_OP_SWIGLU: - if (dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_swiglu; - } else { - kernel = backend_ctx->kernel_swiglu_f16; + if (tensor->type == GGML_TYPE_F32) { + float * data = (float *) buf; + for (int i = 0; i < ggml_nelements(tensor); ++i) { + if (isnan(data[i])) { + printf("NaN found: %s\n", tensor->name); + break; } - break; - case GGML_GLU_OP_SWIGLU_OAI: - if (dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_swiglu_oai; - } else { - kernel = backend_ctx->kernel_swiglu_oai_f16; + fprintf(f, "%f\n", data[i]); + } + } else if (tensor->type == GGML_TYPE_I32) { + int * data = (int *) buf; + for (int i = 0; i < ggml_nelements(tensor); ++i) { + if (isnan(data[i])) { + printf("NaN found: %s\n", tensor->name); + break; } - break; - case GGML_GLU_OP_SWIGLU_CLAMP: - if (dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_swiglu_clamp; - } else { - kernel = backend_ctx->kernel_swiglu_clamp_f16; + fprintf(f, "%d\n", data[i]); + } + } else if (tensor->type == GGML_TYPE_F16) { +#ifdef __cplusplus + half_float::half * data = (half_float::half *) buf; + for (int i = 0; i < ggml_nelements(tensor); ++i) { + if (std::isnan(data[i])) { + printf("NaN found: %s\n", tensor->name); + break; } - break; - case GGML_GLU_OP_GEGLU_ERF: - if (dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_geglu_erf; - } else { - kernel = backend_ctx->kernel_geglu_erf_f16; + fprintf(f, "%f\n", float(data[i])); + } +#endif + } else if (tensor->type == GGML_TYPE_Q4_0) { +#ifdef GGML_OPENCL_SOA_Q + ggml_fp16_t * data_d = (ggml_fp16_t *)buf_d; + unsigned char * data_q = (unsigned char *)buf_q; + + for (int i = 0; i < ggml_nelements(tensor)/QK4_0; ++i) { + fprintf(f, "%04x, ", data_d[i]); + for (int k = 0; k < QK4_0/2; ++k) { + fprintf(f, "%02x, ", data_q[k]); } - break; - case GGML_GLU_OP_GEGLU_QUICK: - if (dst->type == GGML_TYPE_F32) { - kernel = backend_ctx->kernel_geglu_quick; - } else { - kernel = backend_ctx->kernel_geglu_quick_f16; + fprintf(f, "\n"); + data_q += QK4_0/2; + } + free(buf_d); + free(buf_q); +#else + block_q4_0 * data = (block_q4_0 *) buf; + for (int i = 0; i < ggml_nelements(tensor)/QK4_0; ++i) { + fprintf(f, "%04x, ", data[i].d); + for (int k = 0; k < QK4_0/2; ++k) { + fprintf(f, "%02x, ", data[i].qs[k]); } - break; - default: - GGML_ABORT("Unsupported glu op"); - } - - ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; - ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; - - ggml_tensor_extra_cl * extra1 = src1 ? (ggml_tensor_extra_cl *)src1->extra : nullptr; - - cl_ulong offset0 = extra0->offset + src0->view_offs; - cl_ulong offsetd = extrad->offset + dst->view_offs; - - cl_ulong offset1 = extra1 ? extra1->offset + src1->view_offs : offset0; - - const int ne0 = dst->ne[0]; - - const cl_ulong nb01 = src0->nb[1]; - const cl_ulong nb11 = src1 ? src1->nb[1] : nb01; - - const cl_ulong nb1 = dst->nb[1]; - - const int swp = ggml_get_op_params_i32(dst, 1); - const float alpha = ggml_get_op_params_f32(dst, 2); - const float limit = ggml_get_op_params_f32(dst, 3); - - const int ne00_off = src1 ? 0 : (swp ? ne0 : 0); - const int ne10_off = src1 ? 0 : (swp ? 0 : ne0); - - CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); - CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), src1 ? &extra1->data_device : &extra0->data_device)); - CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); - CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); - CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); - CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); - CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb11)); - CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne0)); - CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb1)); - CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00_off)); - CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10_off)); - - if (ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU_OAI || ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU_CLAMP) { - CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float), &limit)); - } - if (ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU_OAI) { - CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha)); + fprintf(f, "\n"); + } +#endif // GGML_OPENCL_SOA_Q } - - const size_t nrows = ggml_nrows(src0); - size_t nth = backend_ctx->max_workgroup_size < 512 ? backend_ctx->max_workgroup_size : 512; - size_t global_work_size[] = {nrows*nth, 1, 1}; - size_t local_work_size[] = {nth, 1, 1}; - - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + free(buf); + fflush(f); + fclose(f); } +#else +#define dump_tensor(tensor) +#endif -static void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { - GGML_ASSERT(dst); - GGML_ASSERT(dst->extra); - - const ggml_tensor * src_q = dst->src[0]; - const ggml_tensor * src_k = dst->src[1]; - const ggml_tensor * src_v = dst->src[2]; - const ggml_tensor * src_g = dst->src[3]; - const ggml_tensor * src_beta = dst->src[4]; - const ggml_tensor * src_state = dst->src[5]; - - GGML_ASSERT(src_q && src_q->extra); - GGML_ASSERT(src_k && src_k->extra); - GGML_ASSERT(src_v && src_v->extra); - GGML_ASSERT(src_g && src_g->extra); - GGML_ASSERT(src_beta && src_beta->extra); - GGML_ASSERT(src_state && src_state->extra); - - ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; - - const cl_uint S_v = (cl_uint) src_v->ne[0]; - const cl_uint H_v = (cl_uint) src_v->ne[1]; - const cl_uint n_tokens = (cl_uint) src_v->ne[2]; - const cl_uint n_seqs = (cl_uint) src_v->ne[3]; - const cl_uint K = (cl_uint) ggml_get_op_params_i32(dst, 0); - const bool replay = dst->src[6] != nullptr; - const cl_uint n_pend = replay ? (cl_uint) ggml_get_op_params_i32(dst, 1) : 0; - const cl_uint keep = replay ? (cl_uint) ggml_get_op_params_i32(dst, 2) : 0; - - int si; - switch (S_v) { - case 16: si = 0; break; - case 32: si = 1; break; - case 64: si = 2; break; - case 128: si = 3; break; - default: - GGML_ASSERT(false && "ggml_cl_gated_delta_net: unsupported S_v"); - } - - const int kda = (src_g->ne[0] == (int64_t) S_v) ? 1 : 0; - - // TODO: Optimize when S_v!=128. Not necessary for now as Qwen3.5/6 are all S_v=128 - // token generation mode (tgpp=0): - // process 1 token at a time, so columns per lane (cpl) == 1 - // prompt processing mode (tgpp=1): - // cpl=4 to process 4 tokens for single-token. 4 is chosen for Adreno 750 as per - // work-item/thread has at most 128 registers. - // All Qwen3.5/6 models are S_v == 128, so LANES_PER_COLUMN == 8 - // such that ROWS_PER_LANE = 128/8 = 16 - // Variables in the kernel: - // k_reg, q_reg, g_exp are all 16 floats - // s_shard has cpl*ROWS_PER_LANE = 4*16 = 64 floats - // Total 112 registers used. - // subgroups_per_workgroup (spw) can be set to 1,2,4,8,16 for tg and 1,2,4 for pp - // for S_v=128. - // Empirically found that when spw=1, we get the best performance for both tg and pp - const int tgpp = (n_tokens == 1) ? 0 : 1; - const int cpl = (tgpp == 0) ? 1 : 4; - // spw needs adjustment when S_v != 128 - const int spw = (tgpp == 0) ? 1 : 1; - - cl_kernel kernel = backend_ctx->kernel_gated_delta_net_f32[si][kda][tgpp][replay]; - GGML_ASSERT(kernel != nullptr); - - const cl_uint s_off = S_v * H_v * n_tokens * n_seqs; - - const cl_uint sq1 = (cl_uint)(src_q->nb[1] / sizeof(float)); - const cl_uint sq2 = (cl_uint)(src_q->nb[2] / sizeof(float)); - const cl_uint sq3 = (cl_uint)(src_q->nb[3] / sizeof(float)); - const cl_uint sk1 = (cl_uint)(src_k->nb[1] / sizeof(float)); - const cl_uint sk2 = (cl_uint)(src_k->nb[2] / sizeof(float)); - const cl_uint sk3 = (cl_uint)(src_k->nb[3] / sizeof(float)); - const cl_uint sv1 = (cl_uint)(src_v->nb[1] / sizeof(float)); - const cl_uint sv2 = (cl_uint)(src_v->nb[2] / sizeof(float)); - const cl_uint sv3 = (cl_uint)(src_v->nb[3] / sizeof(float)); - const cl_uint sb1 = (cl_uint)(src_beta->nb[1] / sizeof(float)); - const cl_uint sb2 = (cl_uint)(src_beta->nb[2] / sizeof(float)); - const cl_uint sb3 = (cl_uint)(src_beta->nb[3] / sizeof(float)); - - const cl_uint H_k = (cl_uint) src_q->ne[1]; - const cl_uint rq3 = (cl_uint)(src_v->ne[3] / src_q->ne[3]); - - const float scale = 1.0f / sqrtf((float) S_v); - - ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *) src_q->extra; - ggml_tensor_extra_cl * extra_k = (ggml_tensor_extra_cl *) src_k->extra; - ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *) src_v->extra; - ggml_tensor_extra_cl * extra_g = (ggml_tensor_extra_cl *) src_g->extra; - ggml_tensor_extra_cl * extra_beta = (ggml_tensor_extra_cl *) src_beta->extra; - ggml_tensor_extra_cl * extra_state = (ggml_tensor_extra_cl *) src_state->extra; - ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *) dst->extra; - - const cl_ulong off_q = extra_q->offset + src_q->view_offs; - const cl_ulong off_k = extra_k->offset + src_k->view_offs; - const cl_ulong off_v = extra_v->offset + src_v->view_offs; - const cl_ulong off_g = extra_g->offset + src_g->view_offs; - const cl_ulong off_beta = extra_beta->offset + src_beta->view_offs; - const cl_ulong off_state = extra_state->offset + src_state->view_offs; - const cl_ulong off_dst = extra_dst->offset + dst->view_offs; - - int idx = 0; - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_q->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_q)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_k->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_k)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_v->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_v)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_g->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_g)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_beta->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_beta)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_state->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_state)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_dst->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_dst)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_v)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_tokens)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_seqs)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &s_off)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sb1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sb2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sb3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_k)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &rq3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(float), &scale)); - - if (replay) { - const ggml_tensor * src_pk = dst->src[6]; - const ggml_tensor * src_pv = dst->src[7]; - const ggml_tensor * src_pgb = dst->src[8]; - const ggml_tensor * src_rep = dst->src[9]; - - GGML_ASSERT(src_pk && src_pk->extra); - GGML_ASSERT(src_pv && src_pv->extra); - GGML_ASSERT(src_pgb && src_pgb->extra); - GGML_ASSERT(src_rep && src_rep->extra); - - const ggml_tensor_extra_cl * extra_pk = (const ggml_tensor_extra_cl *) src_pk->extra; - const ggml_tensor_extra_cl * extra_pv = (const ggml_tensor_extra_cl *) src_pv->extra; - const ggml_tensor_extra_cl * extra_pgb = (const ggml_tensor_extra_cl *) src_pgb->extra; - const ggml_tensor_extra_cl * extra_rep = (const ggml_tensor_extra_cl *) src_rep->extra; - - const cl_ulong off_pk = extra_pk->offset + src_pk->view_offs; - const cl_ulong off_pv = extra_pv->offset + src_pv->view_offs; - const cl_ulong off_pgb = extra_pgb->offset + src_pgb->view_offs; - const cl_ulong off_rep = extra_rep->offset + src_rep->view_offs; - - const cl_ulong spk1 = src_pk->nb[1] / sizeof(float); - const cl_ulong spk2 = src_pk->nb[2] / sizeof(float); - const cl_ulong spk3 = src_pk->nb[3] / sizeof(float); - const cl_ulong spv1 = src_pv->nb[1] / sizeof(float); - const cl_ulong spv2 = src_pv->nb[2] / sizeof(float); - const cl_ulong spv3 = src_pv->nb[3] / sizeof(float); - const cl_ulong spg1 = src_pgb->nb[1] / sizeof(float); - const cl_ulong spg2 = src_pgb->nb[2] / sizeof(float); - const cl_ulong spg3 = src_pgb->nb[3] / sizeof(float); - - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_pend)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &keep)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pk->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pk)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pv->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pv)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pgb->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pgb)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg1)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg2)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg3)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_rep->data_device)); - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_rep)); - } - CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K)); - - // Subgroup size is 64 for Adreno and 32 for Intel - const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1; - if (sg_size < 0) { - GGML_LOG_ERROR("Unsupported GPU Family: only Adreno and Intel are supported.\n"); - exit(1); - } - - // For the subgroup-shuffle kernel, we can safely prefer 8 lanes/column for S_v>=128 - // For the subgroup-shuffle kernel: - // S_v >= 128 -> prefer 8 lanes/column (good occupancy & register pressure tradeoff) - // else -> min(S_v, subgroup_size) - int lanes_per_column; - if ((int)S_v >= 128) { - lanes_per_column = 8; - } else { - lanes_per_column = std::min((int)S_v, sg_size); - } - - // Max workgroup size for Adreno 750 is 1024 - const int wg_size = sg_size * spw; - - // Ensure lanes_per_column is a power-of-two and divides both S_v and subgroup_size. - // (Required for lane-group shuffle-xor reduction correctness.) - while (lanes_per_column > 1 && - (((lanes_per_column & (lanes_per_column - 1)) != 0) || - (((int)S_v % lanes_per_column) != 0) || - (sg_size % lanes_per_column) != 0)) { - lanes_per_column >>= 1; - } - GGML_ASSERT(lanes_per_column >= 1); - GGML_ASSERT(((lanes_per_column & (lanes_per_column - 1)) == 0)); - GGML_ASSERT(((int)S_v % lanes_per_column) == 0); - GGML_ASSERT((sg_size % lanes_per_column) == 0); - - const int cols_per_wg = spw * (sg_size / lanes_per_column) * cpl; - GGML_ASSERT(cols_per_wg > 0); - GGML_ASSERT(((int)S_v % cols_per_wg) == 0); - - size_t global_work_size[3]; - size_t local_work_size[3]; +//------------------------------------------------------------------------------ +// Ops +//------------------------------------------------------------------------------ - global_work_size[0] = (size_t) H_v * (size_t) wg_size; - global_work_size[1] = (size_t) n_seqs; - global_work_size[2] = (size_t) S_v / (size_t) cols_per_wg; +static bool ggml_cl_can_mul_mat(const struct ggml_tensor * src0, const struct ggml_tensor * src1, struct ggml_tensor * dst) { + const int64_t ne10 = src1->ne[0]; - local_work_size[0] = (size_t) wg_size; - local_work_size[1] = 1; - local_work_size[2] = 1; + const int64_t ne0 = dst->ne[0]; + const int64_t ne1 = dst->ne[1]; - backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + // TODO: find the optimal values for these + return (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type)) && + src1->type == GGML_TYPE_F32 && + dst->type == GGML_TYPE_F32 && + (ne0 >= 32 && ne1 >= 32 && ne10 >= 32); } //------------------------------------------------------------------------------ diff --git a/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_attn_adreno.cl b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_attn_adreno.cl new file mode 100644 index 000000000000..7e2b27041c3b --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/mul_mm_f16_f32_attn_adreno.cl @@ -0,0 +1,434 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +#ifdef cl_intel_subgroups +#pragma OPENCL EXTENSION cl_intel_subgroups : enable +#else +#pragma OPENCL EXTENSION cl_khr_subgroups : enable +#endif + +#ifdef cl_intel_required_subgroup_size +#pragma OPENCL EXTENSION cl_intel_required_subgroup_size : enable +#define INTEL_GPU 1 +#define REQD_SUBGROUP_SIZE_16 __attribute__((intel_reqd_sub_group_size(16))) +#define REQD_SUBGROUP_SIZE_32 __attribute__((intel_reqd_sub_group_size(32))) +#elif defined(cl_qcom_reqd_sub_group_size) +#pragma OPENCL EXTENSION cl_qcom_reqd_sub_group_size : enable +#define ADRENO_GPU 1 +#define REQD_SUBGROUP_SIZE_64 __attribute__((qcom_reqd_sub_group_size("half"))) +#define REQD_SUBGROUP_SIZE_128 __attribute__((qcom_reqd_sub_group_size("full"))) +#endif + +#ifdef cl_khr_subgroup_shuffle +#pragma OPENCL EXTENSION cl_khr_subgroup_shuffle : enable +#define HAS_SUBGROUP_SHUFFLE 1 +#elif defined(cl_qcom_subgroup_shuffle) +#pragma OPENCL EXTENSION cl_qcom_subgroup_shuffle : enable +#define HAS_SUBGROUP_SHUFFLE 1 +// Adreno compilers that expose only cl_qcom_subgroup_shuffle do not declare the KHR +// name, so calling it is an implicit declaration and the program fails to build. +// Route it to the qcom builtin. +#define sub_group_shuffle_xor(val, mask) qcom_sub_group_shuffle_xor((val), (mask), CLK_SUB_GROUP_SHUFFLE_WIDTH_WAVE_SIZE_QCOM, 0.0f) +#endif + +#define N_K_ROWS_GQA 16 +#define GQA_RATIO_GQA 8 +#define LANES_PER_QH 8 +#define DK_VEC_GQA 32 + +#define N_DV_ROWS_Y8GQA 8 +#define GQA_RATIO_Y8GQA 8 +#ifdef ADRENO_GPU +REQD_SUBGROUP_SIZE_64 +#endif +kernel void kernel_mul_mat_f16_f32_l4_x8_gqa4_img( + __read_only image1d_buffer_t src0_img, + global char * src1, + ulong offset1, + global float * dst, + ulong offsetd, + int ne00, + int ne01, + int ne02, + ulong nb01, + ulong nb02, + ulong nb03, + int ne10, + int ne11, + int ne12, + ulong nb10, + ulong nb11, + ulong nb12, + ulong nb13, + int ne0, + int ne1, + int r2, + int r3 +) { + src1 = (global char *)((global char *)src1 + offset1); + dst = (global float*)((global char *)dst + offsetd); + + const int sgs_lid = get_sub_group_local_id(); + const int q_id = sgs_lid >> 3; // 0..7: which Q-head (8 per WG) + const int lane_q = sgs_lid & 7; // 0..7: lane within Q-head partition + + const int r0_base = get_group_id(0) * N_K_ROWS_GQA; + const int im_kv = get_group_id(2); + + const int i02 = im_kv % ne02; + const int i03 = im_kv / ne02; + + const int q_head_lo = i02 * GQA_RATIO_GQA; + + __local float4 q_loc[GQA_RATIO_GQA * DK_VEC_GQA]; + #pragma unroll + for (int qh = 0; qh < GQA_RATIO_GQA; ++qh) { + const int qh_idx = q_head_lo + qh; + global float4 * y4 = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); + if (sgs_lid < DK_VEC_GQA) { + q_loc[qh * DK_VEC_GQA + sgs_lid] = y4[sgs_lid]; + } + } + barrier(CLK_LOCAL_MEM_FENCE); + + const int pitch_px_row = (int)(nb01 >> 4); + const int pitch_px_head = (int)(nb02 >> 4); + const int pitch_px_n13 = (int)(nb03 >> 4); + + const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; + + #pragma unroll + for (int dr = 0; dr < N_K_ROWS_GQA; ++dr) { + const int r0 = r0_base + dr; + const int row_px_base = r0 * pitch_px_row + head_px_base; + + float sumf = 0.0f; + #pragma unroll + for (int t = 0; t < 2; ++t) { + const int p = lane_q + t * LANES_PER_QH; // pixel idx in row, 0..15 + const half8 k8 = as_half8(read_imagef(src0_img, row_px_base + p)); + const int i0 = 2 * p; // first half4 idx + const float4 qa = q_loc[q_id * DK_VEC_GQA + i0 ]; + const float4 qb = q_loc[q_id * DK_VEC_GQA + i0 + 1]; + sumf += convert_float(k8.s0) * qa.s0 + + convert_float(k8.s1) * qa.s1 + + convert_float(k8.s2) * qa.s2 + + convert_float(k8.s3) * qa.s3 + + convert_float(k8.s4) * qb.s0 + + convert_float(k8.s5) * qb.s1 + + convert_float(k8.s6) * qb.s2 + + convert_float(k8.s7) * qb.s3; + } + + sumf += sub_group_shuffle_xor(sumf, 4); + sumf += sub_group_shuffle_xor(sumf, 2); + sumf += sub_group_shuffle_xor(sumf, 1); + + if (lane_q == 0) { + const int im_out = i03 * ne12 + (q_head_lo + q_id); + dst[im_out * ne1 * ne0 + r0] = sumf; + } + } +} + +#ifdef ADRENO_GPU +REQD_SUBGROUP_SIZE_64 +#endif +kernel void kernel_mul_mat_f16_f32_l4_y8_gqa_img( + __read_only image1d_buffer_t src0_img, + global char * src1, + ulong offset1, + global float * dst, + ulong offsetd, + int ne00, + int ne01, + int ne02, + ulong nb01, + ulong nb02, + ulong nb03, + int ne10, + int ne11, + int ne12, + ulong nb10, + ulong nb11, + ulong nb12, + ulong nb13, + int ne0, + int ne1, + int r2, + int r3 +) { + src1 = (global char *)((global char *)src1 + offset1); + dst = (global float*)((global char *)dst + offsetd); + + const int sgs_lid = get_sub_group_local_id(); + const int sgs_sz = get_max_sub_group_size(); + + const int r0_base = get_group_id(0) * N_DV_ROWS_Y8GQA; + const int im_kv = get_group_id(2); + + const int i02 = im_kv % ne02; + const int i03 = im_kv / ne02; + + const int q_head_lo = i02 * GQA_RATIO_Y8GQA; + + // Q (= softmax(KQ)) base pointers per Q-head + global float4 * y4_q[GQA_RATIO_Y8GQA]; + #pragma unroll + for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { + const int qh_idx = q_head_lo + qh; + y4_q[qh] = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); + } + + const int pitch_px_row = (int)(nb01 >> 3); + const int pitch_px_head = (int)(nb02 >> 3); + const int pitch_px_n13 = (int)(nb03 >> 3); + + const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; + + // per-DV-row pixel base + int row_px_base[N_DV_ROWS_Y8GQA]; + #pragma unroll + for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { + const int r0 = r0_base + o; + const int r0c = (r0 < ne01) ? r0 : 0; + row_px_base[o] = r0c * pitch_px_row + head_px_base; + } + + float sum[N_DV_ROWS_Y8GQA][GQA_RATIO_Y8GQA] = { {0.0f} }; + + for (int i = sgs_lid; i < ne00 / 4; i += sgs_sz) { + half4 v[N_DV_ROWS_Y8GQA]; + + #pragma unroll + for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { + v[o] = read_imageh(src0_img, row_px_base[o] + i); + } + + float4 q[GQA_RATIO_Y8GQA]; + #pragma unroll + for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { + q[qh] = y4_q[qh][i]; + } + // 64 mads. + #pragma unroll + for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { + const float4 vf = (float4)(convert_float(v[o].s0), + convert_float(v[o].s1), + convert_float(v[o].s2), + convert_float(v[o].s3)); + #pragma unroll + for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { + sum[o][qh] += vf.s0 * q[qh].s0 + + vf.s1 * q[qh].s1 + + vf.s2 * q[qh].s2 + + vf.s3 * q[qh].s3; + } + } + } + + #pragma unroll + for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { + const int r0 = r0_base + o; + #pragma unroll + for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { + const float s = sub_group_reduce_add(sum[o][qh]); + if (sgs_lid == 0 && r0 < ne01) { + const int im_out = i03 * ne12 + (q_head_lo + qh); + dst[im_out * ne1 * ne0 + r0] = s; + } + } + } +} + +#define N_K_ROWS_GQA_R4 16 +#define GQA_RATIO_R4 4 +#define LANES_PER_QH_R4 16 // = 64 / GQA_RATIO_R4 +#define DK_VEC_R4 32 // DK / 4 for DK=128 + +#ifdef ADRENO_GPU +REQD_SUBGROUP_SIZE_64 +#endif +kernel void kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img( + __read_only image1d_buffer_t src0_img, + global char * src1, + ulong offset1, + global float * dst, + ulong offsetd, + int ne00, + int ne01, + int ne02, + ulong nb01, + ulong nb02, + ulong nb03, + int ne10, + int ne11, + int ne12, + ulong nb10, + ulong nb11, + ulong nb12, + ulong nb13, + int ne0, + int ne1, + int r2, + int r3 +) { + src1 = (global char *)((global char *)src1 + offset1); + dst = (global float*)((global char *)dst + offsetd); + + const int sgs_lid = get_sub_group_local_id(); + const int q_id = sgs_lid >> 4; // 0..3 + const int lane_q = sgs_lid & 15; // 0..15 + + const int r0_base = get_group_id(0) * N_K_ROWS_GQA_R4; + const int im_kv = get_group_id(2); + + const int i02 = im_kv % ne02; + const int i03 = im_kv / ne02; + + const int q_head_lo = i02 * GQA_RATIO_R4; + + __local float4 q_loc[GQA_RATIO_R4 * DK_VEC_R4]; + #pragma unroll + for (int qh = 0; qh < GQA_RATIO_R4; ++qh) { + const int qh_idx = q_head_lo + qh; + global float4 * y4 = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); + if (sgs_lid < DK_VEC_R4) { + q_loc[qh * DK_VEC_R4 + sgs_lid] = y4[sgs_lid]; + } + } + barrier(CLK_LOCAL_MEM_FENCE); + + const int pitch_px_row = (int)(nb01 >> 4); + const int pitch_px_head = (int)(nb02 >> 4); + const int pitch_px_n13 = (int)(nb03 >> 4); + + const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; + + #pragma unroll + for (int dr = 0; dr < N_K_ROWS_GQA_R4; ++dr) { + const int r0 = r0_base + dr; + const int row_px_base = r0 * pitch_px_row + head_px_base; + + const int p = lane_q; + const half8 k8 = as_half8(read_imagef(src0_img, row_px_base + p)); + const int i0 = 2 * p; + const float4 qa = q_loc[q_id * DK_VEC_R4 + i0 ]; + const float4 qb = q_loc[q_id * DK_VEC_R4 + i0 + 1]; + + float sumf = + convert_float(k8.s0) * qa.s0 + + convert_float(k8.s1) * qa.s1 + + convert_float(k8.s2) * qa.s2 + + convert_float(k8.s3) * qa.s3 + + convert_float(k8.s4) * qb.s0 + + convert_float(k8.s5) * qb.s1 + + convert_float(k8.s6) * qb.s2 + + convert_float(k8.s7) * qb.s3; + + sumf += sub_group_shuffle_xor(sumf, 8); + sumf += sub_group_shuffle_xor(sumf, 4); + sumf += sub_group_shuffle_xor(sumf, 2); + sumf += sub_group_shuffle_xor(sumf, 1); + + if (lane_q == 0) { + const int im_out = i03 * ne12 + (q_head_lo + q_id); + dst[im_out * ne1 * ne0 + r0] = sumf; + } + } +} + +#define N_K_ROWS_GQA_R2_DK256 16 +#define GQA_RATIO_R2 2 +#define LANES_PER_QH_R2 32 // = 64 / GQA_RATIO_R2 +#define DK_VEC_DK256 64 // DK / 4 for DK=256 + +#ifdef ADRENO_GPU +REQD_SUBGROUP_SIZE_64 +#endif +kernel void kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img( + __read_only image1d_buffer_t src0_img, + global char * src1, + ulong offset1, + global float * dst, + ulong offsetd, + int ne00, + int ne01, + int ne02, + ulong nb01, + ulong nb02, + ulong nb03, + int ne10, + int ne11, + int ne12, + ulong nb10, + ulong nb11, + ulong nb12, + ulong nb13, + int ne0, + int ne1, + int r2, + int r3 +) { + src1 = (global char *)((global char *)src1 + offset1); + dst = (global float*)((global char *)dst + offsetd); + + const int sgs_lid = get_sub_group_local_id(); + const int q_id = sgs_lid >> 5; // 0..1 + const int lane_q = sgs_lid & 31; // 0..31 + + const int r0_base = get_group_id(0) * N_K_ROWS_GQA_R2_DK256; + const int im_kv = get_group_id(2); + + const int i02 = im_kv % ne02; + const int i03 = im_kv / ne02; + + const int q_head_lo = i02 * GQA_RATIO_R2; + + __local float4 q_loc[GQA_RATIO_R2 * DK_VEC_DK256]; + #pragma unroll + for (int qh = 0; qh < GQA_RATIO_R2; ++qh) { + const int qh_idx = q_head_lo + qh; + global float4 * y4 = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); + q_loc[qh * DK_VEC_DK256 + sgs_lid] = y4[sgs_lid]; + } + barrier(CLK_LOCAL_MEM_FENCE); + + const int pitch_px_row = (int)(nb01 >> 4); + const int pitch_px_head = (int)(nb02 >> 4); + const int pitch_px_n13 = (int)(nb03 >> 4); + + const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; + + #pragma unroll + for (int dr = 0; dr < N_K_ROWS_GQA_R2_DK256; ++dr) { + const int r0 = r0_base + dr; + const int row_px_base = r0 * pitch_px_row + head_px_base; + + const int p = lane_q; + const half8 k8 = as_half8(read_imagef(src0_img, row_px_base + p)); + const int i0 = 2 * p; + const float4 qa = q_loc[q_id * DK_VEC_DK256 + i0 ]; + const float4 qb = q_loc[q_id * DK_VEC_DK256 + i0 + 1]; + + float sumf = + convert_float(k8.s0) * qa.s0 + + convert_float(k8.s1) * qa.s1 + + convert_float(k8.s2) * qa.s2 + + convert_float(k8.s3) * qa.s3 + + convert_float(k8.s4) * qb.s0 + + convert_float(k8.s5) * qb.s1 + + convert_float(k8.s6) * qb.s2 + + convert_float(k8.s7) * qb.s3; + + sumf += sub_group_shuffle_xor(sumf, 16); + sumf += sub_group_shuffle_xor(sumf, 8); + sumf += sub_group_shuffle_xor(sumf, 4); + sumf += sub_group_shuffle_xor(sumf, 2); + sumf += sub_group_shuffle_xor(sumf, 1); + + if (lane_q == 0) { + const int im_out = i03 * ne12 + (q_head_lo + q_id); + dst[im_out * ne1 * ne0 + r0] = sumf; + } + } +} diff --git a/ggml/src/ggml-opencl/kernels/mul_mv_f16_f32_l4.cl b/ggml/src/ggml-opencl/kernels/mul_mv_f16_f32_l4.cl index 97148d370fbd..5cde55c163d9 100644 --- a/ggml/src/ggml-opencl/kernels/mul_mv_f16_f32_l4.cl +++ b/ggml/src/ggml-opencl/kernels/mul_mv_f16_f32_l4.cl @@ -839,399 +839,3 @@ kernel void kernel_mul_mat_f16_f32_l4_y8_gqa( } } } - -#ifdef ADRENO_GPU -REQD_SUBGROUP_SIZE_64 -#endif -kernel void kernel_mul_mat_f16_f32_l4_x8_gqa4_img( - __read_only image1d_buffer_t src0_img, - global char * src1, - ulong offset1, - global float * dst, - ulong offsetd, - int ne00, - int ne01, - int ne02, - ulong nb01, - ulong nb02, - ulong nb03, - int ne10, - int ne11, - int ne12, - ulong nb10, - ulong nb11, - ulong nb12, - ulong nb13, - int ne0, - int ne1, - int r2, - int r3 -) { - src1 = (global char *)((global char *)src1 + offset1); - dst = (global float*)((global char *)dst + offsetd); - - const int sgs_lid = get_sub_group_local_id(); - const int q_id = sgs_lid >> 3; // 0..7: which Q-head (8 per WG) - const int lane_q = sgs_lid & 7; // 0..7: lane within Q-head partition - - const int r0_base = get_group_id(0) * N_K_ROWS_GQA; - const int im_kv = get_group_id(2); - - const int i02 = im_kv % ne02; - const int i03 = im_kv / ne02; - - const int q_head_lo = i02 * GQA_RATIO_GQA; - - __local float4 q_loc[GQA_RATIO_GQA * DK_VEC_GQA]; - #pragma unroll - for (int qh = 0; qh < GQA_RATIO_GQA; ++qh) { - const int qh_idx = q_head_lo + qh; - global float4 * y4 = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); - if (sgs_lid < DK_VEC_GQA) { - q_loc[qh * DK_VEC_GQA + sgs_lid] = y4[sgs_lid]; - } - } - barrier(CLK_LOCAL_MEM_FENCE); - - const int pitch_px_row = (int)(nb01 >> 4); - const int pitch_px_head = (int)(nb02 >> 4); - const int pitch_px_n13 = (int)(nb03 >> 4); - - const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; - - #pragma unroll - for (int dr = 0; dr < N_K_ROWS_GQA; ++dr) { - const int r0 = r0_base + dr; - const int row_px_base = r0 * pitch_px_row + head_px_base; - - float sumf = 0.0f; - #pragma unroll - for (int t = 0; t < 2; ++t) { - const int p = lane_q + t * LANES_PER_QH; // pixel idx in row, 0..15 - const half8 k8 = as_half8(read_imagef(src0_img, row_px_base + p)); - const int i0 = 2 * p; // first half4 idx - const float4 qa = q_loc[q_id * DK_VEC_GQA + i0 ]; - const float4 qb = q_loc[q_id * DK_VEC_GQA + i0 + 1]; - sumf += convert_float(k8.s0) * qa.s0 - + convert_float(k8.s1) * qa.s1 - + convert_float(k8.s2) * qa.s2 - + convert_float(k8.s3) * qa.s3 - + convert_float(k8.s4) * qb.s0 - + convert_float(k8.s5) * qb.s1 - + convert_float(k8.s6) * qb.s2 - + convert_float(k8.s7) * qb.s3; - } - - sumf += sub_group_shuffle_xor(sumf, 4); - sumf += sub_group_shuffle_xor(sumf, 2); - sumf += sub_group_shuffle_xor(sumf, 1); - - if (lane_q == 0) { - const int im_out = i03 * ne12 + (q_head_lo + q_id); - dst[im_out * ne1 * ne0 + r0] = sumf; - } - } -} - -#ifdef ADRENO_GPU -REQD_SUBGROUP_SIZE_64 -#endif -kernel void kernel_mul_mat_f16_f32_l4_y8_gqa_img( - __read_only image1d_buffer_t src0_img, - global char * src1, - ulong offset1, - global float * dst, - ulong offsetd, - int ne00, - int ne01, - int ne02, - ulong nb01, - ulong nb02, - ulong nb03, - int ne10, - int ne11, - int ne12, - ulong nb10, - ulong nb11, - ulong nb12, - ulong nb13, - int ne0, - int ne1, - int r2, - int r3 -) { - src1 = (global char *)((global char *)src1 + offset1); - dst = (global float*)((global char *)dst + offsetd); - - const int sgs_lid = get_sub_group_local_id(); - const int sgs_sz = get_max_sub_group_size(); - - const int r0_base = get_group_id(0) * N_DV_ROWS_Y8GQA; - const int im_kv = get_group_id(2); - - const int i02 = im_kv % ne02; - const int i03 = im_kv / ne02; - - const int q_head_lo = i02 * GQA_RATIO_Y8GQA; - - // Q (= softmax(KQ)) base pointers per Q-head - global float4 * y4_q[GQA_RATIO_Y8GQA]; - #pragma unroll - for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { - const int qh_idx = q_head_lo + qh; - y4_q[qh] = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); - } - - const int pitch_px_row = (int)(nb01 >> 3); - const int pitch_px_head = (int)(nb02 >> 3); - const int pitch_px_n13 = (int)(nb03 >> 3); - - const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; - - // per-DV-row pixel base - int row_px_base[N_DV_ROWS_Y8GQA]; - #pragma unroll - for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { - const int r0 = r0_base + o; - const int r0c = (r0 < ne01) ? r0 : 0; - row_px_base[o] = r0c * pitch_px_row + head_px_base; - } - - float sum[N_DV_ROWS_Y8GQA][GQA_RATIO_Y8GQA] = { {0.0f} }; - - for (int i = sgs_lid; i < ne00 / 4; i += sgs_sz) { - half4 v[N_DV_ROWS_Y8GQA]; - - #pragma unroll - for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { - v[o] = read_imageh(src0_img, row_px_base[o] + i); - } - - float4 q[GQA_RATIO_Y8GQA]; - #pragma unroll - for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { - q[qh] = y4_q[qh][i]; - } - // 64 mads. - #pragma unroll - for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { - const float4 vf = (float4)(convert_float(v[o].s0), - convert_float(v[o].s1), - convert_float(v[o].s2), - convert_float(v[o].s3)); - #pragma unroll - for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { - sum[o][qh] += vf.s0 * q[qh].s0 - + vf.s1 * q[qh].s1 - + vf.s2 * q[qh].s2 - + vf.s3 * q[qh].s3; - } - } - } - - #pragma unroll - for (int o = 0; o < N_DV_ROWS_Y8GQA; ++o) { - const int r0 = r0_base + o; - #pragma unroll - for (int qh = 0; qh < GQA_RATIO_Y8GQA; ++qh) { - const float s = sub_group_reduce_add(sum[o][qh]); - if (sgs_lid == 0 && r0 < ne01) { - const int im_out = i03 * ne12 + (q_head_lo + qh); - dst[im_out * ne1 * ne0 + r0] = s; - } - } - } -} - -#define N_K_ROWS_GQA_R4 16 -#define GQA_RATIO_R4 4 -#define LANES_PER_QH_R4 16 // = 64 / GQA_RATIO_R4 -#define DK_VEC_R4 32 // DK / 4 for DK=128 - -#ifdef ADRENO_GPU -REQD_SUBGROUP_SIZE_64 -#endif -kernel void kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img( - __read_only image1d_buffer_t src0_img, - global char * src1, - ulong offset1, - global float * dst, - ulong offsetd, - int ne00, - int ne01, - int ne02, - ulong nb01, - ulong nb02, - ulong nb03, - int ne10, - int ne11, - int ne12, - ulong nb10, - ulong nb11, - ulong nb12, - ulong nb13, - int ne0, - int ne1, - int r2, - int r3 -) { - src1 = (global char *)((global char *)src1 + offset1); - dst = (global float*)((global char *)dst + offsetd); - - const int sgs_lid = get_sub_group_local_id(); - const int q_id = sgs_lid >> 4; // 0..3 - const int lane_q = sgs_lid & 15; // 0..15 - - const int r0_base = get_group_id(0) * N_K_ROWS_GQA_R4; - const int im_kv = get_group_id(2); - - const int i02 = im_kv % ne02; - const int i03 = im_kv / ne02; - - const int q_head_lo = i02 * GQA_RATIO_R4; - - __local float4 q_loc[GQA_RATIO_R4 * DK_VEC_R4]; - #pragma unroll - for (int qh = 0; qh < GQA_RATIO_R4; ++qh) { - const int qh_idx = q_head_lo + qh; - global float4 * y4 = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); - if (sgs_lid < DK_VEC_R4) { - q_loc[qh * DK_VEC_R4 + sgs_lid] = y4[sgs_lid]; - } - } - barrier(CLK_LOCAL_MEM_FENCE); - - const int pitch_px_row = (int)(nb01 >> 4); - const int pitch_px_head = (int)(nb02 >> 4); - const int pitch_px_n13 = (int)(nb03 >> 4); - - const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; - - #pragma unroll - for (int dr = 0; dr < N_K_ROWS_GQA_R4; ++dr) { - const int r0 = r0_base + dr; - const int row_px_base = r0 * pitch_px_row + head_px_base; - - const int p = lane_q; - const half8 k8 = as_half8(read_imagef(src0_img, row_px_base + p)); - const int i0 = 2 * p; - const float4 qa = q_loc[q_id * DK_VEC_R4 + i0 ]; - const float4 qb = q_loc[q_id * DK_VEC_R4 + i0 + 1]; - - float sumf = - convert_float(k8.s0) * qa.s0 - + convert_float(k8.s1) * qa.s1 - + convert_float(k8.s2) * qa.s2 - + convert_float(k8.s3) * qa.s3 - + convert_float(k8.s4) * qb.s0 - + convert_float(k8.s5) * qb.s1 - + convert_float(k8.s6) * qb.s2 - + convert_float(k8.s7) * qb.s3; - - sumf += sub_group_shuffle_xor(sumf, 8); - sumf += sub_group_shuffle_xor(sumf, 4); - sumf += sub_group_shuffle_xor(sumf, 2); - sumf += sub_group_shuffle_xor(sumf, 1); - - if (lane_q == 0) { - const int im_out = i03 * ne12 + (q_head_lo + q_id); - dst[im_out * ne1 * ne0 + r0] = sumf; - } - } -} - -#define N_K_ROWS_GQA_R2_DK256 16 -#define GQA_RATIO_R2 2 -#define LANES_PER_QH_R2 32 // = 64 / GQA_RATIO_R2 -#define DK_VEC_DK256 64 // DK / 4 for DK=256 - -#ifdef ADRENO_GPU -REQD_SUBGROUP_SIZE_64 -#endif -kernel void kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img( - __read_only image1d_buffer_t src0_img, - global char * src1, - ulong offset1, - global float * dst, - ulong offsetd, - int ne00, - int ne01, - int ne02, - ulong nb01, - ulong nb02, - ulong nb03, - int ne10, - int ne11, - int ne12, - ulong nb10, - ulong nb11, - ulong nb12, - ulong nb13, - int ne0, - int ne1, - int r2, - int r3 -) { - src1 = (global char *)((global char *)src1 + offset1); - dst = (global float*)((global char *)dst + offsetd); - - const int sgs_lid = get_sub_group_local_id(); - const int q_id = sgs_lid >> 5; // 0..1 - const int lane_q = sgs_lid & 31; // 0..31 - - const int r0_base = get_group_id(0) * N_K_ROWS_GQA_R2_DK256; - const int im_kv = get_group_id(2); - - const int i02 = im_kv % ne02; - const int i03 = im_kv / ne02; - - const int q_head_lo = i02 * GQA_RATIO_R2; - - __local float4 q_loc[GQA_RATIO_R2 * DK_VEC_DK256]; - #pragma unroll - for (int qh = 0; qh < GQA_RATIO_R2; ++qh) { - const int qh_idx = q_head_lo + qh; - global float4 * y4 = (global float4 *)(src1 + qh_idx * nb12 + i03 * nb13); - q_loc[qh * DK_VEC_DK256 + sgs_lid] = y4[sgs_lid]; - } - barrier(CLK_LOCAL_MEM_FENCE); - - const int pitch_px_row = (int)(nb01 >> 4); - const int pitch_px_head = (int)(nb02 >> 4); - const int pitch_px_n13 = (int)(nb03 >> 4); - - const int head_px_base = i02 * pitch_px_head + (i03 / r3) * pitch_px_n13; - - #pragma unroll - for (int dr = 0; dr < N_K_ROWS_GQA_R2_DK256; ++dr) { - const int r0 = r0_base + dr; - const int row_px_base = r0 * pitch_px_row + head_px_base; - - const int p = lane_q; - const half8 k8 = as_half8(read_imagef(src0_img, row_px_base + p)); - const int i0 = 2 * p; - const float4 qa = q_loc[q_id * DK_VEC_DK256 + i0 ]; - const float4 qb = q_loc[q_id * DK_VEC_DK256 + i0 + 1]; - - float sumf = - convert_float(k8.s0) * qa.s0 - + convert_float(k8.s1) * qa.s1 - + convert_float(k8.s2) * qa.s2 - + convert_float(k8.s3) * qa.s3 - + convert_float(k8.s4) * qb.s0 - + convert_float(k8.s5) * qb.s1 - + convert_float(k8.s6) * qb.s2 - + convert_float(k8.s7) * qb.s3; - - sumf += sub_group_shuffle_xor(sumf, 16); - sumf += sub_group_shuffle_xor(sumf, 8); - sumf += sub_group_shuffle_xor(sumf, 4); - sumf += sub_group_shuffle_xor(sumf, 2); - sumf += sub_group_shuffle_xor(sumf, 1); - - if (lane_q == 0) { - const int im_out = i03 * ne12 + (q_head_lo + q_id); - dst[im_out * ne1 * ne0 + r0] = sumf; - } - } -} diff --git a/ggml/src/ggml-opencl/kernels/unary_ext.cl b/ggml/src/ggml-opencl/kernels/unary_ext.cl index c5dcfec257bd..ff71ca0ddf7c 100644 --- a/ggml/src/ggml-opencl/kernels/unary_ext.cl +++ b/ggml/src/ggml-opencl/kernels/unary_ext.cl @@ -84,29 +84,3 @@ UNARY_EXT(floor, floor(x), floor UNARY_EXT(ceil, ceil(x), ceil(x)) UNARY_EXT(round, round(x), round(x)) UNARY_EXT(trunc, trunc(x), trunc(x)) - -// xielu has more args, cannot fit in UNARY_EXT -inline float xielu(float x, float alpha_n, float alpha_p, float beta, float eps) { - return x > 0.0f ? alpha_p*x*x + beta*x : (expm1(fmin(x, eps)) - x)*alpha_n + beta*x; -} - -#define XIELU_KERNEL(NAME, TYPE) \ -kernel void kernel_xielu_##NAME( \ - global const char * src0, ulong offset0, \ - global char * dst, ulong offsetd, \ - int ne00, ulong nb00, ulong nb01, ulong nb02, ulong nb03, \ - ulong nb0, ulong nb1, ulong nb2, ulong nb3, \ - float alpha_n, float alpha_p, float beta, float eps) { \ - const size_t i3 = get_group_id(2); \ - const size_t i2 = get_group_id(1); \ - const size_t i1 = get_group_id(0); \ - src0 += offset0 + i3*nb03 + i2*nb02 + i1*nb01; \ - dst += offsetd + i3*nb3 + i2*nb2 + i1*nb1; \ - for (size_t i0 = get_local_id(0); i0 < (size_t) ne00; i0 += get_local_size(0)) { \ - const float x = *(global const TYPE *)(src0 + i0*nb00); \ - *(global TYPE *)(dst + i0*nb0) = xielu(x, alpha_n, alpha_p, beta, eps); \ - } \ -} - -XIELU_KERNEL(f32, float) -XIELU_KERNEL(f16, half) diff --git a/ggml/src/ggml-opencl/kernels/xielu.cl b/ggml/src/ggml-opencl/kernels/xielu.cl new file mode 100644 index 000000000000..d4d83978b300 --- /dev/null +++ b/ggml/src/ggml-opencl/kernels/xielu.cl @@ -0,0 +1,26 @@ +#pragma OPENCL EXTENSION cl_khr_fp16 : enable + +inline float xielu(float x, float alpha_n, float alpha_p, float beta, float eps) { + return x > 0.0f ? alpha_p*x*x + beta*x : (expm1(fmin(x, eps)) - x)*alpha_n + beta*x; +} + +#define XIELU_KERNEL(NAME, TYPE) \ +kernel void kernel_xielu_##NAME( \ + global const char * src0, ulong offset0, \ + global char * dst, ulong offsetd, \ + int ne00, ulong nb00, ulong nb01, ulong nb02, ulong nb03, \ + ulong nb0, ulong nb1, ulong nb2, ulong nb3, \ + float alpha_n, float alpha_p, float beta, float eps) { \ + const size_t i3 = get_group_id(2); \ + const size_t i2 = get_group_id(1); \ + const size_t i1 = get_group_id(0); \ + src0 += offset0 + i3*nb03 + i2*nb02 + i1*nb01; \ + dst += offsetd + i3*nb3 + i2*nb2 + i1*nb1; \ + for (size_t i0 = get_local_id(0); i0 < (size_t) ne00; i0 += get_local_size(0)) { \ + const float x = *(global const TYPE *)(src0 + i0*nb00); \ + *(global TYPE *)(dst + i0*nb0) = xielu(x, alpha_n, alpha_p, beta, eps); \ + } \ +} + +XIELU_KERNEL(f32, float) +XIELU_KERNEL(f16, half) diff --git a/ggml/src/ggml-opencl/ops.h b/ggml/src/ggml-opencl/ops.h new file mode 100644 index 000000000000..37d8e8720d2e --- /dev/null +++ b/ggml/src/ggml-opencl/ops.h @@ -0,0 +1,1104 @@ +#pragma once + +#include "ggml-backend.h" + +#include + +struct ggml_backend_opencl_context; + +struct ggml_opencl_add_kernels { + cl_kernel kernel_add; + cl_kernel kernel_add_row; + cl_kernel kernel_add_f16; + cl_kernel kernel_add_row_f16; +}; + +struct ggml_opencl_add_id_kernels { + cl_kernel kernel_add_id; +}; + +struct ggml_opencl_mul_kernels { + cl_kernel kernel_mul; + cl_kernel kernel_mul_row; + cl_kernel kernel_mul_f16; + cl_kernel kernel_mul_row_f16; + cl_kernel kernel_mul_mat_scale = nullptr; +}; + +struct ggml_opencl_div_kernels { + cl_kernel kernel_div; + cl_kernel kernel_div_row; + cl_kernel kernel_div_f16; + cl_kernel kernel_div_row_f16; +}; + +struct ggml_opencl_sub_kernels { + cl_kernel kernel_sub; + cl_kernel kernel_sub_row; + cl_kernel kernel_sub_f16; + cl_kernel kernel_sub_row_f16; +}; + +struct ggml_opencl_scale_kernels { + cl_kernel kernel_scale_f32; + cl_kernel kernel_scale_f32_4; + cl_kernel kernel_scale_f32_nc; + cl_kernel kernel_scale_f16; + cl_kernel kernel_scale_f16_4; + cl_kernel kernel_scale_f16_nc; +}; + +struct ggml_opencl_sqr_kernels { + cl_kernel kernel_sqr_cont_f32; + cl_kernel kernel_sqr_cont_f32_4; + cl_kernel kernel_sqr_cont_f16; + cl_kernel kernel_sqr_cont_f16_4; +}; + +struct ggml_opencl_sqrt_kernels { + cl_kernel kernel_sqrt_cont_f32; + cl_kernel kernel_sqrt_cont_f32_4; + cl_kernel kernel_sqrt_cont_f16; + cl_kernel kernel_sqrt_cont_f16_4; +}; + +struct ggml_opencl_mean_kernels { + cl_kernel kernel_mean_f32; + cl_kernel kernel_mean_f32_4; +}; + +struct ggml_opencl_silu_kernels { + cl_kernel kernel_silu; + cl_kernel kernel_silu_4; + cl_kernel kernel_silu_nc; + cl_kernel kernel_silu_f16; + cl_kernel kernel_silu_f16_4; + cl_kernel kernel_silu_f16_nc; +}; + +struct ggml_opencl_gelu_kernels { + cl_kernel kernel_gelu; + cl_kernel kernel_gelu_4; + cl_kernel kernel_gelu_erf; + cl_kernel kernel_gelu_erf_4; + cl_kernel kernel_gelu_quick; + cl_kernel kernel_gelu_quick_4; +}; + +struct ggml_opencl_relu_kernels { + cl_kernel kernel_relu; +}; + +struct ggml_opencl_sigmoid_kernels { + cl_kernel kernel_sigmoid_f32; + cl_kernel kernel_sigmoid_f16; + cl_kernel kernel_sigmoid_f32_nc; + cl_kernel kernel_sigmoid_f16_nc; +}; + +struct ggml_opencl_tri_kernels { + cl_kernel kernel_tri; +}; + +struct ggml_opencl_fill_kernels { + cl_kernel kernel_fill; +}; + +struct ggml_opencl_arange_kernels { + cl_kernel kernel_arange; +}; + +struct ggml_opencl_clamp_kernels { + cl_kernel kernel_clamp; + cl_kernel kernel_clamp_nc; +}; + +struct ggml_opencl_glu_kernels { + cl_kernel kernel_geglu; + cl_kernel kernel_reglu; + cl_kernel kernel_swiglu; + cl_kernel kernel_swiglu_oai; + cl_kernel kernel_swiglu_clamp; + cl_kernel kernel_geglu_erf; + cl_kernel kernel_geglu_quick; + cl_kernel kernel_geglu_f16; + cl_kernel kernel_reglu_f16; + cl_kernel kernel_swiglu_f16; + cl_kernel kernel_swiglu_oai_f16; + cl_kernel kernel_swiglu_clamp_f16; + cl_kernel kernel_geglu_erf_f16; + cl_kernel kernel_geglu_quick_f16; +}; + +struct ggml_opencl_norm_kernels { + cl_kernel kernel_norm; + cl_kernel kernel_norm_mul_add; +}; + +struct ggml_opencl_rms_norm_kernels { + cl_kernel kernel_rms_norm; + cl_kernel kernel_rms_norm_mul; + cl_kernel kernel_rms_norm_mul_add; +}; + +struct ggml_opencl_l2_norm_kernels { + cl_kernel kernel_l2_norm_f32; +}; + +struct ggml_opencl_group_norm_kernels { + cl_kernel kernel_group_norm; + cl_kernel kernel_group_norm_mul_add; +}; + +struct ggml_opencl_diag_kernels { + cl_kernel kernel_diag_f32; +}; + +struct ggml_opencl_soft_max_kernels { + cl_kernel kernel_soft_max; + cl_kernel kernel_soft_max_4; + cl_kernel kernel_soft_max_f16; + cl_kernel kernel_soft_max_4_f16; +}; + +struct ggml_opencl_get_rows_kernels { + cl_kernel kernel_get_rows_f32; + cl_kernel kernel_get_rows_i32; + cl_kernel kernel_get_rows_f16; + cl_kernel kernel_get_rows_q4_0; +}; + +struct ggml_opencl_set_rows_kernels { + cl_kernel kernel_set_rows_f32_i64; + cl_kernel kernel_set_rows_f32_i32; + cl_kernel kernel_set_rows_f16_i64; + cl_kernel kernel_set_rows_f16_i32; + cl_kernel kernel_set_rows_q8_0_i64; + cl_kernel kernel_set_rows_q8_0_i32; + cl_kernel kernel_set_rows_q8_0_soa_i64; + cl_kernel kernel_set_rows_q8_0_soa_i32; + cl_kernel kernel_set_rows_q4_0_i64; + cl_kernel kernel_set_rows_q4_0_i32; + cl_kernel kernel_set_rows_q4_0_soa_i64; + cl_kernel kernel_set_rows_q4_0_soa_i32; +}; + +struct ggml_opencl_rope_kernels { + cl_kernel kernel_rope_norm_f32; + cl_kernel kernel_rope_norm_f16; + cl_kernel kernel_rope_neox_f32; + cl_kernel kernel_rope_neox_f16; + cl_kernel kernel_rope_multi_f32; + cl_kernel kernel_rope_multi_f16; + cl_kernel kernel_rope_vision_f32; + cl_kernel kernel_rope_vision_f16; +}; + +struct ggml_opencl_cpy_kernels { + cl_kernel kernel_cpy_f16_f16; + cl_kernel kernel_cpy_f16_f32; + cl_kernel kernel_cpy_f32_f16; + cl_kernel kernel_cpy_f32_f32; + cl_kernel kernel_cpy_f32_f32_pack; + cl_kernel kernel_cpy_i32_i32; + cl_kernel kernel_cpy_i32_f32; + cl_kernel kernel_cpy_f32_i32; + cl_kernel kernel_cpy_f32_f32_flat; +}; + +struct ggml_opencl_solve_tri_kernels { + cl_kernel kernel_solve_tri_f32; +}; + +struct ggml_opencl_im2col_kernels { + cl_kernel kernel_im2col_f32; + cl_kernel kernel_im2col_f16; +}; + +struct ggml_opencl_im2col_3d_kernels { + cl_kernel kernel_im2col_3d_f32; + cl_kernel kernel_im2col_3d_f16; +}; + +struct ggml_opencl_argmax_kernels { + cl_kernel kernel_argmax_f32_i32; +}; + +struct ggml_opencl_top_k_kernels { + cl_kernel kernel_top_k_f32; + cl_kernel kernel_top_k_merge_f32; +}; + +struct ggml_opencl_top_k_mask_kernels { + cl_kernel kernel_top_k_mask[2]; + cl_kernel kernel_top_k_mask_fill[2]; +}; + +struct ggml_opencl_lightning_indexer_kernels { + cl_kernel kernel_lightning_indexer; +}; + +struct ggml_opencl_argsort_kernels { + cl_kernel kernel_argsort_f32_i32; +}; + +struct ggml_opencl_sum_rows_kernels { + cl_kernel kernel_sum_rows_f32; + cl_kernel kernel_sum_rows_f32_4; +}; + +struct ggml_opencl_dsv4_hc_kernels { + cl_kernel kernel_dsv4_hc_pre = nullptr; + cl_kernel kernel_dsv4_hc_post[2] = {}; + size_t local_dsv4_hc_pre = 0; + size_t local_dsv4_hc_post[2] = {}; +}; + +struct ggml_opencl_cumsum_kernels { + cl_kernel kernel_cumsum_blk; + cl_kernel kernel_cumsum_add; +}; + +struct ggml_opencl_repeat_kernels { + cl_kernel kernel_repeat_f32; + cl_kernel kernel_repeat_f16; + cl_kernel kernel_repeat_i32; +}; + +struct ggml_opencl_pad_kernels { + cl_kernel kernel_pad; +}; + +struct ggml_opencl_tanh_kernels { + cl_kernel kernel_tanh_f32; + cl_kernel kernel_tanh_f32_4; + cl_kernel kernel_tanh_f32_nc; + cl_kernel kernel_tanh_f16; + cl_kernel kernel_tanh_f16_4; + cl_kernel kernel_tanh_f16_nc; +}; + +struct ggml_opencl_neg_kernels { + cl_kernel kernel_neg_f32; + cl_kernel kernel_neg_f32_4; + cl_kernel kernel_neg_f32_nc; + cl_kernel kernel_neg_f16; + cl_kernel kernel_neg_f16_4; + cl_kernel kernel_neg_f16_nc; +}; + +struct ggml_opencl_exp_kernels { + cl_kernel kernel_exp_f32; + cl_kernel kernel_exp_f32_4; + cl_kernel kernel_exp_f32_nc; + cl_kernel kernel_exp_f16; + cl_kernel kernel_exp_f16_4; + cl_kernel kernel_exp_f16_nc; +}; + +struct ggml_opencl_expm1_kernels { + cl_kernel kernel_expm1_f32; + cl_kernel kernel_expm1_f32_4; + cl_kernel kernel_expm1_f32_nc; + cl_kernel kernel_expm1_f16; + cl_kernel kernel_expm1_f16_4; + cl_kernel kernel_expm1_f16_nc; +}; + +struct ggml_opencl_abs_kernels { + cl_kernel kernel_abs_f32; + cl_kernel kernel_abs_f32_4; + cl_kernel kernel_abs_f32_nc; + cl_kernel kernel_abs_f16; + cl_kernel kernel_abs_f16_4; + cl_kernel kernel_abs_f16_nc; +}; + +struct ggml_opencl_xielu_kernels { + cl_kernel kernel_xielu_f32; + cl_kernel kernel_xielu_f16; +}; + +struct ggml_opencl_unary_ext_kernels { + cl_kernel kernel_sgn_f32; + cl_kernel kernel_sgn_f32_4; + cl_kernel kernel_sgn_f32_nc; + cl_kernel kernel_sgn_f16; + cl_kernel kernel_sgn_f16_4; + cl_kernel kernel_sgn_f16_nc; + cl_kernel kernel_step_f32; + cl_kernel kernel_step_f32_4; + cl_kernel kernel_step_f32_nc; + cl_kernel kernel_step_f16; + cl_kernel kernel_step_f16_4; + cl_kernel kernel_step_f16_nc; + cl_kernel kernel_elu_f32; + cl_kernel kernel_elu_f32_4; + cl_kernel kernel_elu_f32_nc; + cl_kernel kernel_elu_f16; + cl_kernel kernel_elu_f16_4; + cl_kernel kernel_elu_f16_nc; + cl_kernel kernel_hardswish_f32; + cl_kernel kernel_hardswish_f32_4; + cl_kernel kernel_hardswish_f32_nc; + cl_kernel kernel_hardswish_f16; + cl_kernel kernel_hardswish_f16_4; + cl_kernel kernel_hardswish_f16_nc; + cl_kernel kernel_hardsigmoid_f32; + cl_kernel kernel_hardsigmoid_f32_4; + cl_kernel kernel_hardsigmoid_f32_nc; + cl_kernel kernel_hardsigmoid_f16; + cl_kernel kernel_hardsigmoid_f16_4; + cl_kernel kernel_hardsigmoid_f16_nc; + cl_kernel kernel_floor_f32; + cl_kernel kernel_floor_f32_4; + cl_kernel kernel_floor_f32_nc; + cl_kernel kernel_floor_f16; + cl_kernel kernel_floor_f16_4; + cl_kernel kernel_floor_f16_nc; + cl_kernel kernel_ceil_f32; + cl_kernel kernel_ceil_f32_4; + cl_kernel kernel_ceil_f32_nc; + cl_kernel kernel_ceil_f16; + cl_kernel kernel_ceil_f16_4; + cl_kernel kernel_ceil_f16_nc; + cl_kernel kernel_round_f32; + cl_kernel kernel_round_f32_4; + cl_kernel kernel_round_f32_nc; + cl_kernel kernel_round_f16; + cl_kernel kernel_round_f16_4; + cl_kernel kernel_round_f16_nc; + cl_kernel kernel_trunc_f32; + cl_kernel kernel_trunc_f32_4; + cl_kernel kernel_trunc_f32_nc; + cl_kernel kernel_trunc_f16; + cl_kernel kernel_trunc_f16_4; + cl_kernel kernel_trunc_f16_nc; + cl_kernel kernel_log_f32; + cl_kernel kernel_log_f32_4; + cl_kernel kernel_log_f32_nc; + cl_kernel kernel_log_f16; + cl_kernel kernel_log_f16_4; + cl_kernel kernel_log_f16_nc; +}; + +struct ggml_opencl_softplus_kernels { + cl_kernel kernel_softplus_f32; + cl_kernel kernel_softplus_f32_4; + cl_kernel kernel_softplus_f32_nc; + cl_kernel kernel_softplus_f16; + cl_kernel kernel_softplus_f16_4; + cl_kernel kernel_softplus_f16_nc; +}; + +struct ggml_opencl_upscale_kernels { + cl_kernel kernel_upscale; + cl_kernel kernel_upscale_bilinear; +}; + +struct ggml_opencl_concat_kernels { + cl_kernel kernel_concat_b1; + cl_kernel kernel_concat_b2; + cl_kernel kernel_concat_b4; + cl_kernel kernel_concat_b8; + cl_kernel kernel_concat_b4_pack; +}; + +struct ggml_opencl_conv_2d_kernels { + cl_kernel kernel_conv_2d_f16; + cl_kernel kernel_conv_2d_f32; + cl_kernel kernel_conv_2d_f16_f32; +}; + +struct ggml_opencl_conv_2d_dw_kernels { + cl_kernel kernel_conv2d_dw_f32_f32; + cl_kernel kernel_conv2d_dwf16_f32; +}; + +struct ggml_opencl_ssm_conv_kernels { + cl_kernel kernel_ssm_conv_f32_f32; + cl_kernel kernel_ssm_conv_f32_f32_4; +}; + +struct ggml_opencl_gated_delta_net_kernels { + cl_kernel kernel_gated_delta_net_f32[4][2][2][2]; +}; + +struct ggml_opencl_ssm_scan_kernels { + cl_kernel kernel_ssm_scan_f32; + cl_kernel kernel_ssm_scan_f32_mamba2_d128; + cl_kernel kernel_ssm_scan_f32_mamba2_d256; +}; + +struct ggml_opencl_timestep_embedding_kernels { + cl_kernel kernel_timestep_embedding; +}; + +struct ggml_opencl_repack_kernels { + cl_kernel kernel_convert_block_q1_0; + cl_kernel kernel_restore_block_q1_0; + cl_kernel kernel_convert_block_q4_0; + cl_kernel kernel_restore_block_q4_0; + cl_kernel kernel_convert_block_q4_0_trans4_ns; + cl_kernel kernel_restore_block_q4_0_trans4_ns; + cl_kernel kernel_convert_block_q4_1; + cl_kernel kernel_restore_block_q4_1; + cl_kernel kernel_convert_block_q4_1_trans4_ns; + cl_kernel kernel_restore_block_q4_1_trans4_ns; + cl_kernel kernel_convert_block_q5_0; + cl_kernel kernel_restore_block_q5_0; + cl_kernel kernel_convert_block_q5_0_trans4_ns; + cl_kernel kernel_restore_block_q5_0_trans4_ns; + cl_kernel kernel_convert_block_q5_1; + cl_kernel kernel_restore_block_q5_1; + cl_kernel kernel_convert_block_q5_1_trans4_ns; + cl_kernel kernel_restore_block_q5_1_trans4_ns; + cl_kernel kernel_convert_block_q4_k_trans4_ns; + cl_kernel kernel_restore_block_q4_k_trans4_ns; + cl_kernel kernel_convert_block_q5_k_trans4_ns; + cl_kernel kernel_restore_block_q5_k_trans4_ns; + cl_kernel kernel_convert_block_q6_k_trans4_ns; + cl_kernel kernel_restore_block_q6_k_trans4_ns; + cl_kernel kernel_convert_block_mxfp4; + cl_kernel kernel_convert_block_mxfp4_trans; + cl_kernel kernel_restore_block_mxfp4; + cl_kernel kernel_restore_block_mxfp4_trans; + cl_kernel kernel_convert_block_mxfp4_trans4_ns; + cl_kernel kernel_restore_block_mxfp4_trans4_ns; + cl_kernel kernel_convert_block_q8_0; + cl_kernel kernel_restore_block_q8_0; + cl_kernel kernel_restore_block_q8_0_trans; + cl_kernel kernel_dequant_q8_0_f16_view_aos; + cl_kernel kernel_dequant_q8_0_f32_view_aos; + cl_kernel kernel_dequant_q4_0_f16_view_aos; + cl_kernel kernel_dequant_q4_0_f32_view_aos; + cl_kernel kernel_convert_block_q6_K_noshuffle; + cl_kernel kernel_restore_block_q6_K_noshuffle; + cl_kernel kernel_convert_bf16_to_f16; + cl_kernel kernel_convert_f16_to_bf16; + cl_kernel kernel_convert_block_q4_0_noshuffle; + cl_kernel kernel_restore_block_q4_0_noshuffle; + cl_kernel kernel_convert_block_q4_1_noshuffle; + cl_kernel kernel_restore_block_q4_1_noshuffle; + cl_kernel kernel_convert_block_q5_0_noshuffle; + cl_kernel kernel_restore_block_q5_0_noshuffle; + cl_kernel kernel_convert_block_q5_1_noshuffle; + cl_kernel kernel_restore_block_q5_1_noshuffle; + cl_kernel kernel_convert_block_q4_K_noshuffle; + cl_kernel kernel_restore_block_q4_K_noshuffle; + cl_kernel kernel_convert_block_q4_K; + cl_kernel kernel_restore_block_q4_K; + cl_kernel kernel_convert_block_q5_K; + cl_kernel kernel_restore_block_q5_K; + cl_kernel kernel_convert_block_q5_K_noshuffle; + cl_kernel kernel_restore_block_q5_K_noshuffle; + cl_kernel kernel_convert_block_q2_k_noshuffle; + cl_kernel kernel_restore_block_q2_k_noshuffle; + cl_kernel kernel_convert_block_q2_K; + cl_kernel kernel_restore_block_q2_K; + cl_kernel kernel_convert_block_q3_K; + cl_kernel kernel_restore_block_q3_K; + cl_kernel kernel_convert_block_q3_k_noshuffle; + cl_kernel kernel_restore_block_q3_k_noshuffle; + cl_kernel kernel_convert_block_iq2_xxs; + cl_kernel kernel_restore_block_iq2_xxs; + cl_kernel kernel_convert_block_iq2_xs; + cl_kernel kernel_restore_block_iq2_xs; + cl_kernel kernel_convert_block_iq2_s; + cl_kernel kernel_restore_block_iq2_s; + cl_kernel kernel_convert_block_q2_0; + cl_kernel kernel_restore_block_q2_0; + cl_kernel kernel_convert_block_iq1_m; + cl_kernel kernel_restore_block_iq1_m; + cl_kernel kernel_convert_block_iq1_s; + cl_kernel kernel_restore_block_iq1_s; + cl_kernel kernel_convert_block_iq3_xxs; + cl_kernel kernel_restore_block_iq3_xxs; + cl_kernel kernel_convert_block_iq3_s; + cl_kernel kernel_restore_block_iq3_s; + cl_kernel kernel_convert_block_iq4_xs; + cl_kernel kernel_restore_block_iq4_xs; + cl_kernel kernel_convert_block_iq4_xs_noshuffle; + cl_kernel kernel_restore_block_iq4_xs_noshuffle; + cl_kernel kernel_convert_block_q6_K; + cl_kernel kernel_restore_block_q6_K; + cl_kernel kernel_convert_block_iq4_nl; + cl_kernel kernel_restore_block_iq4_nl; + cl_kernel kernel_convert_block_iq4_nl_noshuffle; + cl_kernel kernel_restore_block_iq4_nl_noshuffle; + cl_kernel kernel_moe_expand_scale_q8_0; + cl_kernel kernel_moe_expand_scale_q5_0; + cl_kernel kernel_moe_expand_scale_q5_K; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel_convert_block_q4_k_tiled_ns; + cl_kernel kernel_convert_block_q6_k_tiled_ns; +#endif +}; + +struct ggml_opencl_mul_mat_kernels { + cl_kernel kernel_mul_mat_f32_f32; + cl_kernel kernel_mul_mv_f32_f32_r2 = nullptr; + cl_kernel kernel_fwht[2]; + size_t fwht_workgroup_size[2]; + cl_kernel kernel_mul_mat_f16_f16; + cl_kernel kernel_mul_mat_f16_f32_1row; + cl_kernel kernel_mul_mat_f16_f32_mrow; + cl_kernel kernel_mul_mat_f16_f32_mrow_r2; + cl_kernel kernel_mul_mat_f16_f32_mrow_r4; + cl_kernel kernel_mul_mat_f16_f32_mrow_h8; + cl_kernel kernel_mul_mat_f16_f32_mrow_h8r2; + cl_kernel kernel_mul_mat_f16_f32; + cl_kernel kernel_mul_mat_f16_f32_l4; + cl_kernel kernel_mul_mat_f16_f32_l4_dr; + cl_kernel kernel_mul_mat_f16_f32_l4_dr_ls; + cl_kernel kernel_mul_mat_f16_f32_l4_dr_lq; + cl_kernel kernel_mul_mat_f16_f32_l4_x8; + cl_kernel kernel_mul_mat_f16_f32_l4_x8_pair; + cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa4; + cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa4_img; + cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img; + cl_kernel kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img; + cl_kernel kernel_mul_mat_f16_f32_l4_y8; + cl_kernel kernel_mul_mat_f16_f32_l4_y8_gqa; + cl_kernel kernel_mul_mat_f16_f32_l4_y8_gqa_img; + cl_kernel kernel_mul_mat_f16_f32_tiled; + cl_kernel kernel_adreno_xmem_pack_src_f32; + cl_kernel kernel_adreno_xmem_prepack_weight_f16; + cl_kernel kernel_gemm_xmem_f16_f32_os8; + cl_kernel kernel_adreno_xmem_store_dst_f32; + cl_kernel kernel_mul_mm_f16_f32_kqv; + cl_kernel kernel_mul_mm_f16_f32_kq; + cl_kernel kernel_mul_mat_q4_0_f32; + cl_kernel kernel_mul_mat_q4_0_f32_v; + cl_kernel kernel_mul_mat_q4_0_f32_8x_flat; + cl_kernel kernel_mul_mv_q1_0_f32; + cl_kernel kernel_mul_mv_q1_0_f32_flat; + cl_kernel kernel_mul_mv_q2_K_f32; + cl_kernel kernel_mul_mv_q2_K_f32_flat; + cl_kernel kernel_mul_mv_q3_K_f32; + cl_kernel kernel_mul_mv_q3_K_f32_flat; + cl_kernel kernel_mul_mv_q2_0_f32; + cl_kernel kernel_mul_mv_q2_0_f32_flat; + cl_kernel kernel_mul_mv_iq2_s_f32; + cl_kernel kernel_mul_mv_iq2_s_f32_flat; + cl_kernel kernel_mul_mv_iq2_xs_f32; + cl_kernel kernel_mul_mv_iq2_xs_f32_flat; + cl_kernel kernel_mul_mv_iq2_xxs_f32; + cl_kernel kernel_mul_mv_iq2_xxs_f32_flat; + cl_kernel kernel_mul_mv_iq1_m_f32; + cl_kernel kernel_mul_mv_iq1_m_f32_flat; + cl_kernel kernel_mul_mv_iq1_s_f32; + cl_kernel kernel_mul_mv_iq1_s_f32_flat; + cl_kernel kernel_mul_mv_iq3_s_f32; + cl_kernel kernel_mul_mv_iq3_s_f32_flat; + cl_kernel kernel_mul_mv_iq3_xxs_f32; + cl_kernel kernel_mul_mv_iq3_xxs_f32_flat; + cl_kernel kernel_mul_mv_iq4_xs_f32; + cl_kernel kernel_mul_mv_iq4_xs_f32_flat; + cl_kernel kernel_mul_mat_q4_0_f32_1d_8x_flat; + cl_kernel kernel_mul_mat_q4_0_f32_1d_16x_flat; + cl_kernel kernel_mul_mv_q4_1_f32; + cl_kernel kernel_mul_mv_q4_1_f32_flat; + cl_kernel kernel_mul_mv_q5_0_f32; + cl_kernel kernel_mul_mv_q5_0_f32_flat; + cl_kernel kernel_mul_mv_q5_1_f32; + cl_kernel kernel_mul_mv_q5_1_f32_flat; + cl_kernel kernel_mul_mv_q4_K_f32; + cl_kernel kernel_mul_mv_q4_K_f32_flat; + cl_kernel kernel_mul_mv_q5_K_f32; + cl_kernel kernel_mul_mv_q5_K_f32_flat; + cl_kernel kernel_mul_mv_q6_K_f32; + cl_kernel kernel_mul_mv_q6_K_f32_flat; + cl_kernel kernel_mul_mv_mxfp4_f32; + cl_kernel kernel_mul_mv_mxfp4_f32_flat; + cl_kernel kernel_mul_mv_q8_0_f32; + cl_kernel kernel_mul_mv_q8_0_f32_flat; + cl_kernel kernel_mul_mv_iq4_nl_f32; + cl_kernel kernel_mul_mv_iq4_nl_f32_flat; + cl_kernel kernel_mul_mm_f32_f32_l4_lm; + cl_kernel kernel_gemv_f32_f32_mc; + cl_kernel kernel_gemv_f32_f32_mcr = nullptr; + cl_kernel kernel_mul_mm_f16_f32_l4_lm; + cl_kernel kernel_mul_mm_f16_f32_l4_lm_n8; + cl_kernel kernel_mul_mm_q1_0_f32_l4_lm; + cl_kernel kernel_mul_mm_q2_k_f32_l4_lm; + cl_kernel kernel_mul_mm_q3_k_f32_l4_lm; + cl_kernel kernel_mul_mm_q2_0_f32_l4_lm; + cl_kernel kernel_mul_mm_iq2_s_f32_l4_lm; + cl_kernel kernel_mul_mm_iq2_xs_f32_l4_lm; + cl_kernel kernel_mul_mm_iq2_xxs_f32_l4_lm; + cl_kernel kernel_mul_mm_iq1_m_f32_l4_lm; + cl_kernel kernel_mul_mm_iq1_s_f32_l4_lm; + cl_kernel kernel_mul_mm_iq3_s_f32_l4_lm; + cl_kernel kernel_mul_mm_iq3_xxs_f32_l4_lm; + cl_kernel kernel_mul_mm_iq4_xs_f32_l4_lm; + cl_kernel kernel_mul_mm_q4_0_f32_l4_lm; + cl_kernel kernel_mul_mm_q4_1_f32_l4_lm; + cl_kernel kernel_mul_mm_q5_0_f32_l4_lm; + cl_kernel kernel_mul_mm_q5_1_f32_l4_lm; + cl_kernel kernel_mul_mm_q8_0_f32_l4_lm; + cl_kernel kernel_mul_mm_q4_k_f32_l4_lm; + cl_kernel kernel_mul_mm_q5_k_f32_l4_lm; + cl_kernel kernel_mul_mm_q6_k_f32_l4_lm; + cl_kernel kernel_mul_mm_iq4_nl_f32_l4_lm; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel_transpose_32; + cl_kernel kernel_transpose_32_16; + cl_kernel kernel_transpose_16; + cl_kernel kernel_transpose_8_buf; + cl_kernel kernel_transpose_16_buf; + cl_kernel kernel_transpose_32_buf; + cl_kernel kernel_transpose_16_4x1; + cl_kernel kernel_gemm_noshuffle_q4_0_f32; + cl_kernel kernel_gemv_noshuffle_q4_0_f32; + cl_kernel kernel_gemv_noshuffle_q4_0_f32_mc3; + cl_kernel kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin; + cl_kernel kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin; + cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin; + cl_kernel kernel_gemv_noshuffle_q4_0_f32_32b_trans; + cl_kernel kernel_gemv_noshuffle_q4_0_f32_4096_1_11008; + cl_kernel kernel_gemv_noshuffle_q4_0_f32_4096_1_4096; + cl_kernel kernel_gemv_noshuffle_q4_0_f32_11008_1_4096; + cl_kernel kernel_gemv_noshuffle_q4_0_f32_32000_1_4096; + cl_kernel kernel_gemv_noshuffle_q4_1_f32; + cl_kernel kernel_gemv_noshuffle_q4_1_f32_mc3; + cl_kernel kernel_gemm_noshuffle_q4_1_f32; + cl_kernel kernel_gemm_noshuffle_q8_0_f32; + cl_kernel kernel_gemm_noshuffle_q8_0_f32_bin; + cl_kernel kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin = nullptr; + cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a; + cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4; + cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg; + cl_kernel kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin; + cl_kernel kernel_gemv_noshuffle_q8_0_f32; + cl_kernel kernel_gemv_noshuffle_q8_0_f32_splitk; + cl_kernel kernel_gemv_noshuffle_q8_0_f32_mc; + cl_kernel kernel_gemm_noshuffle_q1_0_f32; + cl_kernel kernel_gemv_noshuffle_q1_0_f32; + cl_kernel kernel_gemv_noshuffle_q1_0_f32_nsg1; + cl_kernel kernel_gemv_noshuffle_q2_k_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_q2_k_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_q2_k_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_q2_k_q8_1_dp4a_narrow = nullptr; + int q2_k_mv_rows = 4; + int q2_k_mv_nsg = 4; + cl_kernel kernel_gemv_noshuffle_q3_k_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_q3_k_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_q3_k_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_q3_k_q8_1_dp4a_narrow = nullptr; + int q3_k_mv_rows = 2; + int q3_k_mv_nsg = 8; + cl_kernel kernel_gemv_noshuffle_q2_0_f32 = nullptr; + cl_kernel kernel_gemv_noshuffle_q2_0_f32_wide = nullptr; + size_t q2_0_mv_workgroup_size = 512; + size_t q2_0_mv_workgroup_size_wide = 512; + cl_kernel kernel_gemm_noshuffle_q2_0_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_q2_0_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_q2_0_q8_1_dp4a_narrow = nullptr; + int q2_0_mv_nsg = 32; + cl_kernel kernel_gemv_noshuffle_iq2_s_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_s_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_s_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_s_q8_1_dp4a_narrow = nullptr; + int iq2_s_mv_nsg = 8; + cl_kernel kernel_gemv_noshuffle_iq2_xs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_xs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a_narrow = nullptr; + int iq2_xs_mv_nsg = 4; + cl_kernel kernel_gemv_noshuffle_iq2_xxs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_xxs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a_narrow = nullptr; + int iq2_xxs_mv_nsg = 4; + cl_kernel kernel_gemv_noshuffle_iq1_m_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq1_m_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq1_m_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq1_m_q8_1_dp4a_narrow = nullptr; + int iq1_m_mv_nsg = 4; + cl_kernel kernel_gemv_noshuffle_iq1_s_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq1_s_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq1_s_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq1_s_q8_1_dp4a_narrow = nullptr; + int iq1_s_mv_nsg = 4; + cl_kernel kernel_gemv_noshuffle_iq3_xxs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq3_xxs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a_narrow = nullptr; + int iq3_xxs_mv_nsg = 4; + cl_kernel kernel_gemv_noshuffle_iq3_s_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq3_s_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq3_s_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq3_s_q8_1_dp4a_narrow = nullptr; + int iq3_s_mv_nsg = 4; + cl_kernel kernel_gemv_noshuffle_iq4_xs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq4_xs_f32 = nullptr; + cl_kernel kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a = nullptr; + cl_kernel kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a_narrow = nullptr; + int iq4_xs_mv_nsg = 8; + cl_kernel kernel_gemv_noshuffle_q4_k_f32; + cl_kernel kernel_gemv_noshuffle_q4_k_f32_o4; + cl_kernel kernel_gemv_noshuffle_q4_k_f32_tiled; + cl_kernel kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a = nullptr; + cl_kernel kernel_gemv_noshuffle_q4_k_f32_splitk; + cl_kernel kernel_gemv_splitk_reduce_f32; + cl_kernel kernel_gemv_noshuffle_q4_k_f32_glu; + cl_kernel kernel_gemv_noshuffle_q4_k_f32_mc3; + cl_kernel kernel_gemm_noshuffle_q4_k_f32; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin; + cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin; + cl_kernel kernel_gemv_noshuffle_q4_k_f32_32b_trans; + cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a; + cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4; + cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg; + cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow; + cl_kernel kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow_wimg; + cl_kernel kernel_gemm_noshuffle_q5_k_q8_1_dp4a; + cl_kernel kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4; + cl_kernel kernel_gemm_noshuffle_q6_k_q8_1_dp4a; + cl_kernel kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4; + cl_kernel kernel_quant_a_q8_1; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_r1; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_kimg; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_cok; + cl_kernel kernel_gemv_noshuffle_q6_K_f32; + cl_kernel kernel_gemv_noshuffle_q6_K_f32_o4; + cl_kernel kernel_gemv_noshuffle_q6_K_f32_o4_global; + cl_kernel kernel_gemv_noshuffle_q6_K_f32_tiled; + cl_kernel kernel_gemv_noshuffle_q6_K_f32_tiled_mc3; // tiled multi-column (N 2..4) verify lm_head + cl_kernel kernel_gemm_noshuffle_q6_K_f32_tiled; + cl_kernel kernel_gemv_noshuffle_q6_K_f32_mc3; + cl_kernel kernel_gemm_noshuffle_q6_K_f32; + cl_kernel kernel_gemm_noshuffle_q6_K_f32_cok; + cl_kernel kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin; + cl_kernel kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin; + cl_kernel kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin; + cl_kernel kernel_gemv_noshuffle_q6_k_f32_32b_trans; + cl_kernel kernel_gemv_noshuffle_q5_k_f32; + cl_kernel kernel_gemv_noshuffle_q5_k_f32_mc3; + cl_kernel kernel_gemm_noshuffle_q5_k_f32; + cl_kernel kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin; + cl_kernel kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin; + cl_kernel kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin; + cl_kernel kernel_gemv_noshuffle_q5_k_f32_32b_trans; + cl_kernel kernel_gemv_noshuffle_q5_0_f32; + cl_kernel kernel_gemm_noshuffle_q5_0_f32; + cl_kernel kernel_gemm_noshuffle_q5_0_q8_1_dp4a; + cl_kernel kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg; + cl_kernel kernel_gemv_noshuffle_q5_1_f32; + cl_kernel kernel_gemm_noshuffle_q5_1_f32; + cl_kernel kernel_gemv_noshuffle_iq4_nl_f32; + cl_kernel kernel_gemm_noshuffle_iq4_nl_f32; + cl_kernel kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a; + cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a; + cl_kernel kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4; + cl_kernel kernel_pack_b_f16_coopmat; + cl_kernel kernel_gemm_noshuffle_q4_0_f32_coopmat; + cl_kernel kernel_gemm_noshuffle_q5_0_f32_coopmat; + cl_kernel kernel_gemm_noshuffle_q8_0_f32_coopmat; + cl_kernel kernel_gemm_noshuffle_q4_k_f32_coopmat; + cl_kernel kernel_gemm_noshuffle_q5_k_f32_coopmat; + cl_kernel kernel_gemm_noshuffle_q6_k_f32_coopmat; + cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c4; + cl_kernel kernel_gemm_coopk_q4_0_q8_1_dp4a_c2; + int nsg_coopk_dp4a_q4_0 = 8; + int rows_coopk_dp4a_q4_0 = 4; + cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_c4; + cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_c2; + int nsg_coopk_dp4a_q4_k = 8; + int rows_coopk_dp4a_q4_k = 4; + cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4; + cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2; + int nsg_coopk_dp4a_q4_k_bin_c4 = 8; + int nsg_coopk_dp4a_q4_k_bin_c2 = 8; + cl_kernel kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = nullptr; + cl_kernel kernel_quant_a_q8_1_k4 = nullptr; + int nsg_coopk_dp4a_q4_k_bin_c8 = 4; + cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c4; + cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_c2; + int nsg_coopk_dp4a_q6_k = 8; + int rows_coopk_dp4a_q6_k = 4; + cl_kernel kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = nullptr; + cl_kernel kernel_quant_a_q8_1_k4h = nullptr; + int nsg_coopk_dp4a_q6_k_bin_c8 = 4; +#endif +}; + +struct ggml_opencl_mul_mat_id_kernels { + cl_kernel kernel_add_id_add_id_swiglu_oai; + cl_kernel kernel_gemv_moe_q4_0_f32_ns; + cl_kernel kernel_gemm_moe_q4_0_f32_ns; + cl_kernel kernel_gemm_moe_q4_0_f32_ns_bin; + cl_kernel kernel_gemm_moe_q8_0_f32_ns; + cl_kernel kernel_gemv_moe_q4_1_f32_ns; + cl_kernel kernel_gemm_moe_q4_1_f32_ns; + cl_kernel kernel_gemm_moe_q4_1_f32_ns_bin; + cl_kernel kernel_gemv_moe_q5_0_f32_ns; + cl_kernel kernel_gemm_moe_q5_0_f32_ns; + cl_kernel kernel_gemv_moe_q5_1_f32_ns; + cl_kernel kernel_gemm_moe_q5_1_f32_ns; + cl_kernel kernel_gemv_moe_q4_k_f32_ns; + cl_kernel kernel_gemm_moe_q4_k_f32_ns; + cl_kernel kernel_gemm_moe_q4_k_f32_ns_bin; + cl_kernel kernel_gemv_moe_q4_k_f32_ns_wimg; + cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a; + cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_bin; + cl_kernel kernel_moe_reorder_quant_a_q8_1; + cl_kernel kernel_gemm_moe_q8_1_dp4a_q80; + cl_kernel kernel_gemm_moe_q8_1_dp4a_q50; + cl_kernel kernel_gemm_moe_q8_1_dp4a_q5k; + cl_kernel kernel_gemv_moe_q5_k_f32_ns; + cl_kernel kernel_gemm_moe_q5_k_f32_ns; + cl_kernel kernel_gemv_moe_q6_k_f32_ns; + cl_kernel kernel_gemm_moe_q6_k_f32_ns; + cl_kernel kernel_gemm_moe_q6_k_f32_ns_bin; + cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a; + cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_bin; + cl_kernel kernel_gemv_moe_mxfp4_f32; + cl_kernel kernel_gemm_moe_mxfp4_f32; + cl_kernel kernel_gemv_moe_mxfp4_f32_ns; + cl_kernel kernel_gemm_moe_mxfp4_f32_ns; + cl_kernel kernel_gemm_moe_mxfp4_f32_ns_bin; + cl_kernel kernel_gemv_moe_mxfp4_f32_ns_wimg; + cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a; + cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a; + cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_bin; + cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin; + cl_kernel kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr; + cl_kernel kernel_gemm_moe_q4_0_q8_1_dp4a_bin; + cl_kernel kernel_transpose_activation_q8; + cl_kernel kernel_moe_reorder_b; + cl_kernel kernel_moe_reorder_b_f16 = nullptr; + cl_kernel kernel_gemm_moe_mxfp4_f32_ns_coopmat = nullptr; + cl_kernel kernel_gemm_moe_q4_0_f32_ns_coopmat = nullptr; + cl_kernel kernel_gemm_moe_q4_1_f32_ns_coopmat = nullptr; + cl_kernel kernel_gemm_moe_q5_0_f32_ns_coopmat = nullptr; + cl_kernel kernel_gemm_moe_q5_1_f32_ns_coopmat = nullptr; + cl_kernel kernel_gemm_moe_q4_k_f32_ns_coopmat = nullptr; + cl_kernel kernel_gemm_moe_q5_k_f32_ns_coopmat = nullptr; + cl_kernel kernel_gemm_moe_q6_k_f32_ns_coopmat = nullptr; + cl_kernel kernel_moe_histogram; + cl_kernel kernel_moe_zero_dst; + cl_kernel kernel_moe_scan; + cl_kernel kernel_moe_fill; + cl_kernel kernel_moe_scatter; + cl_kernel kernel_moe_scatter_stable; + cl_kernel kernel_moe_combine_f32; + cl_kernel kernel_moe_combine_bias_f32; + cl_kernel kernel_mul_mv_id_f32_f32; + cl_kernel kernel_mul_mm_id_f32_f32; + cl_kernel kernel_mul_mv_id_q4_0_f32_8x_flat; + cl_kernel kernel_mul_mv_id_q8_0_f32; + cl_kernel kernel_mul_mv_id_q8_0_f32_flat; + cl_kernel kernel_mul_mv_id_mxfp4_f32; + cl_kernel kernel_mul_mv_id_mxfp4_f32_flat; +}; + +void ggml_cl_init_fa_dims_table(); +bool ggml_opencl_ensure_fa_f32_f16_prefill_512( + ggml_backend_opencl_context * backend_ctx, bool split); +bool ggml_opencl_ensure_fa_f32_f16_vec_512(ggml_backend_opencl_context * backend_ctx); +bool use_fa_bin_kernels_prefill( + const ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v); + +void ggml_cl_nop(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_get_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_set_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_add(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_add_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_div(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_sub(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_sqr(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_sqrt(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mean(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_ssm_conv(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_ssm_scan(ggml_backend_t backend, ggml_tensor * dst); +void ggml_cl_gelu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_gelu_erf(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_gelu_quick(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_silu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_relu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_sigmoid(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_tri(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_fill(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_arange(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_clamp(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_rms_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_group_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_l2_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_tanh(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_neg(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_exp(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_expm1(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_abs(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_xielu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_sgn(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_step(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_elu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_hardswish(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_hardsigmoid(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_floor(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_ceil(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_round(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_trunc(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_log(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_softplus(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_repeat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_concat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_conv_2d(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_conv2_dw(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); + +void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_dup(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_cont(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_reshape(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_view(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_permute(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_transpose(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_set(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_diag(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_rope(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_solve_tri(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_im2col(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_im2col_3d(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_argmax(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_lightning_indexer(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_top_k(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_top_k_mask(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_argsort(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_dsv4_hc(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_sum_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_cumsum(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_glu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_pad(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst); +void ggml_cl_upscale(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst); +void ggml_cl_timestep_embedding(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst); +void ggml_cl_flash_attn(ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst); +void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst); +bool ggml_cl_mul_mat_can_use_fwht(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * op); + +// adreno mul_mat +bool ggml_cl_can_use_adreno_xmem_gemm_f16_f32(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * dst); +void ggml_cl_mul_mat_f16_f32_adreno_xmem(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +bool ggml_cl_mul_mat_f16_f32_attn_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_kq_kqv_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool is_kq); +void ggml_cl_mul_mat_q1_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q2_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q2_k_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q3_k_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq2_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq2_xs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq2_xxs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq1_m_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq1_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq3_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq3_xxs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq4_xs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q4_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q4_1_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q5_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q5_1_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_iq4_nl_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q4_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q6_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); +void ggml_cl_mul_mat_q5_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst); + +// fused ops +void ggml_opencl_op_rms_norm_fused(ggml_backend_t backend, ggml_tensor * rms_norm_tensor, ggml_tensor * mul_tensor); +void ggml_opencl_op_rms_norm_mul_add_fused(ggml_backend_t backend, ggml_tensor * rms_norm_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor); +void ggml_opencl_op_norm_fused(ggml_backend_t backend, ggml_tensor * norm_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor); +void ggml_opencl_op_group_norm_fused(ggml_backend_t backend, ggml_tensor * gn_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor); +void ggml_cl_moe_combine_fused(ggml_backend_t backend, const ggml_tensor * mul, const ggml_tensor * dst); +void ggml_cl_moe_bias_glu_fused(ggml_backend_t backend, ggml_tensor * gate_mm, const ggml_tensor * gate_add, + ggml_tensor * up_mm, const ggml_tensor * up_add, const ggml_tensor * glu); +void ggml_cl_moe_bias_combine_fused(ggml_backend_t backend, const ggml_tensor * add, + const ggml_tensor * mul, const ggml_tensor * dst); +void ggml_cl_mul_mat_q4_K_glu_fused(ggml_backend_t backend, ggml_tensor * gate_tensor, ggml_tensor * up_tensor, ggml_tensor * glu_tensor); + +// kernel loaders +void ggml_cl_load_kernels_nop(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_unary_ext(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_get_rows(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_set_rows(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_add(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_add_id(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_mul(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_div(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_sub(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_sqr(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_sqrt(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_mean(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_ssm_conv(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_ssm_scan(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_gelu(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_silu(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_relu(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_sigmoid(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_tri(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_fill(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_arange(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_clamp(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_norm(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_rms_norm(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_group_norm(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_l2_norm(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_tanh(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_neg(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_exp(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_expm1(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_abs(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_xielu(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_softplus(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_repeat(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_pad(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_upscale(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_concat(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_timestep_embedding(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_flash_attn(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_mul_mat(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_mul_mat_adreno(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_conv_2d(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_conv_2d_dw(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_mul_mat_id(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_scale(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_cpy(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_dup(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_cont(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_reshape(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_view(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_permute(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_transpose(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_set(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_diag(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_soft_max(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_rope(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_solve_tri(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_im2col(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_im2col_3d(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_argmax(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_lightning_indexer(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_top_k(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_top_k_mask(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_argsort(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_dsv4_hc(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_sum_rows(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_cumsum(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_glu(ggml_backend_opencl_context * backend_ctx); +void ggml_cl_load_kernels_gated_delta_net(ggml_backend_opencl_context * backend_ctx); diff --git a/ggml/src/ggml-opencl/ops/abs.cpp b/ggml/src/ggml-opencl/ops/abs.cpp new file mode 100644 index 000000000000..a8277574d10b --- /dev/null +++ b/ggml/src/ggml-opencl/ops/abs.cpp @@ -0,0 +1,123 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_abs(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // abs + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "abs.cl.h" + }; +#else + const std::string kernel_src = read_file("abs.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->abs.kernel_abs_f32 = clCreateKernel(prog, "kernel_abs_f32", &err), err)); + CL_CHECK((backend_ctx->abs.kernel_abs_f32_4 = clCreateKernel(prog, "kernel_abs_f32_4", &err), err)); + CL_CHECK((backend_ctx->abs.kernel_abs_f32_nc = clCreateKernel(prog, "kernel_abs_f32_nc", &err), err)); + CL_CHECK((backend_ctx->abs.kernel_abs_f16 = clCreateKernel(prog, "kernel_abs_f16", &err), err)); + CL_CHECK((backend_ctx->abs.kernel_abs_f16_4 = clCreateKernel(prog, "kernel_abs_f16_4", &err), err)); + CL_CHECK((backend_ctx->abs.kernel_abs_f16_nc = clCreateKernel(prog, "kernel_abs_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_abs(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel; + + if (ggml_is_contiguous(src0)) { + // Handle contiguous input + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->abs.kernel_abs_f32_4; + } else { + kernel = backend_ctx->abs.kernel_abs_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->abs.kernel_abs_f32; + } else { + kernel = backend_ctx->abs.kernel_abs_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); + } else { + // Handle non-contiguous input + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->abs.kernel_abs_f32_nc; + } else { + kernel = backend_ctx->abs.kernel_abs_f16_nc; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/add.cpp b/ggml/src/ggml-opencl/ops/add.cpp new file mode 100644 index 000000000000..e40269a41861 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/add.cpp @@ -0,0 +1,204 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_add(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // add + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "add.cl.h" + }; +#else + const std::string kernel_src = read_file("add.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->add.kernel_add = clCreateKernel(prog, "kernel_add", &err), err)); + CL_CHECK((backend_ctx->add.kernel_add_row = clCreateKernel(prog, "kernel_add_row", &err), err)); + CL_CHECK((backend_ctx->add.kernel_add_f16 = clCreateKernel(prog, "kernel_add_f16", &err), err)); + CL_CHECK((backend_ctx->add.kernel_add_row_f16 = clCreateKernel(prog, "kernel_add_row_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_add(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne10 = src1->ne[0]; + const int ne11 = src1->ne[1]; + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; + + const cl_ulong nb10 = src1->nb[0]; + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + const int ne2 = dst->ne[2]; + const int ne3 = dst->ne[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel; + + const bool bcast_row = ggml_is_contiguous(src0) && ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0; + + if (bcast_row) { + GGML_ASSERT(ggml_is_contiguous(src0)); + GGML_ASSERT(ne11 == 1); + } + + if (dst->type == GGML_TYPE_F32) { + GGML_ASSERT(src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32); + if (bcast_row) { + kernel = backend_ctx->add.kernel_add_row; + const int ne = ne10 / 4; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); + } else { + kernel = backend_ctx->add.kernel_add; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne3)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb3)); + } + } else if (dst->type == GGML_TYPE_F16) { + GGML_ASSERT(src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_F32); + GGML_ASSERT(src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_F32); + const int type_src0 = (src0->type == GGML_TYPE_F32); + const int type_src1 = (src1->type == GGML_TYPE_F32); + if (bcast_row) { + kernel = backend_ctx->add.kernel_add_row_f16; + const int ne = ne10 / 4; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &type_src0)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &type_src1)); + } else { + kernel = backend_ctx->add.kernel_add_f16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne3)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 30, sizeof(int), &type_src0)); + CL_CHECK(clSetKernelArg(kernel, 31, sizeof(int), &type_src1)); + } + } else { + GGML_ASSERT(false && "unsupported data types for add"); + } + + if (bcast_row) { + int n = ggml_nelements(dst)/4; + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size_ptr, dst); + } else { + unsigned int nth = MIN(64, ne0); + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/add_id.cpp b/ggml/src/ggml-opencl/ops/add_id.cpp new file mode 100644 index 000000000000..1d8cd0f9d340 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/add_id.cpp @@ -0,0 +1,92 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_add_id(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // add_id + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "add_id.cl.h" + }; +#else + const std::string kernel_src = read_file("add_id.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->add_id.kernel_add_id = clCreateKernel(prog, "kernel_add_id", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_add_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + const ggml_tensor * src2 = dst->src[2]; + GGML_ASSERT(src2); + GGML_ASSERT(src2->extra); + + GGML_ASSERT(src0->type == GGML_TYPE_F32); + GGML_ASSERT(src1->type == GGML_TYPE_F32); + GGML_ASSERT(src2->type == GGML_TYPE_I32); + GGML_ASSERT(dst->type == GGML_TYPE_F32); + + GGML_ASSERT(ggml_is_contiguous_rows(src0)); + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + + const cl_ulong nb11 = src1->nb[1]; + + const cl_ulong nb21 = src2->nb[1]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offset2 = extra2->offset + src2->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel = backend_ctx->add_id.kernel_add_id; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); + + int nth = MIN(ne00, (int) backend_ctx->get_kernel_workgroup_size(kernel)); + size_t global_work_size[] = { (size_t)ne01*nth, (size_t)ne02, 1 }; + size_t local_work_size[] = { (size_t)nth, 1, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/arange.cpp b/ggml/src/ggml-opencl/ops/arange.cpp new file mode 100644 index 000000000000..d1cfc5a3936c --- /dev/null +++ b/ggml/src/ggml-opencl/ops/arange.cpp @@ -0,0 +1,58 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_arange(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // arange + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "arange.cl.h" + }; +#else + const std::string kernel_src = read_file("arange.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->arange.kernel_arange = clCreateKernel(prog, "kernel_arange_f32", &err), err)); + GGML_LOG_CONT("."); + + CL_CHECK(clReleaseProgram(prog)); + } +} + +void ggml_cl_arange(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(dst->type == GGML_TYPE_F32); + + UNUSED(src0); + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + float start; + float step; + memcpy(&start, (float *) dst->op_params + 0, sizeof(float)); + memcpy(&step, (float *) dst->op_params + 2, sizeof(float)); + + const int n = dst->ne[0]; + + cl_kernel kernel = backend_ctx->arange.kernel_arange; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(float), &start)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &step)); + + size_t local_work_size[1] = { 64 }; + size_t global_work_size[1] = { ((size_t)n + local_work_size[0] - 1) / local_work_size[0] * local_work_size[0] }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/argmax.cpp b/ggml/src/ggml-opencl/ops/argmax.cpp new file mode 100644 index 000000000000..348677de7a2a --- /dev/null +++ b/ggml/src/ggml-opencl/ops/argmax.cpp @@ -0,0 +1,58 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_argmax(ggml_backend_opencl_context * backend_ctx) { + auto opencl_c_std = + std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + std::to_string(backend_ctx->opencl_c_version.minor); + std::string compile_opts = std::string("-cl-std=") + opencl_c_std; + + if (!backend_ctx->kernels_loaded_argmax) { + cl_int err; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "argmax.cl.h" + }; +#else + const std::string kernel_src = read_file("argmax.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->argmax.kernel_argmax_f32_i32 = clCreateKernel(prog, "kernel_argmax_f32_i32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + backend_ctx->kernels_loaded_argmax = true; + } +} + +void ggml_cl_argmax(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_UNUSED(src1); + + GGML_ASSERT(src0->type == GGML_TYPE_F32); + GGML_ASSERT(dst->type == GGML_TYPE_I32); + GGML_ASSERT(ggml_is_contiguous(src0)); + GGML_ASSERT(ggml_is_contiguous(dst)); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + const int ne00 = src0->ne[0]; + const int nrows = ggml_nrows(src0); + constexpr int nth = 64; + + cl_kernel kernel = backend_ctx->argmax.kernel_argmax_f32_i32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &nrows)); + + size_t global_work_size[] = { (size_t) nth, (size_t) CEIL_DIV(nrows, 2), 1 }; + size_t local_work_size[] = { (size_t) nth, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/argsort.cpp b/ggml/src/ggml-opencl/ops/argsort.cpp new file mode 100644 index 000000000000..ee48055517f2 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/argsort.cpp @@ -0,0 +1,83 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_argsort(ggml_backend_opencl_context *backend_ctx) { + // compiler options for general kernels + auto opencl_c_std = + std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + std::to_string(backend_ctx->opencl_c_version.minor); + std::string compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable -cl-unsafe-math-optimizations" + " -cl-finite-math-only -cl-fast-relaxed-math"; + + // argsort + if (!backend_ctx->kernels_loaded_argsort) { + cl_int err; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "argsort.cl.h" + }; +#else + const std::string kernel_src = read_file("argsort.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->argsort.kernel_argsort_f32_i32 = clCreateKernel(prog, "kernel_argsort_f32_i32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + backend_ctx->kernels_loaded_argsort = true; + } +} + + +void ggml_cl_argsort(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_UNUSED(src1); + + GGML_ASSERT(src0->type == GGML_TYPE_F32); + GGML_ASSERT( dst->type == GGML_TYPE_I32); + GGML_ASSERT(ggml_is_contiguous(src0)); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int nrows = ggml_nrows(src0); + + int ne00_padded = 1; + while (ne00_padded < ne00) { + ne00_padded *= 2; + } + + int order = (enum ggml_sort_order) dst->op_params[0]; + + cl_kernel kernel = backend_ctx->argsort.kernel_argsort_f32_i32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00_padded)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &order)); + CL_CHECK(clSetKernelArg(kernel, 7, ne00_padded*sizeof(int), NULL)); + + size_t global_work_size[] = {(size_t)ne00_padded, (size_t)nrows, (size_t)1}; + size_t local_work_size[] = {(size_t)ne00_padded, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + const int ne21 = dst->ne[1]; + if ((strstr(src0->name, "_moe") != NULL) && (ne21 != 1)) { + backend_ctx->toggle_reorder = true; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS +} diff --git a/ggml/src/ggml-opencl/ops/clamp.cpp b/ggml/src/ggml-opencl/ops/clamp.cpp new file mode 100644 index 000000000000..e30ff30b7c2e --- /dev/null +++ b/ggml/src/ggml-opencl/ops/clamp.cpp @@ -0,0 +1,107 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_clamp(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // clamp + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "clamp.cl.h" + }; +#else + const std::string kernel_src = read_file("clamp.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->clamp.kernel_clamp = clCreateKernel(prog, "kernel_clamp", &err), err)); + CL_CHECK((backend_ctx->clamp.kernel_clamp_nc = clCreateKernel(prog, "kernel_clamp_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_clamp(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + float min; + float max; + memcpy(&min, ((int32_t *) dst->op_params) + 0, sizeof(float)); + memcpy(&max, ((int32_t *) dst->op_params) + 1, sizeof(float)); + + if (!ggml_is_contiguous(src0)) { + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel = backend_ctx->clamp.kernel_clamp_nc; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &min)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &max)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb3)); + + const int nth = 64; + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return; + } + + cl_kernel kernel = backend_ctx->clamp.kernel_clamp; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &min)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &max)); + + const int64_t n = ggml_nelements(dst); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/concat.cpp b/ggml/src/ggml-opencl/ops/concat.cpp new file mode 100644 index 000000000000..025712231375 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/concat.cpp @@ -0,0 +1,142 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_concat(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // concat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "concat.cl.h" + }; +#else + const std::string kernel_src = read_file("concat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->concat.kernel_concat_b1 = clCreateKernel(prog, "kernel_concat_b1", &err), err)); + CL_CHECK((backend_ctx->concat.kernel_concat_b2 = clCreateKernel(prog, "kernel_concat_b2", &err), err)); + CL_CHECK((backend_ctx->concat.kernel_concat_b4 = clCreateKernel(prog, "kernel_concat_b4", &err), err)); + CL_CHECK((backend_ctx->concat.kernel_concat_b8 = clCreateKernel(prog, "kernel_concat_b8", &err), err)); + CL_CHECK((backend_ctx->concat.kernel_concat_b4_pack = clCreateKernel(prog, "kernel_concat_b4_pack", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +} + +void ggml_cl_concat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(src0->type == src1->type); + GGML_ASSERT(src0->type == dst->type); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb10 = src1->nb[0]; + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + const int ne2 = dst->ne[2]; + const int ne3 = dst->ne[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + const cl_int dim = ((const int32_t *) dst->op_params)[0]; + GGML_ASSERT(dim >= 0 && dim <= 3); + + int nth = MIN(64, ne0); + + const size_t ts = ggml_type_size(dst->type); + // the pack kernel copies 4-byte elements, so it is only valid for those. + const bool concat_pack = (dim == 0 && ne0 < 32 && ts == 4); + cl_kernel kernel; + if (concat_pack) { + kernel = backend_ctx->concat.kernel_concat_b4_pack; + } else { + switch (ts) { + case 1: kernel = backend_ctx->concat.kernel_concat_b1; break; + case 2: kernel = backend_ctx->concat.kernel_concat_b2; break; + case 4: kernel = backend_ctx->concat.kernel_concat_b4; break; + case 8: kernel = backend_ctx->concat.kernel_concat_b8; break; + default: GGML_ABORT("unsupported concat element size: %zu", ts); + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_int), &dim)); + + if (concat_pack) { + // packed kernel needs the dst dims to unflatten its 1-D row index. + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &ne3)); + + const int maxwg = (int)backend_ctx->get_kernel_workgroup_size(kernel); + const int base = MIN(64, maxwg); + const int tpr = MIN(ne0, base); // threads per row + const int rpw = MAX(1, base / tpr); // rows per workgroup + const int lsz = tpr * rpw; + const int nrows = ne1*ne2*ne3; + const int nwg = (nrows + rpw - 1) / rpw; + size_t global_work_size[] = {(size_t)nwg*lsz, 1, 1}; + size_t local_work_size[] = {(size_t)lsz, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); + } else { + size_t global_work_size[] = {(size_t)ne1*nth, (size_t)ne2, (size_t)ne3}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/cont.cpp b/ggml/src/ggml-opencl/ops/cont.cpp new file mode 100644 index 000000000000..a229909e9d2d --- /dev/null +++ b/ggml/src/ggml-opencl/ops/cont.cpp @@ -0,0 +1,12 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_cont(ggml_backend_opencl_context * backend_ctx) { + GGML_UNUSED(backend_ctx); +} + +void ggml_cl_cont( + ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + ggml_cl_dup(backend, src0, src1, dst); +} diff --git a/ggml/src/ggml-opencl/ops/conv_2d.cpp b/ggml/src/ggml-opencl/ops/conv_2d.cpp new file mode 100644 index 000000000000..afd315414d0d --- /dev/null +++ b/ggml/src/ggml-opencl/ops/conv_2d.cpp @@ -0,0 +1,162 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_conv_2d(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // conv2d + { + #ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "conv2d.cl.h" + }; + const std::string kernel_src_f16_f32 { + #include "conv2d_f16_f32.cl.h" + }; + #else + const std::string kernel_src = read_file("conv2d.cl"); + const std::string kernel_src_f16_f32 = read_file("conv2d_f16_f32.cl"); + #endif + if (!kernel_src.empty()) { + cl_program prog_f16 = + build_program_from_source(backend_ctx, kernel_src.c_str(), (std::string(compile_opts) + " -DUSE_FP16=1").c_str()); + CL_CHECK((backend_ctx->conv_2d.kernel_conv_2d_f16 = clCreateKernel(prog_f16, "kernel_conv_2d", &err), err)); + CL_CHECK(clReleaseProgram(prog_f16)); + GGML_LOG_CONT("."); + cl_program prog_f32 = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->conv_2d.kernel_conv_2d_f32 = clCreateKernel(prog_f32, "kernel_conv_2d", &err), err)); + CL_CHECK(clReleaseProgram(prog_f32)); + GGML_LOG_CONT("."); + } else { + GGML_LOG_WARN("ggml_opencl: conv2d kernel source not found or empty. This op will not be available.\n"); + backend_ctx->conv_2d.kernel_conv_2d_f16 = nullptr; + backend_ctx->conv_2d.kernel_conv_2d_f32 = nullptr; + } + if (!kernel_src_f16_f32.empty()) { + cl_program prog_f16_f32 = + build_program_from_source(backend_ctx, kernel_src_f16_f32.c_str(), compile_opts); + CL_CHECK((backend_ctx->conv_2d.kernel_conv_2d_f16_f32 = clCreateKernel(prog_f16_f32, "kernel_conv_2d", &err), err)); + CL_CHECK(clReleaseProgram(prog_f16_f32)); + GGML_LOG_CONT("."); + } else { + GGML_LOG_WARN("ggml_opencl: conv2d_f16_f32 kernel source not found or empty. This op will not be available.\n"); + backend_ctx->conv_2d.kernel_conv_2d_f16_f32 = nullptr; + } + } +} + +void ggml_cl_conv_2d(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_BINARY_OP_LOCALS; + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const cl_uint Cout = ne03; + const cl_uint Cin = ne02; + const cl_uint N = ne13; + const cl_uint KW = ne00; + const cl_uint KH = ne01; + const cl_uint W = ne10; + const cl_uint H = ne11; + const cl_uint OW = ne0; + const cl_uint OH = ne1; + + const cl_uint s0 = dst->op_params[0]; + const cl_uint s1 = dst->op_params[1]; + const cl_uint p0 = dst->op_params[2]; + const cl_uint p1 = dst->op_params[3]; + const cl_uint d0 = dst->op_params[4]; + const cl_uint d1 = dst->op_params[5]; + + const cl_uint cl_nb00 = nb00/ggml_type_size(src0->type); + const cl_uint cl_nb01 = nb01/ggml_type_size(src0->type); + const cl_uint cl_nb02 = nb02/ggml_type_size(src0->type); + const cl_uint cl_nb03 = nb03/ggml_type_size(src0->type); + const cl_uint cl_nb10 = nb10/ggml_type_size(src1->type); + const cl_uint cl_nb11 = nb11/ggml_type_size(src1->type); + const cl_uint cl_nb12 = nb12/ggml_type_size(src1->type); + const cl_uint cl_nb13 = nb13/ggml_type_size(src1->type); + const cl_uint cl_nb1 = nb1/ggml_type_size(dst->type); + const cl_uint cl_nb2 = nb2/ggml_type_size(dst->type); + const cl_uint cl_nb3 = nb3/ggml_type_size(dst->type); + + const int64_t NPQ = (int64_t)N * OW * OH; + + const uint32_t BS_K = 64; + const uint32_t BS_NPQ = 64; + const uint32_t BS_CRS = 16; + const uint32_t VEC_SIZE = 4; + + const uint32_t TS_K = 4; + const uint32_t TS_NPQ = 8; + + const uint32_t WG_K = BS_K / TS_K; + const uint32_t WG_NPQ = BS_NPQ / TS_NPQ; + + auto splitWork = [](uint32_t work_size, uint32_t block_size) { return (block_size + work_size - 1) / block_size; }; + const uint32_t NB_K = splitWork(Cout, BS_K); + const uint32_t NB_NPQ = splitWork(NPQ, BS_NPQ); + + cl_kernel kernel; + size_t shmem_size; + + if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F16) { + kernel = backend_ctx->conv_2d.kernel_conv_2d_f16; + shmem_size = (size_t)(BS_K * BS_CRS * sizeof(cl_half) + BS_CRS * (BS_NPQ / VEC_SIZE) * sizeof(cl_half4)); + } else if (src0->type == GGML_TYPE_F32 && src1->type == GGML_TYPE_F32) { + kernel = backend_ctx->conv_2d.kernel_conv_2d_f32; + shmem_size = (size_t)(BS_K * BS_CRS * sizeof(cl_float) + BS_CRS * (BS_NPQ / VEC_SIZE) * sizeof(cl_float4)); + } else if (src0->type == GGML_TYPE_F16 && src1->type == GGML_TYPE_F32) { + kernel = backend_ctx->conv_2d.kernel_conv_2d_f16_f32; + shmem_size = (size_t)(BS_K * BS_CRS * sizeof(cl_half) + BS_CRS * (BS_NPQ / VEC_SIZE) * sizeof(cl_float4)); + } else { + GGML_ASSERT(false && "Unsupported data type combination for conv2d"); + } + + cl_uint idx = 0; + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, idx++, shmem_size, NULL)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &Cout)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &Cin)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &N)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &KW)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &KH)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &W)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &OW)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &OH)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &s0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &s1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &p0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &p1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &d0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &d1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb00)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb01)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb02)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb03)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb10)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb11)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb12)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb13)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &cl_nb3)); + + size_t global_work_size[] = { (size_t)NB_K * WG_K, (size_t)NB_NPQ * WG_NPQ, 1 }; + size_t local_work_size[] = { (size_t)WG_K, (size_t)WG_NPQ, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/conv_2d_dw.cpp b/ggml/src/ggml-opencl/ops/conv_2d_dw.cpp new file mode 100644 index 000000000000..a4f12415feeb --- /dev/null +++ b/ggml/src/ggml-opencl/ops/conv_2d_dw.cpp @@ -0,0 +1,102 @@ +#include "../cl-common.h" + +void ggml_cl_load_kernels_conv_2d_dw(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "conv2_dw.cl.h" + }; +#else + const std::string kernel_src = read_file("conv2_dw.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->conv_2d_dw.kernel_conv2d_dw_f32_f32 = clCreateKernel(prog, "kernel_conv2d_dw_f32_f32", &err), err)); + CL_CHECK((backend_ctx->conv_2d_dw.kernel_conv2d_dwf16_f32 = clCreateKernel(prog, "kernel_conv2d_dwf16_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); +} + +void ggml_cl_conv2_dw(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_BINARY_OP_LOCALS; + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + const cl_long offset0 = extra0->offset + src0->view_offs; + const cl_long offset1 = extra1->offset + src1->view_offs; + const cl_long offsetd = extrad->offset + dst->view_offs; + + const cl_long C = ne12; + const cl_long N = ne13; + const cl_long KW = ne00; + const cl_long KH = ne01; + const cl_long W = ne10; + const cl_long H = ne11; + const cl_long OW = ne0; + const cl_long OH = ne1; + + const cl_int s0 = dst->op_params[0]; + const cl_int s1 = dst->op_params[1]; + const cl_int p0 = dst->op_params[2]; + const cl_int p1 = dst->op_params[3]; + const cl_int d0 = dst->op_params[4]; + const cl_int d1 = dst->op_params[5]; + + const cl_long cl_nb01 = nb01/ggml_type_size(src0->type); + const cl_long cl_nb03 = nb03/ggml_type_size(src0->type); + const cl_long cl_nb11 = nb11/ggml_type_size(src1->type); + const cl_long cl_nb12 = nb12/ggml_type_size(src1->type); + const cl_long cl_nb13 = nb13/ggml_type_size(src1->type); + const cl_long cl_nb1 = nb1/ggml_type_size(dst->type); + const cl_long cl_nb2 = nb2/ggml_type_size(dst->type); + const cl_long cl_nb3 = nb3/ggml_type_size(dst->type); + + cl_kernel kernel; + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->conv_2d_dw.kernel_conv2d_dw_f32_f32; + } else if (src0->type == GGML_TYPE_F16) { + kernel = backend_ctx->conv_2d_dw.kernel_conv2d_dwf16_f32; + } else { + GGML_ASSERT(false && "Unsupported data type combination for conv2_dw"); + } + + cl_uint idx = 0; + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &offset0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &offset1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &C)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &N)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &KW)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &KH)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &W)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &H)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &OW)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &OH)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &s0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &s1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &p0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &p1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &d0)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_int), &d1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb01)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb03)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb11)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb12)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb13)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_long), &cl_nb3)); + + const size_t total = (size_t) N * C * OH * OW; + const size_t local_size = MIN((size_t) 256, backend_ctx->get_kernel_workgroup_size(kernel)); + size_t global_work_size[] = { CEIL_DIV(total, local_size) * local_size }; + size_t local_work_size[] = { local_size }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/cpy.cpp b/ggml/src/ggml-opencl/ops/cpy.cpp new file mode 100644 index 000000000000..988c69942269 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/cpy.cpp @@ -0,0 +1,191 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_cpy(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // cpy + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "cpy.cl.h" + }; +#else + const std::string kernel_src = read_file("cpy.cl"); +#endif + const bool no_cpy_pack = backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), + no_cpy_pack ? compile_opts + " -DGGML_CL_NO_CPY_PACK" : compile_opts); + + CL_CHECK((backend_ctx->cpy.kernel_cpy_f16_f16 = clCreateKernel(prog, "kernel_cpy_f16_f16", &err), err)); + CL_CHECK((backend_ctx->cpy.kernel_cpy_f16_f32 = clCreateKernel(prog, "kernel_cpy_f16_f32", &err), err)); + CL_CHECK((backend_ctx->cpy.kernel_cpy_f32_f16 = clCreateKernel(prog, "kernel_cpy_f32_f16", &err), err)); + CL_CHECK((backend_ctx->cpy.kernel_cpy_f32_f32 = clCreateKernel(prog, "kernel_cpy_f32_f32", &err), err)); + if (!no_cpy_pack) { + CL_CHECK((backend_ctx->cpy.kernel_cpy_f32_f32_pack = clCreateKernel(prog, "kernel_cpy_f32_f32_pack", &err), err)); + } + { // optional: without it ggml_cl_cpy keeps the row-mapped kernel + cl_int err_flat = CL_SUCCESS; + cl_kernel k = clCreateKernel(prog, "kernel_cpy_f32_f32_flat", &err_flat); + if (err_flat == CL_SUCCESS) { + backend_ctx->cpy.kernel_cpy_f32_f32_flat = k; + } + } + CL_CHECK((backend_ctx->cpy.kernel_cpy_i32_i32 = clCreateKernel(prog, "kernel_cpy_i32_i32", &err), err)); + CL_CHECK((backend_ctx->cpy.kernel_cpy_i32_f32 = clCreateKernel(prog, "kernel_cpy_i32_f32", &err), err)); + CL_CHECK((backend_ctx->cpy.kernel_cpy_f32_i32 = clCreateKernel(prog, "kernel_cpy_f32_i32", &err), err)); + GGML_LOG_CONT("."); + } + +} + +void ggml_cl_cpy(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + + // GGML_OP_CPY happens between src0 and src1. + // GGML_OP_DUP and GGML_OP_CONT happen between src0 and dst. + UNUSED(dst); + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + + const enum ggml_type src0t = src0->type; + const enum ggml_type src1t = src1->type; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + + // A contiguous f32 -> f32 copy is a linear move. The kernel below maps one workgroup to + // each row, so a tensor with few long rows runs on a single compute unit; dispatch those + // over the whole device instead. GGML_OPENCL_CPY_FLAT=0 restores the row-mapped path. + static const bool cpy_flat_on = []{ + const char * e = getenv("GGML_OPENCL_CPY_FLAT"); + return !(e && e[0] == '0'); + }(); + if (cpy_flat_on && backend_ctx->cpy.kernel_cpy_f32_f32_flat != nullptr && + src0t == GGML_TYPE_F32 && src1t == GGML_TYPE_F32 && + ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && + ggml_nelements(src0) == ggml_nelements(src1)) { + cl_kernel k = backend_ctx->cpy.kernel_cpy_f32_f32_flat; + const cl_ulong nelem = (cl_ulong) ggml_nelements(src0); + const cl_ulong n4 = nelem / 4; + + CL_CHECK(clSetKernelArg(k, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(k, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(k, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(k, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(k, 4, sizeof(cl_ulong), &nelem)); + CL_CHECK(clSetKernelArg(k, 5, sizeof(cl_ulong), &n4)); + + // one work item per float4, plus one for the trailing scalars + const size_t items = (size_t) n4 + ((nelem % 4) ? 1 : 0); + const size_t lsz = MIN((size_t) 64, backend_ctx->max_workgroup_size); + size_t global_work_size[] = { ((items + lsz - 1) / lsz) * lsz, 1, 1 }; + size_t local_work_size[] = { lsz, 1, 1 }; + + backend_ctx->enqueue_ndrange_kernel(k, 1, global_work_size, local_work_size, src1); + return; + } + + cl_kernel kernel; + + switch (src0t) { + case GGML_TYPE_F32: + switch (src1t) { + case GGML_TYPE_I32: + kernel = backend_ctx->cpy.kernel_cpy_f32_i32; + break; + case GGML_TYPE_F16: + kernel = backend_ctx->cpy.kernel_cpy_f32_f16; + break; + case GGML_TYPE_F32: + kernel = (ne00 < 32 && backend_ctx->cpy.kernel_cpy_f32_f32_pack) + ? backend_ctx->cpy.kernel_cpy_f32_f32_pack + : backend_ctx->cpy.kernel_cpy_f32_f32; + break; + default: + GGML_ASSERT(false && "not implemented"); + } + break; + case GGML_TYPE_F16: + switch (src1t) { + case GGML_TYPE_F16: + kernel = backend_ctx->cpy.kernel_cpy_f16_f16; + break; + case GGML_TYPE_F32: + kernel = backend_ctx->cpy.kernel_cpy_f16_f32; + break; + default: + GGML_ASSERT(false && "not implemented"); + } + break; + case GGML_TYPE_I32: + switch (src1t) { + case GGML_TYPE_F32: + kernel = backend_ctx->cpy.kernel_cpy_i32_f32; + break; + case GGML_TYPE_I32: + kernel = backend_ctx->cpy.kernel_cpy_i32_i32; + break; + default: + GGML_ASSERT(false && "not implemented"); + } + break; + default: + GGML_ASSERT(false && "not implemented"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); + + if (kernel == backend_ctx->cpy.kernel_cpy_f32_f32_pack) { + const int maxwg = (int)backend_ctx->get_kernel_workgroup_size(kernel); + const int base = MIN(64, maxwg); + const int tpr = MIN(ne00, base); // threads per row + const int rpw = MAX(1, base / tpr); // rows per workgroup + const int lsz = tpr * rpw; // <= base <= maxwg + const int nrows = ne01*ne02*ne03; + const int nwg = (nrows + rpw - 1) / rpw; + + size_t global_work_size[] = {(size_t)nwg*lsz, 1, 1}; + size_t local_work_size[] = {(size_t)lsz, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, src1); + } else { + const int nth = MIN(64, ne00); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, src1); + } +} diff --git a/ggml/src/ggml-opencl/ops/cumsum.cpp b/ggml/src/ggml-opencl/ops/cumsum.cpp new file mode 100644 index 000000000000..fe3e54e8965c --- /dev/null +++ b/ggml/src/ggml-opencl/ops/cumsum.cpp @@ -0,0 +1,136 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_cumsum(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // cumsum + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "cumsum.cl.h" + }; +#else + const std::string kernel_src = read_file("cumsum.cl"); +#endif + cl_program prog; + prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->cumsum.kernel_cumsum_blk = clCreateKernel(prog, "kernel_cumsum_blk", &err), err)); + CL_CHECK((backend_ctx->cumsum.kernel_cumsum_add = clCreateKernel(prog, "kernel_cumsum_add", &err), err)); + GGML_LOG_CONT("."); + CL_CHECK(clReleaseProgram(prog)); + } +} + +void ggml_cl_cumsum(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_UNUSED(src1); + + GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type)); + GGML_ASSERT(ggml_is_contiguous(src0)); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + + cl_kernel kernel = backend_ctx->cumsum.kernel_cumsum_blk; + + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + int nth = 1; + while (nth < ne00 && 2*nth <= max_workgroup_size) { + nth *= 2; + } + + GGML_ASSERT(ne00 <= nth*nth); + + const int net0 = CEIL_DIV(ne00, nth); + const int net1 = ne01; + const int net2 = ne02; + const int net3 = ne03; + + const cl_ulong nbt0 = sizeof(float); + const cl_ulong nbt1 = net0*nbt0; + const cl_ulong nbt2 = net1*nbt1; + const cl_ulong nbt3 = net2*nbt2; + + static ggml_cl_buffer tmp_buffer; + tmp_buffer.allocate(backend_ctx->context, net0*ne01*ne02*ne03*sizeof(float)); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &tmp_buffer.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &net0)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &net1)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &net2)); + + size_t global_work_size[] = { (size_t)(nth*net0*ne01), (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = { (size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + if(ne00 > nth) { + // if a single workgroup cannot handle an entire row, each workgroup + // computes a partial sum and stores to dst, tmp_buffer contains the sum + // of the each workgroup; cumsum this buffer and add to the partial sums in dst + cl_ulong offsett = 0; + kernel = backend_ctx->cumsum.kernel_cumsum_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &tmp_buffer.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsett)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &tmp_buffer.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &tmp_buffer.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsett)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &net0)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nbt0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nbt1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nbt2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nbt3)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &net0)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &net1)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &net2)); + + size_t global_work_size_1[] = { (size_t)net1*nth, (size_t)net2, (size_t)net3}; + size_t local_work_size_1[] = { (size_t)nth, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size_1, local_work_size_1, dst); + + kernel = backend_ctx->cumsum.kernel_cumsum_add; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &tmp_buffer.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &nbt0)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &nbt1)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &nbt2)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &nbt3)); + + size_t global_work_size_2[] = { (size_t)(nth*net0*ne01), (size_t)ne02, (size_t)ne03}; + size_t local_work_size_2[] = { (size_t)nth, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size_2, local_work_size_2, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/diag.cpp b/ggml/src/ggml-opencl/ops/diag.cpp new file mode 100644 index 000000000000..35dcc125e0e0 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/diag.cpp @@ -0,0 +1,66 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_diag(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // diag + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "diag.cl.h" + }; +#else + const std::string kernel_src = read_file("diag.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->diag.kernel_diag_f32 = clCreateKernel(prog, "kernel_diag_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_diag(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + cl_kernel kernel = backend_ctx->diag.kernel_diag_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne1*nth, (size_t)ne2, (size_t)ne3}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/div.cpp b/ggml/src/ggml-opencl/ops/div.cpp new file mode 100644 index 000000000000..64babf2a37a0 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/div.cpp @@ -0,0 +1,152 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_div(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string opencl_c_std = "CL" + std::to_string(backend_ctx->opencl_c_version.major) + + "." + std::to_string(backend_ctx->opencl_c_version.minor); + + // div + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "div.cl.h" + }; +#else + const std::string kernel_src = read_file("div.cl"); +#endif + std::string compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable -cl-finite-math-only "; + + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->div.kernel_div = clCreateKernel(prog, "kernel_div", &err), err)); + CL_CHECK((backend_ctx->div.kernel_div_row = clCreateKernel(prog, "kernel_div_row", &err), err)); + CL_CHECK((backend_ctx->div.kernel_div_f16 = clCreateKernel(prog, "kernel_div_f16", &err), err)); + CL_CHECK((backend_ctx->div.kernel_div_row_f16 = clCreateKernel(prog, "kernel_div_row_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_div(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT(src0->type == src1->type); + GGML_ASSERT(src0->type == dst->type); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne10 = src1->ne[0]; + const int ne11 = src1->ne[1]; + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; + + const cl_ulong nb10 = src1->nb[0]; + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const int ne0 = dst->ne[0]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + bool bcast_row = false; + cl_kernel kernel; + + if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) { + GGML_ASSERT(ggml_is_contiguous(src0)); + + // src1 is a row + GGML_ASSERT(ne11 == 1); + + bcast_row = true; + int ne = ne00 / 4; + + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->div.kernel_div_row; + } else { + kernel = backend_ctx->div.kernel_div_row_f16; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->div.kernel_div; + } else { + kernel = backend_ctx->div.kernel_div_f16; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); + } + + if (bcast_row) { + int n = ggml_nelements(dst)/4; + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else { + unsigned int nth = MIN(64, ne0); + size_t global_work_size[] = {ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/dsv4_hc.cpp b/ggml/src/ggml-opencl/ops/dsv4_hc.cpp new file mode 100644 index 000000000000..930db3c29abb --- /dev/null +++ b/ggml/src/ggml-opencl/ops/dsv4_hc.cpp @@ -0,0 +1,66 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_dsv4_hc(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "dsv4_hc.cl.h" + }; +#else + const std::string kernel_src = read_file("dsv4_hc.cl"); +#endif + for (int i = 0; i < 2; ++i) { + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + (i == 0 ? " -DHC_VEC=1" : " -DHC_VEC=4")); + if (i == 0) { + CL_CHECK((backend_ctx->dsv4_hc.kernel_dsv4_hc_pre = clCreateKernel(prog, "kernel_dsv4_hc_pre", &err), err)); + backend_ctx->dsv4_hc.local_dsv4_hc_pre = MIN((size_t) 64, backend_ctx->get_kernel_workgroup_size(backend_ctx->dsv4_hc.kernel_dsv4_hc_pre)); + } + CL_CHECK((backend_ctx->dsv4_hc.kernel_dsv4_hc_post[i] = clCreateKernel(prog, "kernel_dsv4_hc_post", &err), err)); + backend_ctx->dsv4_hc.local_dsv4_hc_post[i] = MIN((size_t) 64, backend_ctx->get_kernel_workgroup_size(backend_ctx->dsv4_hc.kernel_dsv4_hc_post[i])); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); +} + +void ggml_cl_dsv4_hc(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const bool pre = dst->op == GGML_OP_DSV4_HC_PRE; + const bool vec = !pre && src0->ne[0] % 4 == 0 && src0->nb[0] == sizeof(float) && src1->nb[0] == sizeof(float); + cl_kernel kernel = pre ? backend_ctx->dsv4_hc.kernel_dsv4_hc_pre : backend_ctx->dsv4_hc.kernel_dsv4_hc_post[vec]; + + cl_uint arg = 0; + for (int i = 0; i < (pre ? 2 : 4); ++i) { + const ggml_tensor * src = dst->src[i]; + auto * extra = src ? (ggml_tensor_extra_cl *) src->extra : nullptr; + const cl_mem buffer = extra ? extra->data_device : nullptr; + const cl_ulong offset = src ? extra->offset + src->view_offs : 0; + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &buffer)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &offset)); + for (int j = 0; j < 3; ++j) { + const cl_ulong stride = src ? src->nb[j] : 0; + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &stride)); + } + } + + auto * extra = (ggml_tensor_extra_cl *) dst->extra; + const cl_ulong offset = extra->offset + dst->view_offs; + const cl_long n_embd = src0->ne[0]; + const cl_long n_hc = pre ? src0->ne[1] : src1->ne[1]; + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &offset)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_long), &n_embd)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_long), &n_hc)); + if (pre) { + const float scale = ggml_get_op_params_f32(dst, 0); + const cl_int gated = ggml_get_op_params_i32(dst, 1); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_int), &gated)); + } + + const size_t n_work = (size_t) n_embd / (vec ? 4 : 1); + size_t local_work_size[] = { pre ? backend_ctx->dsv4_hc.local_dsv4_hc_pre : backend_ctx->dsv4_hc.local_dsv4_hc_post[vec], 1, 1 }; + size_t global_work_size[] = { CEIL_DIV(n_work, local_work_size[0]) * local_work_size[0], (size_t) dst->ne[1], (size_t) dst->ne[2] }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/dup.cpp b/ggml/src/ggml-opencl/ops/dup.cpp new file mode 100644 index 000000000000..9db18a36b448 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/dup.cpp @@ -0,0 +1,12 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_dup(ggml_backend_opencl_context * backend_ctx) { + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + GGML_UNUSED(compile_opts); +} + +void ggml_cl_dup(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_cl_cpy(backend, src0, dst, nullptr); + UNUSED(src1); +} diff --git a/ggml/src/ggml-opencl/ops/exp.cpp b/ggml/src/ggml-opencl/ops/exp.cpp new file mode 100644 index 000000000000..759ef10ecd18 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/exp.cpp @@ -0,0 +1,109 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_exp(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // exp + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "exp.cl.h" + }; +#else + const std::string kernel_src = read_file("exp.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->exp.kernel_exp_f32 = clCreateKernel(prog, "kernel_exp_f32", &err), err)); + CL_CHECK((backend_ctx->exp.kernel_exp_f32_4 = clCreateKernel(prog, "kernel_exp_f32_4", &err), err)); + CL_CHECK((backend_ctx->exp.kernel_exp_f32_nc = clCreateKernel(prog, "kernel_exp_f32_nc", &err), err)); + CL_CHECK((backend_ctx->exp.kernel_exp_f16 = clCreateKernel(prog, "kernel_exp_f16", &err), err)); + CL_CHECK((backend_ctx->exp.kernel_exp_f16_4 = clCreateKernel(prog, "kernel_exp_f16_4", &err), err)); + CL_CHECK((backend_ctx->exp.kernel_exp_f16_nc = clCreateKernel(prog, "kernel_exp_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_exp(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + cl_kernel kernel; + + if (ggml_is_contiguous(src0)) { + // Handle contiguous input + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->exp.kernel_exp_f32_4; + } else { + kernel = backend_ctx->exp.kernel_exp_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->exp.kernel_exp_f32; + } else { + kernel = backend_ctx->exp.kernel_exp_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &n)); + + size_t global_work_size[] = {(size_t)CEIL_DIV(n, 64)*64, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else { + // Handle non-contiguous input + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->exp.kernel_exp_f32_nc; + } else { + kernel = backend_ctx->exp.kernel_exp_f16_nc; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/expm1.cpp b/ggml/src/ggml-opencl/ops/expm1.cpp new file mode 100644 index 000000000000..1dd208b75959 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/expm1.cpp @@ -0,0 +1,123 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_expm1(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // expm1 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "expm1.cl.h" + }; +#else + const std::string kernel_src = read_file("expm1.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->expm1.kernel_expm1_f32 = clCreateKernel(prog, "kernel_expm1_f32", &err), err)); + CL_CHECK((backend_ctx->expm1.kernel_expm1_f32_4 = clCreateKernel(prog, "kernel_expm1_f32_4", &err), err)); + CL_CHECK((backend_ctx->expm1.kernel_expm1_f32_nc = clCreateKernel(prog, "kernel_expm1_f32_nc", &err), err)); + CL_CHECK((backend_ctx->expm1.kernel_expm1_f16 = clCreateKernel(prog, "kernel_expm1_f16", &err), err)); + CL_CHECK((backend_ctx->expm1.kernel_expm1_f16_4 = clCreateKernel(prog, "kernel_expm1_f16_4", &err), err)); + CL_CHECK((backend_ctx->expm1.kernel_expm1_f16_nc = clCreateKernel(prog, "kernel_expm1_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_expm1(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel; + + if (ggml_is_contiguous(src0)) { + // Handle contiguous input + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->expm1.kernel_expm1_f32_4; + } else { + kernel = backend_ctx->expm1.kernel_expm1_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->expm1.kernel_expm1_f32; + } else { + kernel = backend_ctx->expm1.kernel_expm1_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); + } else { + // Handle non-contiguous input + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->expm1.kernel_expm1_f32_nc; + } else { + kernel = backend_ctx->expm1.kernel_expm1_f16_nc; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/fill.cpp b/ggml/src/ggml-opencl/ops/fill.cpp new file mode 100644 index 000000000000..f59719c075f4 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/fill.cpp @@ -0,0 +1,54 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_fill(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // fill + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "fill.cl.h" + }; +#else + const std::string kernel_src = read_file("fill.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->fill.kernel_fill = clCreateKernel(prog, "kernel_fill_f32", &err), err)); + GGML_LOG_CONT("."); + + CL_CHECK(clReleaseProgram(prog)); + } +} + +void ggml_cl_fill(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src0); + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + float v = 0.0f; + memcpy(&v, ((int32_t *) dst->op_params), sizeof(float)); + + const int64_t n = ggml_nelements(dst); + + cl_kernel kernel = backend_ctx->fill.kernel_fill; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(float), &v)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(float), &n)); + + size_t local_work_size[1] = { 256 }; + size_t global_work_size[1] = { ((size_t)n + local_work_size[0] - 1) / local_work_size[0] * local_work_size[0] }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/flash_attn.cpp b/ggml/src/ggml-opencl/ops/flash_attn.cpp new file mode 100644 index 000000000000..ac533f776ec5 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/flash_attn.cpp @@ -0,0 +1,4474 @@ +#include "../cl-common.h" +#include "../ops.h" + +struct ggml_cl_flash_attn_temp_buffer { + cl_mem data = nullptr; + + ~ggml_cl_flash_attn_temp_buffer() { + if (data != nullptr) { + CL_CHECK(clReleaseMemObject(data)); + data = nullptr; + } + } +}; + +void ggml_cl_load_kernels_flash_attn(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno xmem SDPA + if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "sdpa_xmem_f32_f16_os8.cl.h" + }; +#else + const std::string kernel_src = read_file("sdpa_xmem_f32_f16_os8.cl"); +#endif + cl_program program = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + auto & xmem_attn = backend_ctx->adreno_xmem_attn; + CL_CHECK((xmem_attn.kernel_q_f32_to_img_scaled = + clCreateKernel(program, "adreno_xmem_attn_q_f32_to_img_scaled", &err), err)); + CL_CHECK((xmem_attn.kernel_kv_f32_to_img_gqa = + clCreateKernel(program, "adreno_xmem_attn_kv_f32_to_img_gqa", &err), err)); + CL_CHECK((xmem_attn.kernel_kv_f16_to_img_gqa = + clCreateKernel(program, "adreno_xmem_attn_kv_f16_to_img_gqa", &err), err)); + CL_CHECK((xmem_attn.kernel_img_to_f32 = + clCreateKernel(program, "adreno_xmem_attn_img_to_f32", &err), err)); + CL_CHECK((xmem_attn.kernel_k_gather = + clCreateKernel(program, "adreno_xmem_attn_k_gather", &err), err)); + CL_CHECK((xmem_attn.kernel_pack_k = + clCreateKernel(program, "adreno_xmem_attn_pack_k", &err), err)); + CL_CHECK((xmem_attn.kernel_qk_gemm = + clCreateKernel(program, "adreno_xmem_attn_qk_gemm", &err), err)); + CL_CHECK((xmem_attn.kernel_softmax_reduce_basic = + clCreateKernel(program, "adreno_xmem_attn_softmax_reduce_basic", &err), err)); + CL_CHECK((xmem_attn.kernel_softmax_apply_basic = + clCreateKernel(program, "adreno_xmem_attn_softmax_apply_basic", &err), err)); + CL_CHECK((xmem_attn.kernel_mask_scores = + clCreateKernel(program, "adreno_xmem_attn_mask_scores", &err), err)); + CL_CHECK((xmem_attn.kernel_pack_v = + clCreateKernel(program, "adreno_xmem_attn_pack_v", &err), err)); + CL_CHECK((xmem_attn.kernel_pv_gemm = + clCreateKernel(program, "adreno_xmem_attn_pv_gemm", &err), err)); + CL_CHECK(clReleaseProgram(program)); + xmem_attn.compiled = true; + GGML_LOG_CONT("."); + } + + // repack + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "flash_attn_repack.cl.h" + }; +#else + const std::string kernel_src = read_file("flash_attn_repack.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->fa.kernel_repack_q_for_wmm = clCreateKernel(prog, "kernel_repack_q_for_wmm", &err), err)); + CL_CHECK((backend_ctx->fa.kernel_repack_k_for_wmm = clCreateKernel(prog, "kernel_repack_k_for_wmm", &err), err)); + CL_CHECK((backend_ctx->fa.kernel_repack_v_for_wmm = clCreateKernel(prog, "kernel_repack_v_for_wmm", &err), err)); + CL_CHECK((backend_ctx->fa.kernel_repack_mask_for_wmm = clCreateKernel(prog, "kernel_repack_mask_for_wmm", &err), err)); + GGML_LOG_CONT("."); + } + + // kernel_flash_attn_f32_f16_bin + { + auto opencl_c_std = + std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + std::to_string(backend_ctx->opencl_c_version.minor); + std::string bin_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -cl-fast-relaxed-math"; + + size_t bin_size = 0; + backend_ctx->fa.kernel_flash_attn_f32_f16_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("flash_attn_f32_f16_wmm", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, bin_compile_opts, bin_size); + + CL_CHECK((backend_ctx->fa.kernel_flash_attn_f32_f16_bin = clCreateKernel(prog, "flash_attn_f32_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string rows_src { + #include "flash_attn_q8_rows.cl.h" + }; + const std::string kq_src { + #include "mul_mm_q8_kq_p8.cl.h" + }; +#else + const std::string rows_src = read_file("flash_attn_q8_rows.cl"); + const std::string kq_src = read_file("mul_mm_q8_kq_p8.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, rows_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->fa.kernel_fa_q8_rows_f16 = clCreateKernel(prog, "kernel_fa_q8_rows_f16", &err), err)); + CL_CHECK((backend_ctx->fa.kernel_fa_q8_rows_f32 = clCreateKernel(prog, "kernel_fa_q8_rows_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + prog = build_program_from_source(backend_ctx, kq_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->fa.kernel_mul_mm_q8_kq_p8 = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } + + // mul_mm_q8_kq_p8_dk512 + if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q8_kq_p8_dk512.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q8_kq_p8_dk512.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts, /*fatal=*/false); + if (prog != nullptr) { + cl_kernel kernel = clCreateKernel(prog, "kernel_mul_mm_q8_kq_p8_dk512", &err); + CL_CHECK(clReleaseProgram(prog)); + if (err == CL_SUCCESS) { + backend_ctx->fa.kernel_mul_mm_q8_kq_p8_dk512 = kernel; + } + } + GGML_LOG_CONT("."); + } + + // mul_mm_f16_f32_kq_p8 + if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_f16_f32_kq_p8.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_f16_f32_kq_p8.cl"); +#endif + cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), + compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->fa.kernel_mul_mm_f16_f32_kq_p8 = clCreateKernel(prog, "mul_mm_f16_f32_kq_p8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } + + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "flash_attn_pv_direct.cl.h" + }; +#else + const std::string kernel_src = read_file("flash_attn_pv_direct.cl"); +#endif + cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), + compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->fa.kernel_fa_kqv_direct_f16 = clCreateKernel(prog, "kernel_fa_kqv_direct_f16", &err), err)); + CL_CHECK((backend_ctx->fa.kernel_fa_kqv_direct_reduce = clCreateKernel(prog, "kernel_fa_kqv_direct_reduce", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } + + if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO && backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q8_f32_kqv.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q8_f32_kqv.cl"); +#endif + cl_program prog = build_program_from_source_ex(backend_ctx->context, backend_ctx->device, kernel_src.c_str(), + compile_opts, /*fatal=*/false); + if (prog != nullptr) { + CL_CHECK((backend_ctx->fa.kernel_mul_mm_q8_f32_kqv = clCreateKernel(prog, "kernel_mul_mm_q8_f32_kqv", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + // decomposed FA softmax and fixup + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "softmax_4_f16.cl.h" + }; +#else + const std::string kernel_src = read_file("softmax_4_f16.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->fa.kernel_fa_decompose_soft_max_4_f16 = clCreateKernel(prog, "kernel_fa_decompose_soft_max_4_f16", &err), err)); + CL_CHECK((backend_ctx->fa.kernel_fa_decompose_scale_rows_f32 = clCreateKernel(prog, "kernel_fa_decompose_scale_rows_f32", &err), err)); + CL_CHECK((backend_ctx->fa.kernel_fa_p8_fixup = clCreateKernel(prog, "kernel_fa_p8_fixup", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + GGML_UNUSED(backend_ctx); + GGML_UNUSED(err); + GGML_UNUSED(compile_opts); +} + +bool use_fa_bin_kernels_prefill( + const ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * q, const ggml_tensor * k, const ggml_tensor * v) { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (backend_ctx->fa.kernel_flash_attn_f32_f16_bin == nullptr) { + return false; + } + + const bool is_mixed = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16; + const bool is_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0; + + const int n_q = q->ne[1]; + const int dk = q->ne[0]; + const int dv = v->ne[0]; + + // do not choose bin FA kernels to avoid repacking the KV cache for small + // verify batches on X2 + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && is_mixed && + (dk == 256 || dk == 512) && n_q <= 4) { + return false; + } + + constexpr bool prefill_only = true; + + // The repacked Q/K/V are 3D images: Q {n_q, n_batch*n_head, dk/4}, K {dk, n_kv/4, n_batch*n_head_kv}, + // V {n_kv, dv/4, n_batch*n_head_kv}. Past the device's 3D image limits clCreateImage fails and the + // call asserts (X2-90: V is n_kv wide, so any prefill past ~16k tokens of context), so decline those shapes. + const size_t n_kv = (size_t) k->ne[1]; + const size_t n_bh = (size_t) q->ne[3] * (size_t) q->ne[2]; + const size_t n_bhkv = (size_t) q->ne[3] * (size_t) k->ne[2]; + if ((size_t) n_q > backend_ctx->image3d_max_width || n_bh > backend_ctx->image3d_max_height || + (size_t) dk / 4 > backend_ctx->image3d_max_depth || + (size_t) dk > backend_ctx->image3d_max_width || (n_kv + 3) / 4 > backend_ctx->image3d_max_height || + n_kv > backend_ctx->image3d_max_width || (size_t) dv / 4 > backend_ctx->image3d_max_height || + n_bhkv > backend_ctx->image3d_max_depth) { + return false; + } + + // q8_0 K/V at DK=512 gives wrong results here when V differs from K (f16 K/V is correct). + // Decline it, as this backend does without the kernel library. + if (is_q8_0 && dk == 512) { + return false; + } + + return (backend_ctx->gpu_family == GPU_FAMILY::ADRENO && + (is_mixed || is_q8_0) && (dk == dv) + && (dk == 64 || dk == 128 || dk == 256 || dk == 512) + && (!prefill_only || n_q != 1)); +#else + GGML_UNUSED(backend_ctx); + GGML_UNUSED(q); + GGML_UNUSED(k); + GGML_UNUSED(v); + return false; +#endif +} + +// FA per-(dk,dv) tile tuning table + GGML_OPENCL_FA_TUNE override parsing. +#include "../fa_tune.h" + +// FA variant key for the per-(dk,dv,variant) lazy compile cache. +// Kernel built on first dispatch to reduce kernel loading time. +// NB - a warmup run is recommended to get all necessary FA variants compiled +// before actual runs. +enum ggml_opencl_fa_variant { + FA_VARIANT_PRE = 0, // prepass kernels (kv_pad, mask_pad, blk) + FA_VARIANT_F16 = 1, + FA_VARIANT_F32 = 2, + FA_VARIANT_F32_F16 = 3, + FA_VARIANT_Q8_0 = 4, + FA_VARIANT_Q4_0 = 5, + FA_VARIANT_F32_F16_SPLIT = 6, + FA_VARIANT_Q8_0_SPLIT = 7, + FA_VARIANT_Q4_0_SPLIT = 8, +}; + +static std::string ggml_opencl_fa_kernel_src(ggml_opencl_fa_variant v) { +#ifdef GGML_OPENCL_EMBED_KERNELS + switch (v) { + case FA_VARIANT_F16: + return std::string{ + #include "flash_attn_f16.cl.h" + }; + case FA_VARIANT_F32: + return std::string{ + #include "flash_attn_f32.cl.h" + }; + case FA_VARIANT_F32_F16: + case FA_VARIANT_F32_F16_SPLIT: + return std::string{ + #include "flash_attn_f32_f16.cl.h" + }; + case FA_VARIANT_PRE: + return std::string{ + #include "flash_attn_pre_f16.cl.h" + }; + case FA_VARIANT_Q8_0: + case FA_VARIANT_Q8_0_SPLIT: + return std::string{ + #include "flash_attn_f32_q8_0.cl.h" + }; + case FA_VARIANT_Q4_0: + case FA_VARIANT_Q4_0_SPLIT: + return std::string{ + #include "flash_attn_f32_q4_0.cl.h" + }; + } + return {}; +#else + switch (v) { + case FA_VARIANT_F16: return read_file("flash_attn_f16.cl"); + case FA_VARIANT_F32: return read_file("flash_attn_f32.cl"); + case FA_VARIANT_F32_F16: + case FA_VARIANT_F32_F16_SPLIT: return read_file("flash_attn_f32_f16.cl"); + case FA_VARIANT_PRE: return read_file("flash_attn_pre_f16.cl"); + case FA_VARIANT_Q8_0: + case FA_VARIANT_Q8_0_SPLIT: return read_file("flash_attn_f32_q8_0.cl"); + case FA_VARIANT_Q4_0: + case FA_VARIANT_Q4_0_SPLIT: return read_file("flash_attn_f32_q4_0.cl"); + } + return {}; +#endif +} + +static std::string ggml_opencl_fa_compile_opts(ggml_backend_opencl_context * backend_ctx, + const ggml_opencl_fa_dim * cfg, + ggml_opencl_fa_variant variant) { + std::string opts = backend_ctx->kernel_compile_opts + + " -D DK=" + std::to_string(cfg->dk) + + " -D DV=" + std::to_string(cfg->dv) + + " -D BLOCK_M=" + std::to_string(cfg->bm) + + " -D BLOCK_N=" + std::to_string(cfg->bn); + + if (backend_ctx->gpu_family == INTEL) { + opts += " -D FA_SG=32"; + } + + const bool is_split = variant == FA_VARIANT_F32_F16_SPLIT || + variant == FA_VARIANT_Q8_0_SPLIT || + variant == FA_VARIANT_Q4_0_SPLIT; + if (is_split) { + opts += " -D N_SPLIT=" + std::to_string(cfg->n_split); + } + // Shuffle define for the split tile paths AND the cluster-parallel decode + // kernel (q1_vec_mq_split_c8) in the plain F32_F16 program. Without it the + // c8 kernel is compiled out (HAS_SUBGROUP_SHUFFLE guard) and dispatch + // falls back to the baseline mq_split. + if ((is_split || variant == FA_VARIANT_F32_F16) && backend_ctx->has_subgroup_shuffle) { + opts += backend_ctx->has_qcom_subgroup_shuffle + ? " -D cl_qcom_subgroup_shuffle=1" + : " -D cl_khr_subgroup_shuffle=1"; + } + // X1E drops the explicit sub-group size pin on the c8 kernels, compiler + // routes the fp16-heavy kernel to a slow variant with explicit subgroup size + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E) { + opts += " -D FA_C8_NO_SG_PIN"; + } + // Transposed K tile in local memory: the KV rows the QK loop walks together become + // adjacent, so a group of them is ONE 128-bit local read instead of several narrow + // ones. The QK loop is LDS-read-issue-bound (a wrong-math probe that kept every FMA/dp4a + // but removed the LDS reads ran the kernel ~40% faster), so this is worth up to +26% on + // fa=1 prefill. Output is bit-identical -- only the layout moves. + // + // DK <= 128 only. At DK=256 (gemma-3-4b) it measures 1-2% NEGATIVE and reproduces across + // rounds; padding the row stride does not recover it, so the cause is not a simple bank + // conflict and the wider tile does not want this layout. + // + // Default on within that gate; GGML_OPENCL_FA_K_LDS_T=0 restores the row-major tile. + { + const char * e = getenv("GGML_OPENCL_FA_K_LDS_T"); + if ((e == nullptr || e[0] != '0') && cfg->dk <= 128) { + opts += " -D FA_K_LDS_T"; + } + } + return opts; +} + +// only register when the kernel's required dispatch workgroup size is within +// the limit of the device's maximum workgroup size +static bool ggml_opencl_fa_kernel_fits_wg(ggml_backend_opencl_context * backend_ctx, + cl_kernel kernel, size_t required_wg, + const char * name, int dk, int dv) { + if (kernel == NULL) { return false; } + const size_t dev_max = backend_ctx->max_workgroup_size; + if (dev_max < required_wg) { + GGML_LOG_INFO("ggml_opencl: %s DK=%d DV=%d requires WG %zu > device max %zu; skipping registration (will fall back)\n", + name, dk, dv, required_wg, dev_max); + return false; + } + size_t kwg = 0; + cl_int err = clGetKernelWorkGroupInfo(kernel, backend_ctx->device, + CL_KERNEL_WORK_GROUP_SIZE, + sizeof(kwg), &kwg, NULL); + if (err != CL_SUCCESS) { + GGML_LOG_INFO("ggml_opencl: clGetKernelWorkGroupInfo failed for %s DK=%d DV=%d (err=%d); skipping registration\n", + name, dk, dv, err); + return false; + } + if (kwg < required_wg) { + GGML_LOG_INFO("ggml_opencl: %s DK=%d DV=%d per-kernel max %zu < required %zu; skipping registration (will fall back)\n", + name, dk, dv, kwg, required_wg); + return false; + } + return true; +} + +// Log private memory for an FA kernel. Enable via `GGML_OPENCL_FA_LOG_SPILL=1`. +// On Adreno non-zero private_mem means spilling to global memory due to resource +// constraint and usually causes performance degradation. +// (per-work-item, no cache locality) — a strong signal to pick a config +// with smaller per-thread state (e.g. larger N_SPLIT). +static void ggml_opencl_log_fa_kernel_spill(ggml_backend_opencl_context * backend_ctx, + cl_kernel kernel, const char * name, int dk, int dv) { + static const bool enabled = []{ + const char * e = std::getenv("GGML_OPENCL_FA_LOG_SPILL"); + return e && e[0] && e[0] != '0'; + }(); + + if (!enabled || kernel == nullptr) { + return; + } + + cl_ulong priv_mem = 0; + if (clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_PRIVATE_MEM_SIZE, + sizeof(priv_mem), &priv_mem, NULL) == CL_SUCCESS) { + const char * tag = priv_mem > 0 ? "SPILL" : "ok"; + GGML_LOG_INFO("ggml_opencl: [%s] %s DK=%d DV=%d private_mem=%llu bytes\n", + tag, name, dk, dv, (unsigned long long) priv_mem); + } +} + +static void ggml_opencl_ensure_fa_pre_kernels(ggml_backend_opencl_context * backend_ctx, int dk, int dv) { + const std::pair dk_dv = {dk, dv}; + + const ggml_opencl_fa_dim * cfg = nullptr; + for (const auto & d : g_opencl_fa_dims) { + if (d.dk == dk && d.dv == dv) { + cfg = &d; break; + } + } + + if (cfg == nullptr) { + GGML_ABORT("ggml_opencl: no flash_attn config for DK=%d DV=%d", dk, dv); + } + + // BM-tile metadata is consumed by the prefill dispatch (n_q_blocks / wg + // sizing) regardless of whether the prepass kernels are needed for this + // n_kv — set it unconditionally + backend_ctx->fa.f32_f16_bm[{dk, dv}] = cfg->bm; + backend_ctx->fa.f32_f16_bn[{dk, dv}] = cfg->bn; + backend_ctx->fa.f32_f16_wg_size[{dk, dv}] = cfg->bm; + backend_ctx->fa.bm[{dk, dv}] = cfg->bm; + backend_ctx->fa.bn[{dk, dv}] = cfg->bn; + + if (backend_ctx->fa.kv_pad_f16.count(dk_dv) > 0) { return; } + + GGML_LOG_INFO("ggml_opencl: lazy-compiling flash_attn prepass for DK=%d DV=%d\n", dk, dv); + cl_int err; + const std::string src = ggml_opencl_fa_kernel_src(FA_VARIANT_PRE); + const std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, FA_VARIANT_PRE); + // retry when kernel compile fails + cl_program prog_pre_f16 = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts, + /*fatal=*/false, "fa prepass f16", backend_ctx->queue); + if (!prog_pre_f16) { return; } + cl_kernel k_kv_pad_f16 = clCreateKernel(prog_pre_f16, "flash_attn_kv_pad_f16", &err); + if (err != CL_SUCCESS) { clReleaseProgram(prog_pre_f16); return; } + cl_kernel k_mask_pad_f16 = clCreateKernel(prog_pre_f16, "flash_attn_mask_pad_f16", &err); + if (err != CL_SUCCESS) { clReleaseKernel(k_kv_pad_f16); clReleaseProgram(prog_pre_f16); return; } + cl_kernel k_blk_f16 = clCreateKernel(prog_pre_f16, "flash_attn_blk_f16", &err); + if (err != CL_SUCCESS) { clReleaseKernel(k_kv_pad_f16); clReleaseKernel(k_mask_pad_f16); clReleaseProgram(prog_pre_f16); return; } + backend_ctx->fa.kv_pad_f16[{dk, dv}] = k_kv_pad_f16; + backend_ctx->fa.mask_pad_f16[{dk, dv}] = k_mask_pad_f16; + backend_ctx->fa.blk_f16[{dk, dv}] = k_blk_f16; + // optional, the decomposed prefill checks for it and falls back to the fused tile + cl_kernel k_v_transpose_f16 = clCreateKernel(prog_pre_f16, "flash_attn_v_transpose_f16", &err); + if (err == CL_SUCCESS) { + backend_ctx->fa.v_transpose_f16[{dk, dv}] = k_v_transpose_f16; + } + if (backend_ctx->fa.kernel_fa_v_transpose_q8 == nullptr && backend_ctx->has_integer_dot) { + backend_ctx->fa.kernel_fa_v_transpose_q8 = clCreateKernel(prog_pre_f16, "flash_attn_v_transpose_q8", &err); + if (err != CL_SUCCESS) { + backend_ctx->fa.kernel_fa_v_transpose_q8 = nullptr; + } + } + clReleaseProgram(prog_pre_f16); +} + +bool ggml_opencl_ensure_fa_f32_f16_vec_512(ggml_backend_opencl_context * backend_ctx) { + const std::pair key = {512, 512}; + auto & fa = backend_ctx->fa; + if (fa.f32_f16_q1_vec.count(key) > 0) { + return true; + } + if (fa.f32_f16_vec_512_attempted || backend_ctx->kernel_compile_opts.empty()) { + return false; + } + fa.f32_f16_vec_512_attempted = true; + + const ggml_opencl_fa_dim * cfg = nullptr; + for (const auto & d : g_opencl_fa_dims) { + if (d.dk == 512 && d.dv == 512) { + cfg = &d; + break; + } + } + if (cfg == nullptr) { + return false; + } + + // Compile only vec decode and merge to stay within the Adreno compiler's memory limit. + const std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, FA_VARIANT_F32_F16) + + " -D FA_DECODE_ONLY -D FA_VEC_ONLY"; + cl_program prog = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, + ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16).c_str(), opts, + /*fatal=*/false, "fa f32_f16 decode512 vec", backend_ctx->queue); + if (!prog) { + return false; + } + cl_int err; + cl_kernel vec = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec", &err); + if (err != CL_SUCCESS) { + clReleaseProgram(prog); + return false; + } + cl_kernel merge = clCreateKernel(prog, "flash_attn_f32_merge", &err); + clReleaseProgram(prog); + if (err != CL_SUCCESS) { + clReleaseKernel(vec); + return false; + } + if (!ggml_opencl_fa_kernel_fits_wg(backend_ctx, vec, 256, "flash_attn_f32_f16_q1_vec", 512, 512) || + !ggml_opencl_fa_kernel_fits_wg(backend_ctx, merge, 128, "flash_attn_f32_merge", 512, 512)) { + clReleaseKernel(vec); + clReleaseKernel(merge); + return false; + } + fa.f32_f16_q1_vec[key] = vec; + if (fa.f32_merge.count(key) > 0) { + clReleaseKernel(merge); + } else { + fa.f32_merge[key] = merge; + } + return true; +} + +static void ggml_opencl_ensure_fa_f32_f16_mq_decode(ggml_backend_opencl_context * backend_ctx, int dk, int dv, int gqa) { + const std::tuple key = {dk, dv, gqa}; + auto & fa = backend_ctx->fa; + if (fa.f32_f16_mq_decode.count(key) > 0 || fa.f32_f16_mq_decode_attempted.count(key) > 0 || + backend_ctx->kernel_compile_opts.empty()) { + return; + } + if (gqa == 4 && dk != 128 && fa.f32_f16_q1_vec_mq_split.count({dk, dv}) > 0) { + fa.f32_f16_mq_decode[key] = fa.f32_f16_q1_vec_mq_split.at({dk, dv}); + fa.f32_f16_mq_decode_wg[key] = 256; + fa.f32_f16_mq_decode_hs[key] = 1; + return; + } + fa.f32_f16_mq_decode_attempted.insert(key); + const ggml_opencl_fa_dim * cfg = nullptr; + for (const auto & d : g_opencl_fa_dims) { + if (d.dk == dk && d.dv == dv) { + cfg = &d; + break; + } + } + if (cfg == nullptr) { + return; + } + + const bool cluster = dk == 64 || dk == 128; + const int head_sub = gqa == 16 ? (cluster ? 4 : 8) : + cluster ? 2 : (gqa == 8 ? (dk == 512 ? 4 : 2) : 1); + const int nsg_max = dk == 64 ? 1 : (dk == 128 || (gqa == 8 && dk == 256) ? 2 : 4); + const char * kernel_name = cluster ? "flash_attn_f32_f16_q1_vec_mq_split_c8" : "flash_attn_f32_f16_q1_vec_mq_split"; + const std::string src = ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16); + const std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, FA_VARIANT_F32_F16) + + " -D FA_MQ_ONLY -D MQ_GQA=" + std::to_string(gqa / head_sub) + + " -D FA_HEAD_SUB=" + std::to_string(head_sub) + + (cluster ? " -D MQ_NSG=" + std::to_string(nsg_max) + " -D FA_CL_C=16" : " -D FA_MQ_SPLIT_ONLY") + + (dk == 64 ? " -D FA_CL_MHRED -D FA_CL_MASK_BCAST" : (cluster && gqa == 16 ? " -D FA_CL_MHRED" : "")) + + (gqa == 8 && dk == 256 ? " -D FA_Q1_Q_REG" : ""); + for (int nsg = nsg_max; nsg >= 1; nsg /= 2) { + const size_t wg = 64 * nsg; + cl_program prog = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), + opts + " -D MQ_NSG_SPLIT=" + std::to_string(nsg), + /*fatal=*/false, "fa f32_f16 mq decode", backend_ctx->queue); + if (!prog) { + continue; + } + cl_int err; + cl_kernel kernel = clCreateKernel(prog, kernel_name, &err); + clReleaseProgram(prog); + if (err != CL_SUCCESS) { + continue; + } + if (!ggml_opencl_fa_kernel_fits_wg(backend_ctx, kernel, wg, kernel_name, dk, dv)) { + clReleaseKernel(kernel); + continue; + } + fa.f32_f16_mq_decode[key] = kernel; + fa.f32_f16_mq_decode_wg[key] = wg; + fa.f32_f16_mq_decode_hs[key] = head_sub; + return; + } +} + +// DK=512 prefill BM-tile +bool ggml_opencl_ensure_fa_f32_f16_prefill_512(ggml_backend_opencl_context * backend_ctx, bool split) { + const int dk = 512, dv = 512; + const std::pair dk_dv = {dk, dv}; + auto & target = split ? backend_ctx->fa.f32_f16_split : backend_ctx->fa.f32_f16; + if (target.count(dk_dv) > 0) { return true; } + + static bool failed[2] = { false, false }; + if (failed[split ? 1 : 0]) { return false; } + + const ggml_opencl_fa_dim * cfg = nullptr; + for (const auto & d : g_opencl_fa_dims) { + if (d.dk == dk && d.dv == dv) { cfg = &d; break; } + } + if (cfg == nullptr) { failed[split ? 1 : 0] = true; return false; } + if (split && cfg->n_split <= 1) { failed[1] = true; return false; } + + const ggml_opencl_fa_variant variant = split ? FA_VARIANT_F32_F16_SPLIT : FA_VARIANT_F32_F16; + std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, variant) + " -D FA_PREFILL_ONLY"; + cl_program prog = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, + ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16).c_str(), opts, + /*fatal=*/false, split ? "fa f32_f16 prefill512 split" : "fa f32_f16 prefill512", + backend_ctx->queue); + if (!prog) { failed[split ? 1 : 0] = true; return false; } + + cl_int err; + cl_kernel k = clCreateKernel(prog, "flash_attn_f32_f16", &err); + if (err != CL_SUCCESS) { clReleaseProgram(prog); failed[split ? 1 : 0] = true; return false; } + target[dk_dv] = k; + if (split) { + backend_ctx->fa.f32_f16_split_wg_size[dk_dv] = cfg->bm * cfg->n_split; + backend_ctx->fa.f32_f16_split_nkv_threshold[dk_dv] = cfg->nkv_split_threshold; + } + ggml_opencl_log_fa_kernel_spill(backend_ctx, k, + split ? "flash_attn_f32_f16 (prefill512 split)" : "flash_attn_f32_f16 (prefill512)", dk, dv); + clReleaseProgram(prog); + + // determine whether to use the K-image variant of the split tile + static const char * pkimg_build_env = getenv("GGML_OPENCL_FA_PREFILL_K_IMG"); + const bool pkimg_build = (pkimg_build_env != NULL) && (pkimg_build_env[0] != '0'); + if (split && pkimg_build && backend_ctx->fa.f32_f16_split_k_img.count(dk_dv) == 0) { + std::string opts_img = ggml_opencl_fa_compile_opts(backend_ctx, cfg, variant) + + " -D FA_PREFILL_ONLY -D FA_K_IMG -D FA_TILE_NAME=flash_attn_f32_f16_k_img"; + cl_program prog_img = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, + ggml_opencl_fa_kernel_src(FA_VARIANT_F32_F16).c_str(), opts_img, + /*fatal=*/false, "fa f32_f16 prefill512 split k_img", backend_ctx->queue); + if (prog_img) { + cl_int err_img; + cl_kernel k_img = clCreateKernel(prog_img, "flash_attn_f32_f16_k_img", &err_img); + if (err_img == CL_SUCCESS) { + backend_ctx->fa.f32_f16_split_k_img[dk_dv] = k_img; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_img, + "flash_attn_f32_f16 (prefill512 split k_img)", dk, dv); + } + clReleaseProgram(prog_img); + } + } + return true; +} + +// Compile one (variant, dk, dv); memoised. false = compiler rejected. +static bool ggml_opencl_ensure_fa_variant(ggml_backend_opencl_context * backend_ctx, int dk, int dv, ggml_opencl_fa_variant variant) { + const std::pair dk_dv = {dk, dv}; + + const ggml_opencl_fa_dim * cfg = nullptr; + for (const auto & d : g_opencl_fa_dims) { + if (d.dk == dk && d.dv == dv) { + cfg = &d; break; + } + } + if (cfg == nullptr) { + return false; + } + + // if a variant has already been compiled + switch (variant) { + case FA_VARIANT_F16: { + if (backend_ctx->fa.f16.count(dk_dv)) { + return true; + } + break; + } + case FA_VARIANT_F32: { + if (backend_ctx->fa.f32.count(dk_dv)) { + return true; + } + break; + } + case FA_VARIANT_F32_F16: { + // The DK=512 decode-only program does not create the f32_f16 + // prefill kernel; check the q1 kernel instead so that repeated + // calls return a consistent result. + const bool decode_only = (dk == 512); + if (decode_only ? (backend_ctx->fa.f32_f16_q1.count(dk_dv) > 0) + : (backend_ctx->fa.f32_f16.count(dk_dv) > 0)) { + return true; + } + break; + } + case FA_VARIANT_Q8_0: { + if (backend_ctx->fa.f32_q8_0.count(dk_dv)) { + return true; + } + break; + } + case FA_VARIANT_Q4_0: { + if (backend_ctx->fa.f32_q4_0.count(dk_dv)) { + return true; + } + break; + } + case FA_VARIANT_F32_F16_SPLIT: { + if (backend_ctx->fa.f32_f16_split.count(dk_dv)) { + return true; + } + break; + } + case FA_VARIANT_Q8_0_SPLIT: { + if (backend_ctx->fa.f32_q8_0_split.count(dk_dv)) { + return true; + } + break; + } + case FA_VARIANT_Q4_0_SPLIT: { + if (backend_ctx->fa.f32_q4_0_split.count(dk_dv)) { + return true; + } + break; + } + case FA_VARIANT_PRE: { + ggml_opencl_ensure_fa_pre_kernels(backend_ctx, dk, dv); + return true; + } + } + + // not registered but attempted - meaning these kernels failed to compile + const auto attempt_key = std::make_pair(variant, dk_dv); + if (backend_ctx->fa.variant_attempted.count(attempt_key)) { + return false; + } + backend_ctx->fa.variant_attempted.insert(attempt_key); + + const bool is_split = variant == FA_VARIANT_F32_F16_SPLIT || + variant == FA_VARIANT_Q8_0_SPLIT || + variant == FA_VARIANT_Q4_0_SPLIT; + const bool is_quant = variant == FA_VARIANT_Q8_0 || variant == FA_VARIANT_Q8_0_SPLIT || + variant == FA_VARIANT_Q4_0 || variant == FA_VARIANT_Q4_0_SPLIT; + if (is_quant && (dk % 32 != 0 || dv % 32 != 0)) { + return false; + } + if (is_split && cfg->n_split <= 1) { + return false; + } + if ((variant == FA_VARIANT_Q8_0_SPLIT || variant == FA_VARIANT_Q4_0_SPLIT) && + ((dk / 32) % cfg->n_split != 0 || (dv / 4) % cfg->n_split != 0)) { + return false; + } + + const std::string src = ggml_opencl_fa_kernel_src(variant); + if (src.empty()) { return false; } + std::string opts = ggml_opencl_fa_compile_opts(backend_ctx, cfg, variant); + + // bypass kernels for DK=512 + const bool fa_decode_only = (variant == FA_VARIANT_F32_F16 && dk == 512); + if (fa_decode_only) { + opts += " -D FA_DECODE_ONLY -D FA_DECODE_MINIMAL"; + } + + // c8 cluster width (GGML_OPENCL_FA_CL_C overrides): value = GQA4 cluster + // width (kernel default 8); the g8 programs use 2x the value (default 16). + // Wider clusters halve per-lane o_acc at the cost of position streams per + // subgroup + static const int fa_cl_c_env = []{ + const char * e = std::getenv("GGML_OPENCL_FA_CL_C"); + const int x = (e && e[0]) ? atoi(e) : 0; + return (x == 8 || x == 16 || x == 32) ? x : 0; // 0 = per-gen default + }(); + // X2E needs 16 to keep per-lane o_acc at 128B (the compiler spills the + // kernel-default width); X1E does not spill, but C=16 is still a measured + // +28-30% DK128-GQA4 decode win there (X1-85, kv 4096/8192), neutral on + // DK64 / GQA1 / quant-KV. + const int fa_cl_c_gqa4 = fa_cl_c_env ? fa_cl_c_env + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E ? 16 : 0); + const std::string opts_cl_c_gqa4 = fa_cl_c_gqa4 + ? " -D FA_CL_C=" + std::to_string(fa_cl_c_gqa4) : std::string(); + const std::string fa_cl_c_g8_val = std::to_string(fa_cl_c_gqa4 ? fa_cl_c_gqa4 * 2 : 16); + + const char * tag = nullptr; + switch (variant) { + case FA_VARIANT_F16: tag = "fa f16"; break; + case FA_VARIANT_F32: tag = "fa f32"; break; + case FA_VARIANT_F32_F16: tag = "fa f32_f16"; break; + case FA_VARIANT_Q8_0: tag = "fa q8_0"; break; + case FA_VARIANT_Q4_0: tag = "fa q4_0"; break; + case FA_VARIANT_F32_F16_SPLIT: tag = "fa f32_f16 split"; break; + case FA_VARIANT_Q8_0_SPLIT: tag = "fa q8_0 split"; break; + case FA_VARIANT_Q4_0_SPLIT: tag = "fa q4_0 split"; break; + default: break; + } + cl_program prog = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts + opts_cl_c_gqa4, + /*fatal=*/false, tag, backend_ctx->queue); + if (!prog) { return false; } + + cl_int err; + switch (variant) { + case FA_VARIANT_F16: { + cl_kernel k, kq1; + CL_CHECK((k = clCreateKernel(prog, "flash_attn_f16", &err), err)); + CL_CHECK((kq1 = clCreateKernel(prog, "flash_attn_f16_q1", &err), err)); + backend_ctx->fa.f16[{dk, dv}] = k; + backend_ctx->fa.f16_q1[{dk, dv}] = kq1; + break; + } + case FA_VARIANT_F32: { + cl_kernel k, kq1; + CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32", &err), err)); + CL_CHECK((kq1 = clCreateKernel(prog, "flash_attn_f32_q1", &err), err)); + backend_ctx->fa.f32[{dk, dv}] = k; + backend_ctx->fa.f32_q1[{dk, dv}] = kq1; + break; + } + case FA_VARIANT_F32_F16: { + cl_kernel kq1; + // BM-tile prefill kernel is excluded from the decode-only (DK=512) + if (!fa_decode_only) { + cl_kernel k; + CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_f16", &err), err)); + backend_ctx->fa.f32_f16[{dk, dv}] = k; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k, "flash_attn_f32_f16", dk, dv); + } + CL_CHECK((kq1 = clCreateKernel(prog, "flash_attn_f32_f16_q1", &err), err)); + backend_ctx->fa.f32_f16_q1[{dk, dv}] = kq1; + ggml_opencl_log_fa_kernel_spill(backend_ctx, kq1, "flash_attn_f32_f16_q1", dk, dv); + cl_kernel k_split = clCreateKernel(prog, "flash_attn_f32_f16_q1_split", &err); + if (err == CL_SUCCESS) { + backend_ctx->fa.f32_f16_q1_split[{dk, dv}] = k_split; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_split, "flash_attn_f32_f16_q1_split", dk, dv); + } + // q1_vec decode kernel (DV-split + subgroup reduce) + cl_kernel k_q1_vec = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec, 256, + "flash_attn_f32_f16_q1_vec", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec[{dk, dv}] = k_q1_vec; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec, "flash_attn_f32_f16_q1_vec", dk, dv); + } else { + clReleaseKernel(k_q1_vec); + } + } + // KV-head-coalesced vec for high-GQA small models + cl_kernel k_q1_vec_mq = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq, 256, + "flash_attn_f32_f16_q1_vec_mq", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq[{dk, dv}] = k_q1_vec_mq; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq, "flash_attn_f32_f16_q1_vec_mq", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq); + } + } + // KV-head-coalesced + flash-decoding split, reuses merge kernel + cl_kernel k_q1_vec_mq_split = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq_split", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split, 256, + "flash_attn_f32_f16_q1_vec_mq_split", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split[{dk, dv}] = k_q1_vec_mq_split; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split, "flash_attn_f32_f16_q1_vec_mq_split", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_split); + } + } + // K-image variant of MQ_GQA=4 split + cl_kernel k_q1_vec_mq_split_k_img = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq_split_k_img", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_k_img, 256, + "flash_attn_f32_f16_q1_vec_mq_split_k_img", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_k_img[{dk, dv}] = k_q1_vec_mq_split_k_img; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_k_img, "flash_attn_f32_f16_q1_vec_mq_split_k_img", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_split_k_img); + } + } + // Cluster-parallel decode variant + cl_kernel k_q1_vec_mq_split_c8 = clCreateKernel(prog, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_c8, 256, + "flash_attn_f32_f16_q1_vec_mq_split_c8", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_c8[{dk, dv}] = k_q1_vec_mq_split_c8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_split_c8); + } + } + cl_kernel k_merge = clCreateKernel(prog, "flash_attn_f32_merge", &err); + if (err == CL_SUCCESS) { + backend_ctx->fa.f32_merge[{dk, dv}] = k_merge; + } + // local-tile decode variant + if (dk == 128 && dv == 128) { + cl_kernel k_lt = clCreateKernel(prog, "flash_attn_f32_f16_q1_local_tile", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_lt, 128, + "flash_attn_f32_f16_q1_local_tile", dk, dv)) { + backend_ctx->fa.f32_f16_q1_local_tile[{dk, dv}] = k_lt; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_lt, "flash_attn_f32_f16_q1_local_tile", dk, dv); + } else { + clReleaseKernel(k_lt); + } + } + // hybrid local-tile + MQ + FD-split + cl_kernel k_lmq = clCreateKernel(prog, "flash_attn_f32_f16_q1_local_mq_split", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_lmq, 64, + "flash_attn_f32_f16_q1_local_mq_split", dk, dv)) { + backend_ctx->fa.f32_f16_q1_local_mq_split[{dk, dv}] = k_lmq; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_lmq, "flash_attn_f32_f16_q1_local_mq_split", dk, dv); + } else { + clReleaseKernel(k_lmq); + } + } + } + + // second compile of the same source with -DMQ_GQA=8. + // FA_MQ_ONLY keeps only the vec_mq kernels so that the program + // compiles within the Adreno compiler's memory budget at DK>=256. + // FA_CL_C for the g8 program: MQ_GQA=8 doubles the c8 kernel's + // per-lane o_acc, so widen the cluster to keep the register + // footprint inside the 192-thread WG cap (see fa_cl_c_gqa4 above + // for the per-gen default). + const std::string opts_g8 = opts + " -D MQ_GQA=8 -D MQ_NSG=3 -D MQ_NSG_SPLIT=3 -D FA_MQ_ONLY -D FA_CL_C=" + fa_cl_c_g8_val; + cl_program prog_g8 = fa_decode_only ? nullptr : build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts_g8, + /*fatal=*/false, "fa f32_f16 MQ_GQA=8", backend_ctx->queue); + if (prog_g8) { + const size_t mq_g8_required_wg = 192; // Q1_WG_SIZE(64) * MQ_NSG_SPLIT(3) + cl_kernel k_q1_vec_mq_g8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_g8, mq_g8_required_wg, + "flash_attn_f32_f16_q1_vec_mq (g8)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_g8[{dk, dv}] = k_q1_vec_mq_g8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_g8, "flash_attn_f32_f16_q1_vec_mq_g8", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_g8); + } + } + cl_kernel k_q1_vec_mq_split_g8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq_split", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_g8, mq_g8_required_wg, + "flash_attn_f32_f16_q1_vec_mq_split (g8)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8[{dk, dv}] = k_q1_vec_mq_split_g8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_g8, "flash_attn_f32_f16_q1_vec_mq_split_g8", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_split_g8); + } + } + // K-image variant + cl_kernel k_q1_vec_mq_split_g8_k_img = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq_split_k_img", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_g8_k_img, mq_g8_required_wg, + "flash_attn_f32_f16_q1_vec_mq_split_k_img (g8)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_k_img[{dk, dv}] = k_q1_vec_mq_split_g8_k_img; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_g8_k_img, "flash_attn_f32_f16_q1_vec_mq_split_g8_k_img", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_split_g8_k_img); + } + } + // Cluster-parallel decode, MQ_GQA=8 / FA_CL_C=16 specialization + cl_kernel k_q1_vec_mq_split_g8_c8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split_g8_c8, mq_g8_required_wg, + "flash_attn_f32_f16_q1_vec_mq_split_c8 (g8)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8[{dk, dv}] = k_q1_vec_mq_split_g8_c8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split_g8_c8, "flash_attn_f32_f16_q1_vec_mq_split_g8_c8", dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_split_g8_c8); + } + } + // hybrid local-tile + MQ_GQA=8 + if (dk == 128 && dv == 128) { + cl_kernel k_lmq_g8 = clCreateKernel(prog_g8, "flash_attn_f32_f16_q1_local_mq_split", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_lmq_g8, 64, + "flash_attn_f32_f16_q1_local_mq_split (g8)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_local_mq_split_g8[{dk, dv}] = k_lmq_g8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_lmq_g8, "flash_attn_f32_f16_q1_local_mq_split_g8", dk, dv); + } else { + clReleaseKernel(k_lmq_g8); + } + } + } + clReleaseProgram(prog_g8); + } + // NSG_SPLIT=2 programs for the cluster-parallel kernel: its register + // footprint caps the per-kernel WG at 128 on X2 (< the stock 256/192 + // requirement), so it can never register from the stock programs. + // With FA_CL_NCL position streams per subgroup, 2 subgroups still + // carry 16 in-flight rows per WG (baseline WG has 4). FA_MQ_ONLY + // keeps these compiles minimal; skipped when the stock program c8 + // registered (some other device) or shuffles are absent. + if (!fa_decode_only && backend_ctx->has_subgroup_shuffle && + backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.count({dk, dv}) == 0) { + const std::string opts_c8_ns2 = opts + " -D FA_MQ_ONLY -D MQ_GQA=4 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2" + opts_cl_c_gqa4; + cl_program prog_c8 = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts_c8_ns2, + /*fatal=*/false, "fa f32_f16 c8 NSG2", backend_ctx->queue); + if (prog_c8) { + cl_kernel k_c8 = clCreateKernel(prog_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); + if (err == CL_SUCCESS) { + // WG = MQ_NSG(2) × Q1_WG_SIZE(=FA_SG): 128 Adreno (64), 64 Intel (32). + const size_t c8_ns2_wg = backend_ctx->gpu_family == INTEL ? 64 : 128; + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_c8, c8_ns2_wg, + "flash_attn_f32_f16_q1_vec_mq_split_c8 (ns2)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2[{dk, dv}] = k_c8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8_ns2", dk, dv); + } else { + clReleaseKernel(k_c8); + } + } + clReleaseProgram(prog_c8); + } + } + // FA_CL_C=32 g8 program for the DK=DV=256 GQA=8 + if (!fa_decode_only && backend_ctx->has_subgroup_shuffle && + dk == 256 && dv == 256) { + const std::string opts_g8_c32 = opts + " -D FA_MQ_ONLY -D MQ_GQA=8 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2 -D FA_CL_C=32"; + cl_program prog_g8_c32 = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts_g8_c32, + /*fatal=*/false, "fa f32_f16 c32 g8 d256 NSG2", backend_ctx->queue); + if (prog_g8_c32) { + cl_kernel k_g8_c32 = clCreateKernel(prog_g8_c32, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_g8_c32, 128, + "flash_attn_f32_f16_q1_vec_mq_split_c8 (g8 c32 d256)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c32[{dk, dv}] = k_g8_c32; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_g8_c32, "flash_attn_f32_f16_q1_vec_mq_split_g8_c32", dk, dv); + } else { + clReleaseKernel(k_g8_c32); + } + } + clReleaseProgram(prog_g8_c32); + } + } + if (!fa_decode_only && backend_ctx->has_subgroup_shuffle && + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.count({dk, dv}) == 0) { + const std::string opts_g8_c8_ns2 = opts + " -D FA_MQ_ONLY -D MQ_GQA=8 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2 -D FA_CL_C=" + fa_cl_c_g8_val; + cl_program prog_g8_c8 = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts_g8_c8_ns2, + /*fatal=*/false, "fa f32_f16 c8 g8 NSG2", backend_ctx->queue); + if (prog_g8_c8) { + cl_kernel k_g8_c8 = clCreateKernel(prog_g8_c8, "flash_attn_f32_f16_q1_vec_mq_split_c8", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_g8_c8, 128, + "flash_attn_f32_f16_q1_vec_mq_split_c8 (g8 ns2)", dk, dv)) { + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8_ns2[{dk, dv}] = k_g8_c8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_g8_c8, "flash_attn_f32_f16_q1_vec_mq_split_g8_c8_ns2", dk, dv); + } else { + clReleaseKernel(k_g8_c8); + } + } + clReleaseProgram(prog_g8_c8); + } + } + break; + } + case FA_VARIANT_Q8_0: + case FA_VARIANT_Q4_0: { + const bool is_q8 = variant == FA_VARIANT_Q8_0; + const std::string base = is_q8 ? "flash_attn_f32_q8_0" : "flash_attn_f32_q4_0"; + const std::string name_q1 = base + "_q1"; + const std::string name_q1_split = base + "_q1_split"; + auto & m_q1 = is_q8 ? backend_ctx->fa.f32_q8_0_q1 : backend_ctx->fa.f32_q4_0_q1; + auto & m_prefill = is_q8 ? backend_ctx->fa.f32_q8_0 : backend_ctx->fa.f32_q4_0; + auto & m_q1_split = is_q8 ? backend_ctx->fa.f32_q8_0_q1_split : backend_ctx->fa.f32_q4_0_q1_split; + + cl_kernel k, kq1; + CL_CHECK((kq1 = clCreateKernel(prog, name_q1.c_str(), &err), err)); + CL_CHECK((k = clCreateKernel(prog, base.c_str(), &err), err)); + m_q1[{dk, dv}] = kq1; + m_prefill[{dk, dv}] = k; + ggml_opencl_log_fa_kernel_spill(backend_ctx, kq1, name_q1.c_str(), dk, dv); + ggml_opencl_log_fa_kernel_spill(backend_ctx, k, base.c_str(), dk, dv); + cl_kernel k_split = clCreateKernel(prog, name_q1_split.c_str(), &err); + if (err == CL_SUCCESS) { + m_q1_split[{dk, dv}] = k_split; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_split, name_q1_split.c_str(), dk, dv); + } + + // DV-split decode variant (q1_vec) + auto & m_q1_vec = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec : backend_ctx->fa.f32_q4_0_q1_vec; + const std::string name_q1_vec = name_q1 + "_vec"; + cl_kernel k_q1_vec = clCreateKernel(prog, name_q1_vec.c_str(), &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec, 256, + name_q1_vec.c_str(), dk, dv)) { + m_q1_vec[{dk, dv}] = k_q1_vec; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec, name_q1_vec.c_str(), dk, dv); + } else { + clReleaseKernel(k_q1_vec); + } + } + + // KV-head-coalesced + flash-decoding split + auto & m_mq_split = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec_mq_split + : backend_ctx->fa.f32_q4_0_q1_vec_mq_split; + const std::string name_mq_split = name_q1 + "_vec_mq_split"; + cl_kernel k_q1_vec_mq_split = clCreateKernel(prog, name_mq_split.c_str(), &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_q1_vec_mq_split, 256, + name_mq_split.c_str(), dk, dv)) { + m_mq_split[{dk, dv}] = k_q1_vec_mq_split; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_q1_vec_mq_split, name_mq_split.c_str(), dk, dv); + } else { + clReleaseKernel(k_q1_vec_mq_split); + } + } + if (!backend_ctx->fa.f32_merge.count({dk, dv})) { + cl_kernel k_merge = clCreateKernel(prog, "flash_attn_f32_merge", &err); + if (err == CL_SUCCESS) { + backend_ctx->fa.f32_merge[{dk, dv}] = k_merge; + } + } + // Second compile with MQ_GQA=8, MQ_NSG=3, MQ_NSG_SPLIT=3 + auto & m_mq_split_g8 = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec_mq_split_g8 + : backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8; + const std::string opts_mq_g8 = opts + " -D MQ_GQA=8 -D MQ_NSG=3 -D MQ_NSG_SPLIT=3"; + cl_program prog_mq_g8 = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts_mq_g8, + /*fatal=*/false, is_q8 ? "fa q8_0 MQ_GQA=8" : "fa q4_0 MQ_GQA=8", + backend_ctx->queue); + if (prog_mq_g8) { + const size_t mq_g8_required_wg = 192; + cl_kernel k_g8 = clCreateKernel(prog_mq_g8, name_mq_split.c_str(), &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_g8, mq_g8_required_wg, + name_mq_split.c_str(), dk, dv)) { + m_mq_split_g8[{dk, dv}] = k_g8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_g8, name_mq_split.c_str(), dk, dv); + } else { + clReleaseKernel(k_g8); + } + } + clReleaseProgram(prog_mq_g8); + } + // GQA=4 cluster-parallel program (NSG_SPLIT=2 / WG=128) + if (backend_ctx->has_subgroup_shuffle) { + auto & m_c8_gqa4 = is_q8 ? backend_ctx->fa.f32_q8_0_q1_vec_mq_split_c8 + : backend_ctx->fa.f32_q4_0_q1_vec_mq_split_c8; + const std::string name_c8_gqa4 = name_q1 + "_vec_mq_split_c8"; + const std::string opts_c8_gqa4 = opts + " -D MQ_GQA=4 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2" + opts_cl_c_gqa4; + cl_program prog_c8_gqa4 = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts_c8_gqa4, + /*fatal=*/false, is_q8 ? "fa q8_0 c8 GQA4 NSG2" : "fa q4_0 c8 GQA4 NSG2", + backend_ctx->queue); + if (prog_c8_gqa4) { + cl_kernel k_c8_gqa4 = clCreateKernel(prog_c8_gqa4, name_c8_gqa4.c_str(), &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_c8_gqa4, 128, + name_c8_gqa4.c_str(), dk, dv)) { + m_c8_gqa4[{dk, dv}] = k_c8_gqa4; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_c8_gqa4, name_c8_gqa4.c_str(), dk, dv); + } else { + clReleaseKernel(k_c8_gqa4); + } + } + clReleaseProgram(prog_c8_gqa4); + } + } + // Cluster-parallel q4_0 decode kernel + if (!is_q8 && backend_ctx->has_subgroup_shuffle) { + const std::string opts_c8 = opts + " -D MQ_GQA=8 -D MQ_NSG=2 -D MQ_NSG_SPLIT=2"; + cl_program prog_c8 = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts_c8, + /*fatal=*/false, "fa q4_0 c8 NSG2", backend_ctx->queue); + if (prog_c8) { + cl_kernel k_c8 = clCreateKernel(prog_c8, "flash_attn_f32_q4_0_q1_vec_mq_split_c8", &err); + if (err == CL_SUCCESS) { + if (ggml_opencl_fa_kernel_fits_wg(backend_ctx, k_c8, 128, + "flash_attn_f32_q4_0_q1_vec_mq_split_c8 (g8 ns2)", dk, dv)) { + backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8_c8[{dk, dv}] = k_c8; + ggml_opencl_log_fa_kernel_spill(backend_ctx, k_c8, "flash_attn_f32_q4_0_q1_vec_mq_split_g8_c8", dk, dv); + } else { + clReleaseKernel(k_c8); + } + } + clReleaseProgram(prog_c8); + } + } + break; + } + case FA_VARIANT_F32_F16_SPLIT: { + cl_kernel k; + CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_f16", &err), err)); + backend_ctx->fa.f32_f16_split[{dk, dv}] = k; + backend_ctx->fa.f32_f16_split_wg_size[{dk, dv}] = cfg->bm * cfg->n_split; + backend_ctx->fa.f32_f16_split_nkv_threshold[{dk, dv}] = cfg->nkv_split_threshold; + break; + } + case FA_VARIANT_Q8_0_SPLIT: + case FA_VARIANT_Q4_0_SPLIT: { + const bool is_q8 = variant == FA_VARIANT_Q8_0_SPLIT; + cl_kernel k; + CL_CHECK((k = clCreateKernel(prog, is_q8 ? "flash_attn_f32_q8_0" : "flash_attn_f32_q4_0", &err), err)); + auto & split = is_q8 ? backend_ctx->fa.f32_q8_0_split : backend_ctx->fa.f32_q4_0_split; + auto & split_wg = is_q8 ? backend_ctx->fa.f32_q8_0_split_wg_size : backend_ctx->fa.f32_q4_0_split_wg_size; + auto & split_bm = is_q8 ? backend_ctx->fa.f32_q8_0_split_bm : backend_ctx->fa.f32_q4_0_split_bm; + auto & split_thresh = is_q8 ? backend_ctx->fa.f32_q8_0_split_nkv_threshold : backend_ctx->fa.f32_q4_0_split_nkv_threshold; + split[{dk, dv}] = k; + split_wg[{dk, dv}] = cfg->bm * cfg->n_split; + split_bm[{dk, dv}] = cfg->bm; + split_thresh[{dk, dv}] = 0; // quant prefill: always split + break; + } + default: + break; + } + CL_CHECK(clReleaseProgram(prog)); + return true; +} + +// Compile a quant FA split kernel with a hand-picked (BLOCK_M, N_SPLIT) that +// overrides the default fa_dims tuning, for the DK values where the default +// N_SPLIT is degenerate for quant prefill: +// DK=256: default N_SPLIT=16 leaves DK/32=8 blocks -> 0 blocks/split. +// Override N_SPLIT=8 (1 block/split), BLOCK_M=16. +// DK=96 : DK/32 = 3 blocks, not divisible by the default N_SPLIT=2 -> +// override N_SPLIT=3. BLOCK_M must be 16, not 32: the N_SPLIT=3 +// QK-partial reduction uses sub_group_shuffle, so all 3 split +// threads of a query must land in one subgroup — WG_SIZE = +// BLOCK_M*N_SPLIT must be <= the 64-lane Adreno subgroup (16*3=48). +static bool ggml_opencl_ensure_fa_quant_split_override( + ggml_backend_opencl_context * backend_ctx, + int dk, int dv, int quant_bm, int quant_n_split, bool is_q8_0 +) { + const std::pair dk_dv = {dk, dv}; + if (is_q8_0 && backend_ctx->fa.f32_q8_0_split.count(dk_dv)) { + return true; + } + if (!is_q8_0 && backend_ctx->fa.f32_q4_0_split.count(dk_dv)) { + return true; + } + + const ggml_opencl_fa_variant variant = is_q8_0 ? FA_VARIANT_Q8_0_SPLIT : FA_VARIANT_Q4_0_SPLIT; + const auto attempt_key = std::make_pair(variant, dk_dv); + if (backend_ctx->fa.variant_attempted.count(attempt_key)) { + return false; + } + + backend_ctx->fa.variant_attempted.insert(attempt_key); + + std::string shuffle_opts; + if (backend_ctx->has_subgroup_shuffle) { + shuffle_opts = backend_ctx->has_qcom_subgroup_shuffle + ? " -D cl_qcom_subgroup_shuffle=1" + : " -D cl_khr_subgroup_shuffle=1"; + } + const ggml_opencl_fa_dim * cfg = nullptr; + for (const auto & d : g_opencl_fa_dims) { + if (d.dk == dk && d.dv == dv) { + cfg = &d; break; + } + } + if (cfg == nullptr) { + return false; + } + + // BLK_PREPASS_BM is the prepass-kernel BLOCK_M, needed so the quant kernel + // indexes the blk[] classification buffer correctly. + std::string opts = backend_ctx->kernel_compile_opts + shuffle_opts + + " -D DK=" + std::to_string(dk) + + " -D DV=" + std::to_string(dv) + + " -D BLOCK_M=" + std::to_string(quant_bm) + + " -D BLOCK_N=" + std::to_string(cfg->bn) + + " -D N_SPLIT=" + std::to_string(quant_n_split) + + " -D BLK_PREPASS_BM=" + std::to_string(cfg->bm); + + const std::string src = ggml_opencl_fa_kernel_src(variant); + if (src.empty()) { + return false; + } + + const std::string tag = std::string("fa ") + (is_q8_0 ? "q8_0" : "q4_0") + + " split DK=" + std::to_string(dk); + cl_program prog = build_program_from_source_ex( + backend_ctx->context, backend_ctx->device, src.c_str(), opts, + /*fatal=*/false, tag.c_str(), backend_ctx->queue); + if (!prog) { return false; } + cl_int err; + cl_kernel k; + if (is_q8_0) { + CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_q8_0", &err), err)); + backend_ctx->fa.f32_q8_0_split[dk_dv] = k; + backend_ctx->fa.f32_q8_0_split_wg_size[dk_dv] = quant_bm * quant_n_split; + backend_ctx->fa.f32_q8_0_split_bm[dk_dv] = quant_bm; + backend_ctx->fa.f32_q8_0_split_nkv_threshold[dk_dv] = 0; + } else { + CL_CHECK((k = clCreateKernel(prog, "flash_attn_f32_q4_0", &err), err)); + backend_ctx->fa.f32_q4_0_split[dk_dv] = k; + backend_ctx->fa.f32_q4_0_split_wg_size[dk_dv] = quant_bm * quant_n_split; + backend_ctx->fa.f32_q4_0_split_bm[dk_dv] = quant_bm; + backend_ctx->fa.f32_q4_0_split_nkv_threshold[dk_dv] = 0; + } + CL_CHECK(clReleaseProgram(prog)); + return true; +} + +// Resolve the source buffer + strides for an FA KV tensor: keep the +// caller-supplied AoS buffer if non-NULL, else fall back to tensor->extra. +static void ggml_cl_flash_attn_resolve_src( + const ggml_tensor * tensor, + cl_mem & buf, + cl_ulong & offset, + cl_ulong & nb1, + cl_ulong & nb2, + cl_ulong & nb3) { + if (buf != NULL) { + return; + } + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; + GGML_ASSERT(extra && extra->data_device); + buf = extra->data_device; + offset = extra->offset + tensor->view_offs; + nb1 = tensor->nb[1]; + nb2 = tensor->nb[2]; + nb3 = tensor->nb[3]; +} + +// Read a (possibly strided-view) tensor from device into a tight host buffer. +// dim 0 is always tight; a strided view is gathered row-by-row. +static void ggml_cl_flash_attn_read_tensor_host( + ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * tensor, + cl_mem src_buffer, cl_ulong src_offset, + cl_ulong src_nb1, cl_ulong src_nb2, cl_ulong src_nb3, + size_t row_bytes, void * dst, size_t total_bytes +) { + const bool contiguous_layout = + src_nb1 == row_bytes && + src_nb2 == row_bytes * (cl_ulong) tensor->ne[1] && + src_nb3 == src_nb2 * (cl_ulong) tensor->ne[2]; + + if (contiguous_layout) { + CL_CHECK(clEnqueueReadBuffer(backend_ctx->queue, src_buffer, CL_TRUE, + src_offset, total_bytes, dst, 0, NULL, NULL)); + return; + } + + size_t dst_off = 0; + for (int64_t i3 = 0; i3 < tensor->ne[3]; ++i3) { + for (int64_t i2 = 0; i2 < tensor->ne[2]; ++i2) { + for (int64_t i1 = 0; i1 < tensor->ne[1]; ++i1) { + const cl_ulong row_src_off = src_offset + + (cl_ulong) i3 * src_nb3 + + (cl_ulong) i2 * src_nb2 + + (cl_ulong) i1 * src_nb1; + CL_CHECK(clEnqueueReadBuffer(backend_ctx->queue, src_buffer, CL_TRUE, + row_src_off, row_bytes, + (uint8_t *) dst + dst_off, 0, NULL, NULL)); + dst_off += row_bytes; + } + } + } + GGML_ASSERT(dst_off == total_bytes); +} + +// Rebuild AoS q8_0/q4_0 bytes from a SoA tensor into a temp buffer. +// Returns false if the tensor is not SoA-quantised (already AoS). +static bool ggml_cl_flash_attn_reconstruct_aos( + ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * tensor, + ggml_cl_flash_attn_temp_buffer & temp, + cl_mem & out_buf, + cl_ulong & out_offset, + cl_ulong & out_nb1, + cl_ulong & out_nb2, + cl_ulong & out_nb3 +) { + if (tensor == nullptr) { + return false; + } + const bool is_q8_0 = tensor->type == GGML_TYPE_Q8_0 && ggml_cl_is_q8_0_soa(tensor); + const bool is_q4_0 = tensor->type == GGML_TYPE_Q4_0 && ggml_cl_is_q4_0_soa(tensor); + if (!is_q8_0 && !is_q4_0) { + return false; + } + + // For views, SoA extra is on view_src (view->extra is pre-SoA). + // Noshuffle layout only applies to 2D weights, as determined by `use_adreno_kernels`, + // where ne2 == 1 and ne3 == 1 -- these are never FA inputs. + // Therefore, we use `restore_block_qk_0` kernels, not `restore_block_qk_0_noshuffle`. + const ggml_tensor * soa_src = tensor->view_src ? tensor->view_src : tensor; + cl_mem extra_q = NULL; + cl_mem extra_d = NULL; + if (is_q8_0) { + auto * e = (ggml_tensor_extra_cl_q8_0 *) soa_src->extra; + GGML_ASSERT(e && e->q && e->d); + extra_q = e->q; + extra_d = e->d; + } else { + auto * e = (ggml_tensor_extra_cl_q4_0 *) soa_src->extra; + GGML_ASSERT(e && e->q && e->d); + extra_q = e->q; + extra_d = e->d; + } + + // Reconstruct the whole parent; view offsets then work naturally. + const size_t parent_nbytes = ggml_nbytes(soa_src); + cl_int err; + temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, parent_nbytes, NULL, &err); + CL_CHECK(err); + + cl_kernel kernel = is_q8_0 ? backend_ctx->repack.kernel_restore_block_q8_0 + : backend_ctx->repack.kernel_restore_block_q4_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra_d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &temp.data)); + + const size_t n_blocks = (size_t) ggml_nelements(soa_src) / ggml_blck_size(soa_src->type); + size_t global_work_size[] = { n_blocks, 1, 1 }; + size_t local_work_size[] = { 1, 1, 1 }; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, NULL)); + + out_buf = temp.data; + out_offset = tensor->view_offs; + out_nb1 = tensor->nb[1]; + out_nb2 = tensor->nb[2]; + out_nb3 = tensor->nb[3]; + return true; +} + +// GPU dequant of a contiguous q4_0/q8_0 KV tensor to f16/f32. Caller supplies +// src_buf when reconstructing from SoA. Returns false for non-contig layouts +// (the kernel indexes blocks tightly within ne[0]) so the caller can fall back +// to the host path. +static bool ggml_cl_flash_attn_dequant_kv_gpu( + ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * tensor, + ggml_type target_type, + cl_mem in_src_buf, + cl_ulong in_src_offset, + cl_ulong in_src_nb1, + cl_ulong in_src_nb2, + cl_ulong in_src_nb3, + ggml_cl_flash_attn_temp_buffer & temp, + cl_mem & out_buf, + cl_ulong & out_offset, + cl_ulong & out_nb1, + cl_ulong & out_nb2, + cl_ulong & out_nb3 +) { + GGML_ASSERT(tensor->type == GGML_TYPE_Q8_0 || tensor->type == GGML_TYPE_Q4_0); + GGML_ASSERT(target_type == GGML_TYPE_F16 || target_type == GGML_TYPE_F32); + + const bool is_q8_0 = tensor->type == GGML_TYPE_Q8_0; + + cl_mem src_buf = in_src_buf; + cl_ulong src_offset = in_src_offset; + cl_ulong src_nb1 = in_src_nb1; + cl_ulong src_nb2 = in_src_nb2; + cl_ulong src_nb3 = in_src_nb3; + ggml_cl_flash_attn_resolve_src(tensor, src_buf, src_offset, src_nb1, src_nb2, src_nb3); + + if (tensor->nb[0] != (cl_ulong) ggml_type_size(tensor->type)) { + return false; + } + + const size_t n_blocks = (size_t) ggml_nelements(tensor) / 32; // block size is 32 + const size_t elem_size = ggml_type_size(target_type); + const size_t out_bytes = n_blocks * 32 * elem_size; + const cl_int nblk0_arg = (cl_int) (tensor->ne[0] / 32); + const cl_int ne1_arg = (cl_int) tensor->ne[1]; + const cl_int ne2_arg = (cl_int) tensor->ne[2]; + const cl_int ne3_arg = (cl_int) tensor->ne[3]; + + cl_int err; + temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, out_bytes, NULL, &err); + CL_CHECK(err); + + cl_kernel kernel; + if (target_type == GGML_TYPE_F16) { + kernel = is_q8_0 ? backend_ctx->repack.kernel_dequant_q8_0_f16_view_aos + : backend_ctx->repack.kernel_dequant_q4_0_f16_view_aos; + } else { + kernel = is_q8_0 ? backend_ctx->repack.kernel_dequant_q8_0_f32_view_aos + : backend_ctx->repack.kernel_dequant_q4_0_f32_view_aos; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &src_offset)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &src_nb1)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &src_nb2)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &src_nb3)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &nblk0_arg)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne1_arg)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne2_arg)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne3_arg)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_mem), &temp.data)); + + size_t global_ws[3] = { (size_t) nblk0_arg, (size_t) ne1_arg, (size_t) ne2_arg * (size_t) ne3_arg }; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, + global_ws, NULL, 0, NULL, NULL)); + + out_buf = temp.data; + out_offset = 0; + out_nb1 = (cl_ulong) tensor->ne[0] * elem_size; + out_nb2 = out_nb1 * (cl_ulong) tensor->ne[1]; + out_nb3 = out_nb2 * (cl_ulong) tensor->ne[2]; + return true; +} + +static bool ggml_cl_flash_attn_prepare_quantized_tensor( + ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * tensor, + ggml_type target_type, + ggml_cl_flash_attn_temp_buffer & temp, + cl_mem & data_device, + cl_ulong & offset, + cl_ulong & nb1, + cl_ulong & nb2, + cl_ulong & nb3 +) { + if (!ggml_is_quantized(tensor->type)) { + return false; + } + + // Caller-supplied AoS buffer wins over tensor->extra when present. + cl_mem src_buffer = data_device; + cl_ulong src_offset = offset; + cl_ulong src_nb1 = nb1; + cl_ulong src_nb2 = nb2; + cl_ulong src_nb3 = nb3; + ggml_cl_flash_attn_resolve_src(tensor, src_buffer, src_offset, src_nb1, src_nb2, src_nb3); + + const int64_t n = ggml_nelements(tensor); + const size_t row_bytes = (size_t) (tensor->ne[0] / ggml_blck_size(tensor->type)) * ggml_type_size(tensor->type); + // tight-packed byte count (ggml_nbytes includes stride gaps). + const size_t total_bytes = (size_t) (n / ggml_blck_size(tensor->type)) * ggml_type_size(tensor->type); + std::vector host_quant(total_bytes); + + sync_with_other_backends(backend_ctx); + ggml_cl_flash_attn_read_tensor_host(backend_ctx, tensor, src_buffer, src_offset, + src_nb1, src_nb2, src_nb3, + row_bytes, host_quant.data(), total_bytes); + + std::vector host_f32(n); + ggml_get_type_traits(tensor->type)->to_float(host_quant.data(), host_f32.data(), n); + + const size_t bytes_per_elem = ggml_type_size(target_type); + const size_t buffer_size = (size_t) n * bytes_per_elem; + + std::vector host_linear(buffer_size); + if (target_type == GGML_TYPE_F32) { + memcpy(host_linear.data(), host_f32.data(), buffer_size); + } else { + GGML_ASSERT(target_type == GGML_TYPE_F16); + ggml_fp32_to_fp16_row(host_f32.data(), (ggml_fp16_t *) host_linear.data(), n); + } + + cl_int err; + temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, buffer_size, NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer(backend_ctx->queue, temp.data, CL_TRUE, 0, buffer_size, host_linear.data(), 0, NULL, NULL)); + + data_device = temp.data; + offset = 0; + nb1 = (cl_ulong) (tensor->ne[0] * bytes_per_elem); + nb2 = (cl_ulong) (tensor->ne[1] * nb1); + nb3 = (cl_ulong) (tensor->ne[2] * nb2); + + static bool warned = false; + if (!warned) { + GGML_LOG_WARN("ggml_opencl: OpenCL flash attention dequantizes GPU-resident quantized KV cache into temporary linear buffers; performance may be poor\n"); + warned = true; + } + + return true; +} + +// Host-side F16 -> F32 for the asymmetric-KV F32 fallback path. +static bool ggml_cl_flash_attn_convert_f16_to_f32( + ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * tensor, + ggml_cl_flash_attn_temp_buffer & temp, + cl_mem & data_device, + cl_ulong & offset, + cl_ulong & nb1, + cl_ulong & nb2, + cl_ulong & nb3 +) { + if (tensor->type != GGML_TYPE_F16) { + return false; + } + + cl_mem src_buffer = data_device; + cl_ulong src_offset = offset; + cl_ulong src_nb1 = nb1; + cl_ulong src_nb2 = nb2; + cl_ulong src_nb3 = nb3; + ggml_cl_flash_attn_resolve_src(tensor, src_buffer, src_offset, src_nb1, src_nb2, src_nb3); + + const int64_t n = ggml_nelements(tensor); + const size_t row_bytes = (size_t) tensor->ne[0] * sizeof(ggml_fp16_t); + const size_t total_bytes = (size_t) n * sizeof(ggml_fp16_t); + std::vector host_f16(total_bytes); + + sync_with_other_backends(backend_ctx); + ggml_cl_flash_attn_read_tensor_host(backend_ctx, tensor, src_buffer, src_offset, + src_nb1, src_nb2, src_nb3, + row_bytes, host_f16.data(), total_bytes); + + std::vector host_f32(n); + ggml_fp16_to_fp32_row((const ggml_fp16_t *) host_f16.data(), host_f32.data(), n); + + const size_t f32_bytes = (size_t) n * sizeof(float); + cl_int err; + temp.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, f32_bytes, NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer(backend_ctx->queue, temp.data, CL_TRUE, 0, + f32_bytes, host_f32.data(), 0, NULL, NULL)); + + data_device = temp.data; + offset = 0; + nb1 = (cl_ulong) (tensor->ne[0] * sizeof(float)); + nb2 = (cl_ulong) (tensor->ne[1] * nb1); + nb3 = (cl_ulong) (tensor->ne[2] * nb2); + + static bool warned = false; + if (!warned) { + GGML_LOG_WARN("ggml_opencl: OpenCL flash attention asymmetric KV converts an F16 cache to F32 host-side; performance may be poor\n"); + warned = true; + } + + return true; +} + +// Flash-Decoding (K-split) dispatch thresholds. FD fires for non-causal +// attention with n_kv >= FD_MIN_N_KV and d_head <= FD_MAX_DK; the KV range is +// split into ~n_kv/FD_KV_PER_SPLIT partials, clamped to [FD_MIN_SPLITS, +// FD_MAX_SPLITS]. Multi-query FD is restricted to small heads +// (d_head <= FD_MAX_DK_MULTI) and capped at FD_MAX_N_Q_MULTI queries. +static constexpr int FD_MIN_N_KV = 2048; +static constexpr int FD_KV_PER_SPLIT = 2048; +// f16 KV decode wants more splits than the 2048 default; quantized KV keeps 2048. +static constexpr int FD_KV_PER_SPLIT_F16 = 512; +static constexpr int FD_MIN_SPLITS = 2; +static constexpr int FD_MAX_SPLITS = 16; +static constexpr int FD_MAX_DK = 128; +static constexpr int FD_MAX_DK_MULTI = 64; +static constexpr int FD_MAX_N_Q_MULTI = 8; +// MQ FD split-groups have few subgroups (MQ_NSG_SPLIT), so use a smaller +// kv_per_split to keep the softmax recurrence short; non-MQ keeps FD_KV_PER_SPLIT. +static constexpr int FD_MQ_KV_PER_SPLIT = 256; +static constexpr int FD_MQ_MAX_SPLITS = 128; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +struct ggml_cl_adreno_xmem_attn_schedule { + int qk_lws0 = 256; + int qk_lws2 = 1; + int softmax_reduce_lws0 = 256; + int softmax_apply_lws0 = 64; + int softmax_apply_lws2 = 4; + int pv_lws0 = 64; + int pv_lws2 = 4; +}; + +static inline size_t ggml_cl_round_up(size_t x, size_t a) { + return ((x + a - 1) / a) * a; +} + +static inline int ggml_cl_round_up_div(int x, int y) { + return (x + y - 1) / y; +} + +static inline void ggml_cl_set_arg_int4(cl_kernel kernel, cl_uint index, int x, int y, int z, int w) { + struct { int x, y, z, w; } value { x, y, z, w }; + CL_CHECK(clSetKernelArg(kernel, index, sizeof(value), &value)); +} + +static cl_mem ggml_cl_make_image2d_half4(cl_context context, cl_mem_flags flags, size_t width, size_t height) { + cl_int err = CL_SUCCESS; + cl_image_format format = { CL_RGBA, CL_HALF_FLOAT }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE2D; + desc.image_width = width; + desc.image_height = height; + cl_mem image = clCreateImage(context, flags, &format, &desc, nullptr, &err); + CL_CHECK(err); + return image; +} + +static cl_mem ggml_cl_make_image1d_buffer_half4(cl_context context, cl_mem_flags flags, size_t width, cl_mem backing_buffer) { + cl_int err = CL_SUCCESS; + cl_image_format format = { CL_RGBA, CL_HALF_FLOAT }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = width; + desc.buffer = backing_buffer; + cl_mem image = clCreateImage(context, flags, &format, &desc, nullptr, &err); + CL_CHECK(err); + return image; +} + +static void ggml_cl_release_mem(cl_mem & mem) { + if (mem != nullptr) { + CL_CHECK(clReleaseMemObject(mem)); + mem = nullptr; + } +} + +void ggml_cl_adreno_xmem_attn_release_scratch(ggml_backend_opencl_context * backend_ctx) { + auto & s = backend_ctx->adreno_xmem_attn.scratch; + ggml_cl_release_mem(s.q_img); + ggml_cl_release_mem(s.k_img); + ggml_cl_release_mem(s.v_img); + ggml_cl_release_mem(s.out_img); + ggml_cl_release_mem(s.k_transpose_img1d); + ggml_cl_release_mem(s.k_transpose_buf); + ggml_cl_release_mem(s.k_packed_buf); + ggml_cl_release_mem(s.v_packed_buf); + ggml_cl_release_mem(s.score_img1d); + ggml_cl_release_mem(s.prob_img1d); + ggml_cl_release_mem(s.score_buf); + ggml_cl_release_mem(s.prob_buf); + ggml_cl_release_mem(s.softmax_stats_img2d); + ggml_cl_release_mem(s.xmem_qk); + ggml_cl_release_mem(s.xmem_pv); + s = {}; +} + +static ggml_cl_adreno_xmem_attn_schedule ggml_cl_adreno_xmem_attn_select_schedule( + const ggml_backend_opencl_context * backend_ctx, + int n_q, + int n_kv, + int heads_total, + int q_width, + int gqa_ratio) { + const bool big_h = heads_total >= 8; + ggml_cl_adreno_xmem_attn_schedule sched; + + if (gqa_ratio == 1) { + if (n_q >= 512) { sched.qk_lws0 = 512; } + else if (n_q >= 256) { sched.qk_lws0 = 128; } + else { sched.qk_lws0 = 64; } + sched.qk_lws2 = (big_h && n_q >= 512) ? 2 : 1; + } else { + if (q_width >= 2048) { sched.qk_lws0 = 512; } + else if (q_width >= 256) { sched.qk_lws0 = 128; } + else { sched.qk_lws0 = 64; } + sched.qk_lws2 = MIN(8, (int) backend_ctx->max_workgroup_size / sched.qk_lws0); + } + + if (n_kv >= 2048) { sched.softmax_reduce_lws0 = 1024; } + else if (n_kv >= 512) { sched.softmax_reduce_lws0 = big_h ? 256 : 512; } + else { sched.softmax_reduce_lws0 = 256; } + + if (n_kv < 256) { sched.softmax_apply_lws0 = 64; } + else { sched.softmax_apply_lws0 = big_h ? 128 : 64; } + sched.softmax_apply_lws2 = n_kv >= 512 ? 8 : 4; + + if (n_q < 256) { sched.pv_lws0 = 64; } + else { sched.pv_lws0 = big_h ? 128 : 64; } + sched.pv_lws2 = big_h ? 8 : (n_q <= 256 ? 8 : 4); + + const int max_wg = (int) backend_ctx->max_workgroup_size; + auto fix = [&](int & l0, int & l2) { + while (l0 * l2 > max_wg) { + if (l2 > 1) { l2 /= 2; } + else if (l0 > 32) { l0 /= 2; } + else { break; } + } + }; + fix(sched.qk_lws0, sched.qk_lws2); + fix(sched.softmax_apply_lws0, sched.softmax_apply_lws2); + fix(sched.pv_lws0, sched.pv_lws2); + while (sched.softmax_reduce_lws0 > max_wg) { + sched.softmax_reduce_lws0 /= 2; + } + + return sched; +} + +static bool ggml_cl_adreno_xmem_attn_prepare( + ggml_backend_opencl_context * backend_ctx, + int n_q, + int n_kv, + int d_head_q, + int d_head_v, + int n_head, + int n_head_kv, + int n_batch) { + auto & s = backend_ctx->adreno_xmem_attn.scratch; + const int gqa_ratio = n_head / n_head_kv; + const int q_width = n_q * gqa_ratio; + const int kv_heads_total = n_head_kv * n_batch; + const int n_kv_padded = (int) ggml_cl_round_up((size_t) n_kv, 32); + if (s.q_img != nullptr && + s.n_q == n_q && + s.n_kv == n_kv && + s.n_kv_padded == n_kv_padded && + s.d_head_q == d_head_q && + s.d_head_v == d_head_v && + s.q_width == q_width && + s.kv_heads_total == kv_heads_total) { + return true; + } + + ggml_cl_adreno_xmem_attn_release_scratch(backend_ctx); + + const int qpack = d_head_q / 4; + const int vpack = d_head_v / 4; + const int npack = n_kv_padded / 4; + const size_t q_img_h = (size_t) kv_heads_total * qpack; + const size_t v_img_h = (size_t) kv_heads_total * vpack; + + s.q_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) q_width, q_img_h); + s.k_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) n_kv_padded, q_img_h); + s.v_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) n_kv_padded, v_img_h); + s.out_img = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, (size_t) q_width, v_img_h); + + const size_t k_transpose_half4_elems = (size_t) npack * kv_heads_total * d_head_q; + s.k_transpose_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, k_transpose_half4_elems * sizeof(uint16_t) * 4, nullptr, nullptr); + GGML_ASSERT(s.k_transpose_buf != nullptr); + s.k_transpose_img1d = ggml_cl_make_image1d_buffer_half4(backend_ctx->context, CL_MEM_READ_ONLY, k_transpose_half4_elems, s.k_transpose_buf); + + const size_t k_groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_q, 16); + const size_t v_groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_v, 16); + const size_t k_packed_half4_elems = (size_t) n_kv_padded * k_groups16 * 4; + const size_t v_packed_half4_elems = (size_t) n_kv_padded * v_groups16 * 4; + s.k_packed_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, k_packed_half4_elems * sizeof(uint16_t) * 4, nullptr, nullptr); + s.v_packed_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, v_packed_half4_elems * sizeof(uint16_t) * 4, nullptr, nullptr); + GGML_ASSERT(s.k_packed_buf != nullptr && s.v_packed_buf != nullptr); + + const size_t score_half4_elems = (size_t) npack * kv_heads_total * q_width; + const size_t score_bytes = score_half4_elems * sizeof(uint16_t) * 4; + s.score_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, score_bytes, nullptr, nullptr); + s.prob_buf = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, score_bytes, nullptr, nullptr); + GGML_ASSERT(s.score_buf != nullptr && s.prob_buf != nullptr); + s.score_img1d = ggml_cl_make_image1d_buffer_half4(backend_ctx->context, CL_MEM_READ_ONLY, score_half4_elems, s.score_buf); + s.prob_img1d = ggml_cl_make_image1d_buffer_half4(backend_ctx->context, CL_MEM_READ_ONLY, score_half4_elems, s.prob_buf); + s.softmax_stats_img2d = ggml_cl_make_image2d_half4(backend_ctx->context, CL_MEM_READ_WRITE, + (size_t) q_width, (size_t) kv_heads_total); + s.xmem_qk = clCreateBuffer(backend_ctx->context, CL_MEM_READ_ONLY, 6144, nullptr, nullptr); + s.xmem_pv = clCreateBuffer(backend_ctx->context, CL_MEM_READ_ONLY, 6144, nullptr, nullptr); + GGML_ASSERT(s.softmax_stats_img2d != nullptr && s.xmem_qk != nullptr && s.xmem_pv != nullptr); + + s.n_q = n_q; + s.n_kv = n_kv; + s.n_kv_padded = n_kv_padded; + s.d_head_q = d_head_q; + s.d_head_v = d_head_v; + s.q_width = q_width; + s.kv_heads_total = kv_heads_total; + return true; +} + +static bool ggml_cl_adreno_xmem_attn_can_use( + const ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * q, + const ggml_tensor * k, + const ggml_tensor * dst) { + static const char * xmem_sdpa_env = getenv("GGML_OPENCL_XMEM_SDPA"); + if (xmem_sdpa_env == nullptr || xmem_sdpa_env[0] == '0') { + return false; + } + + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + + if (!backend_ctx->adreno_xmem_attn.compiled || backend_ctx->gpu_family != GPU_FAMILY::ADRENO) { + return false; + } + if (q->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || + (k->type != GGML_TYPE_F16 && k->type != GGML_TYPE_F32) || + (v->type != GGML_TYPE_F16 && v->type != GGML_TYPE_F32)) { + return false; + } + if (sinks != nullptr) { + return false; + } + if (q->nb[0] != ggml_type_size(q->type) || k->nb[0] != ggml_type_size(k->type) || + v->nb[0] != ggml_type_size(v->type) || dst->nb[0] != ggml_type_size(dst->type)) { + return false; + } + if (mask != nullptr && (mask->type != GGML_TYPE_F16 || mask->nb[0] != sizeof(ggml_fp16_t))) { + return false; + } + + const int n_q = q->ne[1]; + const int n_kv = k->ne[1]; + const int d_head_q = q->ne[0]; + const int d_head_v = v->ne[0]; + const int n_head = q->ne[2]; + const int n_head_kv = k->ne[2]; + const int n_batch = q->ne[3]; + + if (n_q <= 1 || n_kv <= 0 || n_kv > 8192) { + return false; + } + if (d_head_q != k->ne[0] || d_head_v != v->ne[0] || k->ne[1] != v->ne[1] || k->ne[3] != v->ne[3]) { + return false; + } + if (q->ne[3] != k->ne[3]) { + return false; + } + if (n_head_kv <= 0 || n_head % n_head_kv != 0 || k->ne[2] != v->ne[2]) { + return false; + } + if (dst->ne[0] != d_head_v || dst->ne[1] != n_head || dst->ne[2] != n_q || dst->ne[3] != n_batch) { + return false; + } + if ((d_head_q % 8) != 0 || (d_head_v % 32) != 0) { + return false; + } + if (mask != nullptr && + (mask->ne[0] < n_kv || mask->ne[1] < n_q || mask->ne[2] <= 0 || mask->ne[3] <= 0)) { + return false; + } + + float params[3]; + memcpy(params, dst->op_params, sizeof(params)); + if (params[1] != 0.0f || params[2] != 0.0f) { + return false; + } + + const int gqa_ratio = n_head / n_head_kv; + const int q_width = n_q * gqa_ratio; + const int kv_heads_total = n_head_kv * n_batch; + const int n_kv_padded = (int) ggml_cl_round_up((size_t) n_kv, 32); + const int qpack = d_head_q / 4; + const int vpack = d_head_v / 4; + const int npack = n_kv_padded / 4; + + if ((size_t) q_width > backend_ctx->image2d_max_width || + (size_t) n_kv_padded > backend_ctx->image2d_max_width) { + return false; + } + if ((size_t) kv_heads_total * (size_t) qpack > backend_ctx->image2d_max_height || + (size_t) kv_heads_total * (size_t) vpack > backend_ctx->image2d_max_height) { + return false; + } + if ((size_t) npack * (size_t) kv_heads_total * (size_t) d_head_q > backend_ctx->image_max_buffer_size || + (size_t) npack * (size_t) kv_heads_total * (size_t) q_width > backend_ctx->image_max_buffer_size) { + return false; + } + + return true; +} + +static void ggml_cl_adreno_xmem_attn_run( + ggml_backend_t backend, + const ggml_tensor * q, + const ggml_tensor * k, + ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto & xstate = backend_ctx->adreno_xmem_attn; + auto & s = xstate.scratch; + if (!xstate.logged) { + GGML_LOG_INFO("ggml_opencl: using Adreno xmem attention path\n"); + xstate.logged = true; + } + + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + + ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *) q->extra; + ggml_tensor_extra_cl * extra_k = (ggml_tensor_extra_cl *) k->extra; + ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *) v->extra; + ggml_tensor_extra_cl * extra_o = (ggml_tensor_extra_cl *) dst->extra; + ggml_tensor_extra_cl * extra_mask = mask ? (ggml_tensor_extra_cl *) mask->extra : nullptr; + + const cl_ulong offset_q = extra_q->offset + q->view_offs; + const cl_ulong offset_k = extra_k->offset + k->view_offs; + const cl_ulong offset_v = extra_v->offset + v->view_offs; + const cl_ulong offset_o = extra_o->offset + dst->view_offs; + const cl_ulong offset_mask = extra_mask ? extra_mask->offset + mask->view_offs : 0; + + const int n_q = q->ne[1]; + const int n_kv = k->ne[1]; + const int d_head_q = q->ne[0]; + const int d_head_v = v->ne[0]; + const int n_head = q->ne[2]; + const int n_head_kv = k->ne[2]; + const int n_batch = q->ne[3]; + const int heads_total = n_head * n_batch; + const int gqa_ratio = n_head / n_head_kv; + const int q_width = n_q * gqa_ratio; + const int kv_heads_total = n_head_kv * n_batch; + const int n_kv_padded = (int) ggml_cl_round_up((size_t) n_kv, 32); + const int qpack = d_head_q / 4; + const int opack = d_head_v / 4; + const int npack = n_kv_padded / 4; + const float scale = ((const float *) dst->op_params)[0]; + + GGML_ASSERT(ggml_cl_adreno_xmem_attn_prepare( + backend_ctx, n_q, n_kv, d_head_q, d_head_v, n_head, n_head_kv, n_batch)); + const ggml_cl_adreno_xmem_attn_schedule sched = + ggml_cl_adreno_xmem_attn_select_schedule( + backend_ctx, n_q, n_kv_padded, heads_total, q_width, gqa_ratio); + + { + size_t gws[3] = {ggml_cl_round_up((size_t) n_q, 8), (size_t) heads_total, (size_t) qpack}; + size_t lws[3] = {8, 1, (size_t) ((qpack <= 32) ? qpack : 1)}; + cl_kernel kernel = xstate.kernel_q_f32_to_img_scaled; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_q->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.q_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &d_head_q)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &n_batch)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &q->nb[1])); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &q->nb[2])); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &q->nb[3])); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + { + size_t gws[3] = {(size_t) n_kv_padded, (size_t) kv_heads_total, (size_t) qpack}; + size_t lws[3] = {8, 1, (size_t) ((qpack <= 32) ? qpack : 1)}; + cl_kernel kernel = k->type == GGML_TYPE_F16 ? + xstate.kernel_kv_f16_to_img_gqa : xstate.kernel_kv_f32_to_img_gqa; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_k->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_k)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.k_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &d_head_q)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_kv_padded)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_batch)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &k->nb[1])); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &k->nb[2])); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &k->nb[3])); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + { + size_t gws[3] = {(size_t) n_kv_padded, (size_t) kv_heads_total, (size_t) opack}; + size_t lws[3] = {8, 1, (size_t) ((opack <= 32) ? opack : 1)}; + cl_kernel kernel = v->type == GGML_TYPE_F16 ? + xstate.kernel_kv_f16_to_img_gqa : xstate.kernel_kv_f32_to_img_gqa; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.v_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &d_head_v)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_kv_padded)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_batch)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &v->nb[1])); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &v->nb[2])); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &v->nb[3])); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + { + size_t gws[3] = {(size_t) d_head_q, (size_t) kv_heads_total, (size_t) npack}; + size_t lws[3] = {(size_t) MIN(64, d_head_q), (size_t) (kv_heads_total >= 2 ? 2 : 1), (size_t) MIN(8, npack)}; + if (lws[0] * lws[1] * lws[2] > backend_ctx->max_workgroup_size) { + lws[1] = 1; + } + cl_kernel kernel = xstate.kernel_k_gather; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.k_transpose_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.k_img)); + ggml_cl_set_arg_int4(kernel, 2, n_kv_padded, kv_heads_total, npack, d_head_q); + ggml_cl_set_arg_int4(kernel, 3, qpack, 0, 0, 0); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + { + const size_t groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_q, 16); + const size_t packed_linear = (size_t) n_kv_padded * groups16; + const size_t lws0 = MIN((size_t) 1024, backend_ctx->max_workgroup_size); + size_t gws[3] = {ggml_cl_round_up(packed_linear, lws0), 1, 1}; + size_t lws[3] = {lws0, 1, 1}; + cl_kernel kernel = xstate.kernel_pack_k; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.k_packed_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.k_transpose_img1d)); + ggml_cl_set_arg_int4(kernel, 2, 8, (int) packed_linear, qpack, d_head_q); + ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, kv_heads_total, kv_heads_total, npack); + ggml_cl_set_arg_int4(kernel, 4, d_head_q, 0, 0, 0); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + { + size_t lws[3] = {(size_t) sched.qk_lws0, 1, (size_t) sched.qk_lws2}; + const int slices_per_group = sched.qk_lws2 * 8; + const size_t groups_z = (size_t) ggml_cl_round_up_div(npack, slices_per_group); + const size_t groups_x = (size_t) ggml_cl_round_up_div(q_width, sched.qk_lws0); + size_t gws[3] = { + lws[0] * groups_z, + groups_x, + (size_t) kv_heads_total * lws[2], + }; + + cl_kernel kernel = xstate.kernel_qk_gemm; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.score_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.k_packed_buf)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.xmem_qk)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &s.q_img)); + ggml_cl_set_arg_int4(kernel, 4, kv_heads_total, npack, q_width, 32); + ggml_cl_set_arg_int4(kernel, 5, qpack, 0, 0, kv_heads_total); + ggml_cl_set_arg_int4(kernel, 6, qpack, 1, 1, 0); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + cl_mem softmax_input_img = s.score_img1d; + cl_mem softmax_output_buf = s.prob_buf; + cl_mem pv_prob_img = s.prob_img1d; + + if (mask != nullptr) { + const cl_ulong mask_nb1 = mask->nb[1]; + const cl_ulong mask_nb2 = mask->nb[2]; + const cl_ulong mask_nb3 = mask->nb[3]; + const int mask_ne2 = mask->ne[2]; + const int mask_ne3 = mask->ne[3]; + size_t lws[3] = {(size_t) sched.softmax_apply_lws0, 1, (size_t) sched.softmax_apply_lws2}; + size_t gws[3] = { + ggml_cl_round_up((size_t) q_width, lws[0]), + (size_t) kv_heads_total, + ggml_cl_round_up((size_t) npack, lws[2]), + }; + cl_kernel kernel = xstate.kernel_mask_scores; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.prob_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.score_img1d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_mask->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_mask)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &q_width)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_kv_padded)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &kv_heads_total)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &mask_nb2)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &mask_nb3)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &mask_ne2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &mask_ne3)); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + + softmax_input_img = s.prob_img1d; + softmax_output_buf = s.score_buf; + pv_prob_img = s.score_img1d; + } + + { + size_t lws[3] = {(size_t) sched.softmax_reduce_lws0, 1, 1}; + size_t gws[3] = {ggml_cl_round_up((size_t) q_width, lws[0]), (size_t) kv_heads_total, 1}; + cl_kernel kernel = xstate.kernel_softmax_reduce_basic; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &softmax_input_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.softmax_stats_img2d)); + ggml_cl_set_arg_int4(kernel, 2, kv_heads_total, 1, q_width, n_kv); + ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, q_width, 0, 0); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + { + size_t lws[3] = {(size_t) sched.softmax_apply_lws0, 1, (size_t) sched.softmax_apply_lws2}; + size_t gws[3] = { + ggml_cl_round_up((size_t) q_width, lws[0]), + (size_t) kv_heads_total, + ggml_cl_round_up((size_t) npack, lws[2]), + }; + cl_kernel kernel = xstate.kernel_softmax_apply_basic; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &softmax_output_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &softmax_input_img)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.softmax_stats_img2d)); + ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, npack, q_width, 1); + ggml_cl_set_arg_int4(kernel, 4, kv_heads_total, q_width, n_kv, 0); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + { + const size_t groups16 = (size_t) ggml_cl_round_up_div(kv_heads_total * d_head_v, 16); + const size_t packed_linear = (size_t) n_kv_padded * groups16; + const size_t lws0 = MIN((size_t) 1024, backend_ctx->max_workgroup_size); + size_t gws[3] = {ggml_cl_round_up(packed_linear, lws0), 1, 1}; + size_t lws[3] = {lws0, 1, 1}; + cl_kernel kernel = xstate.kernel_pack_v; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.v_packed_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.v_img)); + ggml_cl_set_arg_int4(kernel, 2, 8, (int) packed_linear, npack, n_kv_padded); + ggml_cl_set_arg_int4(kernel, 3, kv_heads_total, kv_heads_total, opack, 0); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + { + size_t lws[3] = {(size_t) sched.pv_lws0, 1, (size_t) sched.pv_lws2}; + const int blocks = ggml_cl_round_up_div(opack, 8); + const size_t groups_z = (size_t) ggml_cl_round_up_div(blocks, sched.pv_lws2); + const size_t groups_x = (size_t) ggml_cl_round_up_div(q_width, sched.pv_lws0); + size_t gws[3] = { + lws[0] * groups_z, + groups_x, + (size_t) kv_heads_total * lws[2], + }; + + cl_kernel kernel = xstate.kernel_pv_gemm; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &s.v_packed_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s.xmem_pv)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &pv_prob_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &s.out_img)); + ggml_cl_set_arg_int4(kernel, 4, kv_heads_total, opack, q_width, 32); + ggml_cl_set_arg_int4(kernel, 5, npack, 0, 0, kv_heads_total); + ggml_cl_set_arg_int4(kernel, 6, kv_heads_total * q_width, npack, q_width, 1); + ggml_cl_set_arg_int4(kernel, 7, 1, 0, 0, 0); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + { + size_t gws[3] = {ggml_cl_round_up((size_t) n_q, 8), (size_t) heads_total, (size_t) opack}; + size_t lws[3] = {8, 1, (size_t) ((opack <= 32) ? opack : 1)}; + cl_kernel kernel = xstate.kernel_img_to_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_o->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_o)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s.out_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &d_head_v)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &n_batch)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &dst->nb[1])); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &dst->nb[2])); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &dst->nb[3])); + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } +} + +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_flash_attn_prefill_bin(ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst) { + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + GGML_ASSERT(q->extra); + GGML_ASSERT(k->extra); + GGML_ASSERT(v->extra); + GGML_ASSERT(dst->extra); + if (mask) { + GGML_ASSERT(mask->extra); + } + if (sinks) { + GGML_ASSERT(sinks->extra); + } + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + cl_context context = backend_ctx->context; + + const int n_q = q->ne[1]; + const int n_kv = k->ne[1]; + const int d_head_q = q->ne[0]; + const int d_head_v = v->ne[0]; + const int n_head = q->ne[2]; + const int n_head_kv = k->ne[2]; + const int n_batch = q->ne[3]; + + const std::pair dk_dv = {d_head_q, d_head_v}; + cl_kernel kernel = backend_ctx->fa.kernel_flash_attn_f32_f16_bin; + GGML_ASSERT(kernel != NULL); + + ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *)q->extra; + ggml_tensor_extra_cl * extra_k = (ggml_tensor_extra_cl *)k->extra; + ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; + ggml_tensor_extra_cl * extra_o = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl * extra_mask = mask ? (ggml_tensor_extra_cl *)mask->extra : NULL; + ggml_tensor_extra_cl * extra_sinks = sinks ? (ggml_tensor_extra_cl *)sinks->extra : NULL; + + cl_ulong offset_q = extra_q->offset + q->view_offs; + cl_ulong offset_o = extra_o->offset + dst->view_offs; + + cl_mem mask_buffer = extra_mask ? extra_mask->data_device : NULL; + cl_ulong offset_mask = extra_mask ? extra_mask->offset + mask->view_offs : 0; + cl_mem sinks_buffer = extra_sinks ? extra_sinks->data_device : NULL; + cl_ulong offset_sinks = extra_sinks ? extra_sinks->offset + sinks->view_offs : 0; + + const cl_ulong q_nb1 = q->nb[1]; + const cl_ulong q_nb2 = q->nb[2]; + const cl_ulong q_nb3 = q->nb[3]; + + cl_mem k_data_device = extra_k->data_device; + cl_ulong offset_k = extra_k->offset + k->view_offs; + cl_ulong k_nb1 = k->nb[1]; + cl_ulong k_nb2 = k->nb[2]; + cl_ulong k_nb3 = k->nb[3]; + + cl_mem v_data_device = extra_v->data_device; + cl_ulong offset_v = extra_v->offset + v->view_offs; + cl_ulong v_nb1 = v->nb[1]; + cl_ulong v_nb2 = v->nb[2]; + cl_ulong v_nb3 = v->nb[3]; + + const cl_ulong o_nb1 = dst->nb[1]; + const cl_ulong o_nb2 = dst->nb[2]; + const cl_ulong o_nb3 = dst->nb[3]; + + const cl_ulong mask_nb1 = mask ? mask->nb[1] : 0; + const cl_ulong mask_nb2 = mask ? mask->nb[2] : 0; + const cl_ulong mask_nb3 = mask ? mask->nb[3] : 0; + const int mask_ne2 = mask ? mask->ne[2] : 0; + const int mask_ne3 = mask ? mask->ne[3] : 0; + + float * params = (float *)dst->op_params; + float scale = params[0]; + float max_bias = params[1]; + float logit_softcap = params[2]; + + const int is_causal = (mask == NULL && n_q > 1 && n_q == n_kv); // redundant n_q > 1 check ? + + const int n_head_log2_val = n_head > 0 ? 1u << (int)floorf(log2f((float)n_head)) : 0; + const float n_head_log2_f = n_head_log2_val > 0 ? (float)n_head_log2_val : 1.0f; + const float m0 = powf(2.0f, -(max_bias) / n_head_log2_f); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2_f); + + const bool is_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0; + + ggml_cl_flash_attn_temp_buffer temp_k; + ggml_cl_flash_attn_temp_buffer temp_v; + ggml_cl_flash_attn_temp_buffer temp_k_aos; + ggml_cl_flash_attn_temp_buffer temp_v_aos; + + if (is_q8_0) { + ggml_cl_flash_attn_reconstruct_aos( + backend_ctx, k, temp_k_aos, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); + + ggml_cl_flash_attn_reconstruct_aos( + backend_ctx, v, temp_v_aos, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); + + bool k_done = ggml_cl_flash_attn_dequant_kv_gpu( + backend_ctx, k, GGML_TYPE_F16, k_data_device, offset_k, k_nb1, k_nb2, k_nb3, + temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); + + bool v_done = ggml_cl_flash_attn_dequant_kv_gpu( + backend_ctx, v, GGML_TYPE_F16, v_data_device, offset_v, v_nb1, v_nb2, v_nb3, + temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); + + GGML_ASSERT(k_done && v_done); + } + + // Allocate input/output memory buffers + cl_mem mem_matrixQ; + cl_mem mem_matrixK; + cl_mem mem_matrixV; + cl_mem mem_matrixO; + cl_buffer_region region; + cl_int err; + + region.origin = offset_q; + region.size = ggml_nbytes(q); + mem_matrixQ = clCreateSubBuffer(extra_q->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + region.origin = offset_k; + region.size = is_q8_0 ? (size_t) k_nb3 * (size_t) k->ne[3] : ggml_nbytes(k); + mem_matrixK = clCreateSubBuffer(k_data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + region.origin = offset_v; + region.size = is_q8_0 ? (size_t) v_nb3 * (size_t) v->ne[3] : ggml_nbytes(v); + mem_matrixV = clCreateSubBuffer(v_data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + region.origin = offset_o; + region.size = ggml_nbytes(dst); + mem_matrixO = clCreateSubBuffer(extra_o->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt_1d = { CL_RGBA, CL_FLOAT}; + cl_image_desc img_desc_1d; + + // use image 1d buffer used as fallback when on mask is applied + cl_mem mem_tex_mask_fallback_1dbuf; + img_fmt_1d = { CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc_1d, 0, sizeof(img_desc_1d)); + img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc_1d.image_width = 1; + img_desc_1d.buffer = mem_matrixK; + mem_tex_mask_fallback_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &err); + CL_CHECK(err); + + cl_mem mem_tex_matrixO_1dbuf; + img_fmt_1d = { CL_RGBA, CL_FLOAT}; + memset(&img_desc_1d, 0, sizeof(img_desc_1d)); + img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc_1d.image_width = ggml_nbytes(dst) / 4 / 4; + img_desc_1d.buffer = mem_matrixO; + mem_tex_matrixO_1dbuf = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &err); + CL_CHECK(err); + + // The bin kernel requires 2d (or 3d) buffers packed for data loading/multiplication. + // These repack kernels launch across all buffers to ensure compatibility + cl_mem mem_tex_matrixMask_1dbuf = NULL; + cl_mem mem_matrixMask = NULL; + cl_mem mem_matrixMask_padded = NULL; + cl_ulong mask_nb1_padded = mask_nb1, mask_nb2_padded = mask_nb2, mask_nb3_padded = mask_nb3; + if (extra_mask) { + // allocate mem_matrixMask w/ new padded size + size_t n_kv_padded = GGML_PAD(n_kv, 4); + size_t mask_nb_padded = n_kv_padded * sizeof(cl_half) * mask->ne[1] * mask->ne[2] * mask->ne[3]; + + // apply offset and create subBuffer for mask + region.origin = offset_mask; + region.size = ggml_nbytes(mask); + mem_matrixMask = clCreateSubBuffer(extra_mask->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + { + // create padded mask to contain all data + mem_matrixMask_padded = clCreateBuffer(context, CL_MEM_ALLOC_HOST_PTR, mask_nb_padded, NULL, &err); + CL_CHECK(err); + + // pass extra_mask->data_device, mem_matrixMask to kernel for copying/padding + mask_nb1_padded = (cl_ulong)n_kv_padded * sizeof(cl_half); + mask_nb2_padded = mask_nb1_padded * (cl_ulong)mask->ne[1]; + mask_nb3_padded = mask_nb2_padded * (cl_ulong)mask->ne[2]; + + cl_kernel repack_mask = backend_ctx->fa.kernel_repack_mask_for_wmm; + CL_CHECK(clSetKernelArg(repack_mask, 0, sizeof(cl_mem), &mem_matrixMask)); + CL_CHECK(clSetKernelArg(repack_mask, 1, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(repack_mask, 2, sizeof(cl_ulong), &mask_nb2)); + CL_CHECK(clSetKernelArg(repack_mask, 3, sizeof(cl_ulong), &mask_nb3)); + CL_CHECK(clSetKernelArg(repack_mask, 4, sizeof(int), &mask_ne2)); + CL_CHECK(clSetKernelArg(repack_mask, 5, sizeof(cl_mem), &mem_matrixMask_padded)); + CL_CHECK(clSetKernelArg(repack_mask, 6, sizeof(cl_ulong), &mask_nb1_padded)); + CL_CHECK(clSetKernelArg(repack_mask, 7, sizeof(cl_ulong), &mask_nb2_padded)); + CL_CHECK(clSetKernelArg(repack_mask, 8, sizeof(cl_ulong), &mask_nb3_padded)); + + size_t repack_mask_gws[3] = {(size_t)n_kv, (size_t)mask->ne[1], (size_t)mask_ne2 * (size_t)mask->ne[3]}; + backend_ctx->enqueue_ndrange_kernel(repack_mask, 3, repack_mask_gws, NULL, dst); + } + + // use image 1d buffer for matrix Mask (padded row stride) + cl_image_format img_fmt_mask_1d = { CL_RGBA, CL_HALF_FLOAT}; + cl_image_desc img_desc_mask_1d; + memset(&img_desc_mask_1d, 0, sizeof(img_desc_mask_1d)); + img_desc_mask_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc_mask_1d.image_width = mask_nb_padded / 2 / 4; + img_desc_mask_1d.buffer = mem_matrixMask_padded; + mem_tex_matrixMask_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_mask_1d, &img_desc_mask_1d, NULL, &err); + CL_CHECK(err); + } + + // WMM QK uses repacked 3D images. + // Q image: rows, heads, packed depth. + cl_image_format img_fmt_3d = { CL_RGBA, CL_HALF_FLOAT }; + cl_image_desc img_desc_3d; + + memset(&img_desc_3d, 0, sizeof(img_desc_3d)); + img_desc_3d.image_type = CL_MEM_OBJECT_IMAGE3D; + img_desc_3d.image_width = (size_t)n_q; + img_desc_3d.image_height = (size_t)n_batch * (size_t)n_head; + img_desc_3d.image_depth = (size_t)d_head_q / 4; + cl_mem img_q_wmm = NULL; + img_q_wmm = clCreateImage(context, CL_MEM_READ_WRITE, &img_fmt_3d, &img_desc_3d, NULL, &err); + CL_CHECK(err); + + { + cl_kernel repack_q = backend_ctx->fa.kernel_repack_q_for_wmm; + CL_CHECK(clSetKernelArg(repack_q, 0, sizeof(cl_mem), &mem_matrixQ)); + CL_CHECK(clSetKernelArg(repack_q, 1, sizeof(cl_ulong), &q_nb1)); + CL_CHECK(clSetKernelArg(repack_q, 2, sizeof(cl_ulong), &q_nb2)); + CL_CHECK(clSetKernelArg(repack_q, 3, sizeof(cl_ulong), &q_nb3)); + CL_CHECK(clSetKernelArg(repack_q, 4, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(repack_q, 5, sizeof(cl_mem), &img_q_wmm)); + + size_t repack_q_gws[3] = {(size_t)d_head_q / 4, (size_t)n_q, (size_t)n_batch * (size_t)n_head}; + backend_ctx->enqueue_ndrange_kernel(repack_q, 3, repack_q_gws, NULL, dst); + } + + // K image: columns, row groups, KV heads. + const size_t n_kv_row4 = ((size_t)n_kv + 3) / 4; + + memset(&img_desc_3d, 0, sizeof(img_desc_3d)); + img_desc_3d.image_type = CL_MEM_OBJECT_IMAGE3D; + img_desc_3d.image_width = (size_t)d_head_q; + img_desc_3d.image_height = n_kv_row4; + img_desc_3d.image_depth = (size_t)n_batch * (size_t)n_head_kv; + cl_mem img_k_wmm = NULL; + img_k_wmm = clCreateImage(context, CL_MEM_READ_WRITE, &img_fmt_3d, &img_desc_3d, NULL, &err); + CL_CHECK(err); + + { + cl_kernel repack_k = backend_ctx->fa.kernel_repack_k_for_wmm; + CL_CHECK(clSetKernelArg(repack_k, 0, sizeof(cl_mem), &mem_matrixK)); + CL_CHECK(clSetKernelArg(repack_k, 1, sizeof(cl_ulong), &k_nb1)); + CL_CHECK(clSetKernelArg(repack_k, 2, sizeof(cl_ulong), &k_nb2)); + CL_CHECK(clSetKernelArg(repack_k, 3, sizeof(cl_ulong), &k_nb3)); + CL_CHECK(clSetKernelArg(repack_k, 4, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(repack_k, 5, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(repack_k, 6, sizeof(cl_mem), &img_k_wmm)); + + size_t repack_k_gws[3] = {(size_t)d_head_q, n_kv_row4, (size_t)n_batch * (size_t)n_head_kv}; + backend_ctx->enqueue_ndrange_kernel(repack_k, 3, repack_k_gws, NULL, dst); + } + + // V image: kv-rows (contracted), packed head-dim groups, KV heads. + memset(&img_desc_3d, 0, sizeof(img_desc_3d)); + img_desc_3d.image_type = CL_MEM_OBJECT_IMAGE3D; + img_desc_3d.image_width = (size_t)n_kv; + img_desc_3d.image_height = (size_t)d_head_v / 4; + img_desc_3d.image_depth = (size_t)n_batch * (size_t)n_head_kv; + cl_mem img_v_wmm = NULL; + img_v_wmm = clCreateImage(context, CL_MEM_READ_WRITE, &img_fmt_3d, &img_desc_3d, NULL, &err); + CL_CHECK(err); + + { + cl_kernel repack_v = backend_ctx->fa.kernel_repack_v_for_wmm; + CL_CHECK(clSetKernelArg(repack_v, 0, sizeof(cl_mem), &mem_matrixV)); + CL_CHECK(clSetKernelArg(repack_v, 1, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(repack_v, 2, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(repack_v, 3, sizeof(cl_ulong), &v_nb3)); + CL_CHECK(clSetKernelArg(repack_v, 4, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(repack_v, 5, sizeof(cl_mem), &img_v_wmm)); + + size_t repack_v_gws[3] = {(size_t)d_head_v / 4, (size_t)n_kv, (size_t)n_batch * (size_t)n_head_kv}; + backend_ctx->enqueue_ndrange_kernel(repack_v, 3, repack_v_gws, NULL, dst); + } + + cl_int enable_mask = (extra_mask) ? 1 : 0; + mask_buffer = extra_mask ? mem_tex_matrixMask_1dbuf : mem_tex_mask_fallback_1dbuf; + + cl_mem mem_sinksBuf = NULL; + cl_mem mem_tex_sinks_1dbuf = NULL; + cl_int enable_sinks = (sinks_buffer != NULL) ? 1 : 0; + if (enable_sinks) { + region.origin = offset_sinks; + region.size = ggml_nbytes(sinks); + mem_sinksBuf = clCreateSubBuffer(extra_sinks->data_device, CL_MEM_READ_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt_sinks_1d = { CL_R, CL_FLOAT }; + cl_image_desc img_desc_sinks_1d; + memset(&img_desc_sinks_1d, 0, sizeof(img_desc_sinks_1d)); + img_desc_sinks_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc_sinks_1d.image_width = (size_t)n_head; + img_desc_sinks_1d.buffer = mem_sinksBuf; + mem_tex_sinks_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_sinks_1d, &img_desc_sinks_1d, NULL, &err); + CL_CHECK(err); + } else { + // The image obj cannot be null so we back with buffer of size 1 and use matrixK to back because it always exists + cl_image_format img_fmt_sinks_fallback = { CL_R, CL_FLOAT }; + cl_image_desc img_desc_sinks_fallback; + memset(&img_desc_sinks_fallback, 0, sizeof(img_desc_sinks_fallback)); + img_desc_sinks_fallback.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc_sinks_fallback.image_width = 1; + img_desc_sinks_fallback.buffer = mem_matrixK; + mem_tex_sinks_1dbuf = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_sinks_fallback, &img_desc_sinks_fallback, NULL, &err); + CL_CHECK(err); + } + + cl_uint arg = 0; + + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &mem_tex_matrixO_1dbuf)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &is_causal)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &q_nb1)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &q_nb2)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &q_nb3)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &k_nb1)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &k_nb2)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &k_nb3)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &v_nb3)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &o_nb1)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &o_nb2)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &o_nb3)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_head_log2_val)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(float), &logit_softcap)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &mask_buffer)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &enable_mask)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &mask_nb1_padded)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &mask_nb2_padded)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_ulong), &mask_nb3_padded)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &mask_ne2)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &mask_ne3)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &mem_tex_sinks_1dbuf)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &enable_sinks)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &img_q_wmm)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &img_k_wmm)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(cl_mem), &img_v_wmm)); + CL_CHECK(clSetKernelArg(kernel, arg++, sizeof(int), &d_head_q)); + + size_t global_work_size[3], local_work_size[3]; + + const int n_waves_v = d_head_q / 64; + + local_work_size[0] = 64; + local_work_size[1] = n_waves_v; + local_work_size[2] = 1; + + global_work_size[0] = 64; + global_work_size[1] = ((n_q + 64 - 1) / 64) * n_waves_v; + global_work_size[2] = n_batch * n_head; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(mem_tex_matrixO_1dbuf)); + CL_CHECK(clReleaseMemObject(mem_tex_mask_fallback_1dbuf)); + CL_CHECK(clReleaseMemObject(img_q_wmm)); + CL_CHECK(clReleaseMemObject(img_k_wmm)); + CL_CHECK(clReleaseMemObject(img_v_wmm)); + + if (mem_tex_matrixMask_1dbuf) { + CL_CHECK(clReleaseMemObject(mem_tex_matrixMask_1dbuf)); + } + if (mem_matrixMask) { + CL_CHECK(clReleaseMemObject(mem_matrixMask)); + } + if (mem_matrixMask_padded) { + CL_CHECK(clReleaseMemObject(mem_matrixMask_padded)); + } + if (mem_tex_sinks_1dbuf) { + CL_CHECK(clReleaseMemObject(mem_tex_sinks_1dbuf)); + } + if (mem_sinksBuf) { + CL_CHECK(clReleaseMemObject(mem_sinksBuf)); + } + CL_CHECK(clReleaseMemObject(mem_matrixQ)); + CL_CHECK(clReleaseMemObject(mem_matrixK)); + CL_CHECK(clReleaseMemObject(mem_matrixV)); + CL_CHECK(clReleaseMemObject(mem_matrixO)); +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +static void ggml_cl_fa_decompose_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * src2, ggml_tensor * dst, cl_mem sums) { + GGML_ASSERT(src0 && src0->extra); + GGML_ASSERT(src1 && src1->extra && src1->type == GGML_TYPE_F16); + GGML_ASSERT(dst && dst->extra); + GGML_ASSERT(sums != nullptr); + GGML_ASSERT(src0->ne[0] % 4 == 0); + + if (src2) { + GGML_ASSERT(src2->extra); + } + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extra2 = src2 ? (ggml_tensor_extra_cl *)src2->extra : nullptr; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offset2 = extra2 ? extra2->offset + src2->view_offs : offset0; + cl_ulong offsetd = extrad->offset + dst->view_offs; + cl_ulong offsets = 0; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; + + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + float scale, max_bias; + memcpy(&scale, dst->op_params + 0, sizeof(float)); + memcpy(&max_bias, dst->op_params + 1, sizeof(float)); + + const int n_head = src0->ne[2]; + const int n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head)); + + const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + + // one wave per row, same as ggml_cl_soft_max on Adreno + const int nth = 64; + + cl_kernel kernel = backend_ctx->fa.kernel_fa_decompose_soft_max_4_f16; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), extra2 ? &extra2->data_device : &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &sums)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsets)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &n_head_log2)); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_fa_q8_rows( + ggml_backend_t backend, const ggml_tensor * src, const ggml_tensor * dst, + cl_mem values, cl_mem scales, int64_t row0, int nrow +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto * extra = (ggml_tensor_extra_cl *) (src->view_src ? src->view_src->extra : src->extra); + const cl_ulong offset = extra->offset + src->view_offs + row0 * src->nb[1]; + const cl_ulong nb1 = src->nb[1]; + const cl_ulong nb2 = src->nb[2]; + const int dk = src->ne[0]; + const int nhead = src->ne[2]; + cl_kernel kernel; + switch (src->type) { + case GGML_TYPE_F16: kernel = backend_ctx->fa.kernel_fa_q8_rows_f16; break; + case GGML_TYPE_F32: kernel = backend_ctx->fa.kernel_fa_q8_rows_f32; break; + default: GGML_ABORT("unsupported int8 KQ input type"); + } + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &values)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &scales)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nrow)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhead)); + const size_t blocks = (size_t) (dk / 32) * nrow * nhead; + size_t gws[3] = {(blocks + 63) / 64 * 64, 1, 1}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); +} + +static void ggml_cl_fa_kq_int8_prepare(ggml_backend_t backend, const ggml_tensor * dst, int64_t n_q_chunk) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * k = dst->src[1]; + const size_t k_bytes = (size_t) k->ne[0] * k->ne[1] * k->ne[2]; + const size_t q_bytes = (size_t) q->ne[0] * n_q_chunk * q->ne[2]; + backend_ctx->prealloc_fa_k8.allocate(backend_ctx->context, k_bytes); + backend_ctx->prealloc_fa_k8_scale.allocate(backend_ctx->context, k_bytes / 32 * sizeof(cl_half)); + backend_ctx->prealloc_fa_q8.allocate(backend_ctx->context, q_bytes); + backend_ctx->prealloc_fa_q8_scale.allocate(backend_ctx->context, q_bytes / 32 * sizeof(cl_half)); + ggml_cl_fa_q8_rows(backend, k, dst, backend_ctx->prealloc_fa_k8.buffer, backend_ctx->prealloc_fa_k8_scale.buffer, 0, k->ne[1]); +} + +static void ggml_cl_fa_kq_p8_dispatch( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, + const ggml_tensor * mask, const ggml_tensor * sinks, + const ggml_tensor * dst, + int64_t q0, int nqc, float scale, float max_bias, int p_pitch, bool kq_int8 +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto * extra_k = (ggml_tensor_extra_cl *) (k->view_src ? k->view_src->extra : k->extra); + auto * extra_q = (ggml_tensor_extra_cl *) q->extra; + auto * extra_m = (ggml_tensor_extra_cl *) mask->extra; + + const int M = k->ne[1]; + const int K = k->ne[0]; + const int N = nqc; + const int D_A = k->ne[2]; + const int D_B = q->ne[2]; + + const cl_ulong off_mask = extra_m->offset + mask->view_offs + q0 * mask->nb[1]; + const cl_ulong mask_nb1 = mask->nb[1]; + const int n_head_log2 = 1u << (unsigned) floorf(log2f((float) D_B)); + const float m0 = powf(2.0f, -max_bias / n_head_log2); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + + cl_kernel kernel; + cl_uint a = 0; + + if (kq_int8) { + ggml_cl_fa_q8_rows(backend, q, dst, backend_ctx->prealloc_fa_q8.buffer, backend_ctx->prealloc_fa_q8_scale.buffer, q0, nqc); + kernel = K <= 256 ? backend_ctx->fa.kernel_mul_mm_q8_kq_p8 : backend_ctx->fa.kernel_mul_mm_q8_kq_p8_dk512; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_k8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_q8_scale.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + size_t gws[3] = {64 * (((size_t) N + 31) / 32) * (D_B / D_A), ((size_t) M + 511) / 512, (size_t) D_A}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } else { + cl_int err; + + cl_buffer_region region = {extra_k->offset + k->view_offs, k->nb[1] * k->ne[1]}; + cl_mem k_sub = clCreateSubBuffer(extra_k->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format fmt = {CL_RGBA, CL_FLOAT}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = region.size / 16; + desc.buffer = k_sub; + cl_mem k_img = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &fmt, &desc, nullptr, &err); + CL_CHECK(err); + + region.origin = extra_q->offset + q->view_offs + q0 * q->nb[1]; + region.size = (size_t) K * N * D_B * sizeof(float); + cl_mem q_sub = clCreateSubBuffer(extra_q->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + kernel = backend_ctx->fa.kernel_mul_mm_f16_f32_kq_p8; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &k_img)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &q_sub)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_m->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_mask)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_log2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_A)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &D_B)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &p_pitch)); + + // Pack query heads of each KV group into a short batch's tile. + static const bool fold_enabled = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_P8_FOLD"); + return !e || e[0] != '0'; + }(); + const int gqa = D_B / D_A; + const int fold = fold_enabled && gqa > 1 && N < 32 && gqa <= INT_MAX / N ? gqa : 1; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &fold)); + + const size_t n_tiles = ((size_t) N * fold + 31) / 32; + size_t gws[3] = {64, n_tiles, (size_t)(M / 64) * (fold > 1 ? D_A : D_B)}; + + const bool two_tiles = n_tiles % 2 == 0 && backend_ctx->get_kernel_workgroup_size(kernel) >= 128; + size_t lws[3] = {64, two_tiles ? (size_t) 2 : (size_t) 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + CL_CHECK(clReleaseMemObject(k_img)); + CL_CHECK(clReleaseMemObject(k_sub)); + CL_CHECK(clReleaseMemObject(q_sub)); + } + + cl_mem sinks_buf = extra_q->data_device; + cl_ulong sinks_off = 0; + const int has_sinks = sinks != nullptr; + + if (sinks) { + auto * extra_s = (ggml_tensor_extra_cl *) sinks->extra; + sinks_buf = extra_s->data_device; + sinks_off = extra_s->offset + sinks->view_offs; + } + + const int nblk = M / 32; + const int row_blk = p_pitch / 32; + + kernel = backend_ctx->fa.kernel_fa_p8_fixup; + + a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bmax.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_bsum.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_sums.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &sinks_buf)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &sinks_off)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &has_sinks)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nblk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &row_blk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &N)); + + size_t gws_fixup[3] = {(size_t) 64 * N, (size_t) D_B, 1}; + size_t lws_fixup[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws_fixup, lws_fixup, dst); +} + +static void ggml_cl_fa_decompose_scratch_tensor( + ggml_tensor & t, ggml_tensor_extra_cl & extra, cl_mem buffer, ggml_type type, + int64_t ne0, int64_t ne1, int64_t ne2 +) { + memset(&t, 0, sizeof(t)); + t.type = type; + t.ne[0] = ne0; t.ne[1] = ne1; t.ne[2] = ne2; t.ne[3] = 1; + t.nb[0] = ggml_type_size(type); + t.nb[1] = t.nb[0]*ne0; + t.nb[2] = t.nb[1]*ne1; + t.nb[3] = t.nb[2]*ne2; + + extra.reset(); + extra.data_device = buffer; + t.extra = &extra; +} + +static void ggml_cl_fa_decompose_write_chunk( + ggml_backend_t backend, const ggml_tensor & kqv, int64_t q0, ggml_tensor * dst +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const int64_t dv = kqv.ne[0]; + const int64_t nqc = kqv.ne[1]; + const int64_t n_head = kqv.ne[2]; + + // apply the deferred 1/sum to the KQV rows + { + cl_kernel kernel = backend_ctx->fa.kernel_fa_decompose_scale_rows_f32; + const cl_ulong offset_kqv = 0; + const cl_ulong offset_sums = 0; + const int dv_i = (int) dv; + const int nqc_i = (int) nqc; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_kqv)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &backend_ctx->prealloc_fa_sums.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_sums)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &nqc_i)); + + size_t gws[3] = { (size_t) 64 * nqc, (size_t) n_head, 1 }; + size_t lws[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + // permute into dst: [dv, nqc, n_head] -> dst[dv, n_head, q0 .. q0+nqc) + { + ggml_tensor kqv_perm = kqv; + kqv_perm.ne[1] = n_head; + kqv_perm.ne[2] = nqc; + kqv_perm.nb[1] = kqv.nb[2]; + kqv_perm.nb[2] = kqv.nb[1]; + + ggml_tensor dst_chunk = *dst; + dst_chunk.ne[2] = nqc; + dst_chunk.view_offs = dst->view_offs + (size_t) q0 * dst->nb[2]; + + ggml_cl_cpy(backend, &kqv_perm, &dst_chunk, nullptr); + } +} + +static void ggml_cl_flash_attn_decompose( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst, + int64_t n_q_chunk, float scale, float max_bias +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + const int64_t dv = v->ne[0]; + const int64_t n_head = q->ne[2]; + const int64_t n_head_kv = k->ne[2]; + + const std::pair dk_dv = {(int) q->ne[0], (int) dv}; + + // The image GEMMs work in 64 x 32 tiles and can touch past the exact extent, + // so size each scratch by the padded shape plus one extra head. + auto pad_up = [](int64_t x, int64_t a) { return ((x + a - 1) / a) * a; }; + const int64_t kq_m = pad_up(n_kv, 64); + const int64_t kqv_m = pad_up(dv, 64); + const int64_t tile_n = pad_up(n_q_chunk, 32); + + backend_ctx->prealloc_fa_vt.allocate(backend_ctx->context, (size_t)(n_kv * kqv_m * (n_head_kv + 1)) * sizeof(ggml_fp16_t)); + backend_ctx->prealloc_fa_kq.allocate(backend_ctx->context, (size_t)(kq_m * tile_n * (n_head + 1)) * sizeof(float)); + backend_ctx->prealloc_fa_kqv.allocate(backend_ctx->context, (size_t)(kqv_m * tile_n * (n_head + 1)) * sizeof(float)); + backend_ctx->prealloc_fa_sums.allocate(backend_ctx->context, (size_t)(n_q_chunk * n_head) * sizeof(float)); + + // V^T once per call: [dv, n_kv, n_head_kv] -> [n_kv, dv, n_head_kv] + { + ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; + cl_kernel kernel = backend_ctx->fa.v_transpose_f16.at(dk_dv); + + const cl_ulong offset_v = extra_v->offset + v->view_offs; + const cl_ulong v_nb1 = v->nb[1]; + const cl_ulong v_nb2 = v->nb[2]; + const int n_kv_i = (int) n_kv; + const int dv_i = (int) dv; + const int n_head_kv_i = (int) n_head_kv; + + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vt.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); + + size_t gws[3] = { (size_t)((dv + 31) / 32) * 32, (size_t)((n_kv + 31) / 32) * 8, (size_t) n_head_kv }; + size_t lws[3] = { 32, 8, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + ggml_tensor_extra_cl extra_vt; + ggml_tensor_extra_cl extra_kq; + ggml_tensor_extra_cl extra_kqv; + ggml_tensor vt; + ggml_tensor kq; + ggml_tensor kqv; + ggml_cl_fa_decompose_scratch_tensor(vt, extra_vt, backend_ctx->prealloc_fa_vt.buffer, GGML_TYPE_F16, n_kv, dv, n_head_kv); + + for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { + const int64_t nqc = MIN(n_q_chunk, n_q - q0); + + // KQ: [dk, n_kv, n_head_kv] x [dk, nqc, n_head] -> [n_kv, nqc, n_head] + ggml_cl_fa_decompose_scratch_tensor(kq, extra_kq, backend_ctx->prealloc_fa_kq.buffer, GGML_TYPE_F32, n_kv, nqc, n_head); + + { + ggml_tensor q_chunk = *q; + q_chunk.ne[1] = nqc; + q_chunk.view_offs = q->view_offs + (size_t) q0 * q->nb[1]; + ggml_cl_mul_mat(backend, k, &q_chunk, &kq); + } + + // softmax in place, the row sums go to prealloc_fa_sums + { + memcpy((float *) kq.op_params + 0, &scale, sizeof(float)); + memcpy((float *) kq.op_params + 1, &max_bias, sizeof(float)); + + ggml_tensor mask_chunk = *mask; + mask_chunk.ne[1] = nqc; + mask_chunk.view_offs = mask->view_offs + (size_t) q0 * mask->nb[1]; + + ggml_cl_fa_decompose_soft_max(backend, &kq, &mask_chunk, sinks, &kq, backend_ctx->prealloc_fa_sums.buffer); + } + + // KQV: [n_kv, dv, n_head_kv] x [n_kv, nqc, n_head] -> [dv, nqc, n_head] + // V^T is contiguous, so mul_mat would not pick the KQV image kernel; call it here. + ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (backend_ctx->mul_mat.kernel_mul_mm_f16_f32_kqv != nullptr && + (dv % 64) == 0 && (n_kv % 16) == 0 && nqc >= 32 && + ((size_t)(vt.nb[2] * n_head_kv / 4) / 4 <= backend_ctx->image_max_buffer_size) && + ((size_t)(dv * nqc * n_head) <= backend_ctx->image_max_buffer_size)) { + ggml_cl_mul_mat_kq_kqv_adreno(backend, &vt, &kq, &kqv, /*is_kq =*/ false); + } else +#endif + { + ggml_cl_mul_mat(backend, &vt, &kq, &kqv); + } + + ggml_cl_fa_decompose_write_chunk(backend, kqv, q0, dst); + } +} + +static void ggml_cl_fa_pv_direct(ggml_backend_t backend, ggml_tensor * dst, int kv_pitch) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * q = dst->src[0]; + const ggml_tensor * v = dst->src[2]; + auto * extra_v = (ggml_tensor_extra_cl *) v->extra; + + const int dv = v->ne[0]; + const int n_q = q->ne[1]; + const int n_head = q->ne[2]; + const int n_head_kv = v->ne[2]; + const int gqa = n_head / n_head_kv; + const int nblk = v->ne[1] / 32; + const int d_blocks = dv / 128; + // Split the KV range to give a small query batch about 256 workgroups. + const int want = MAX(1, 256 / (d_blocks * n_head_kv)); + const int blocks_per_split = (nblk + want - 1) / want; + const int n_split = (nblk + blocks_per_split - 1) / blocks_per_split; + const int n_elem = n_head * n_q * dv; + backend_ctx->prealloc_fa_kq.allocate(backend_ctx->context, (size_t) n_split * n_elem * sizeof(float)); + + const cl_ulong off_v = extra_v->offset + v->view_offs; + const cl_ulong v_nb1 = v->nb[1]; + const cl_ulong v_nb2 = v->nb[2]; + { + cl_kernel kernel = backend_ctx->fa.kernel_fa_kqv_direct_f16; + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_v)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &gqa)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nblk)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &blocks_per_split)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); + size_t gws[3] = {(size_t) d_blocks * 64, (size_t) n_head_kv, (size_t) n_split}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + { + cl_kernel kernel = backend_ctx->fa.kernel_fa_kqv_direct_reduce; + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_elem)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_split)); + size_t gws[3] = {((size_t) n_elem + 63) / 64 * 64, 1, 1}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } +} + +static void ggml_cl_flash_attn_decompose_kq_p8( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, + ggml_tensor * dst, + int64_t n_q_chunk, float scale, float max_bias, bool kqv_direct, bool kq_int8 +) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + const int64_t dv = v->ne[0]; + const int64_t n_head = q->ne[2]; + const int64_t n_head_kv = k->ne[2]; + + auto pad_up = [](int64_t x, int64_t a) { return ((x + a - 1) / a) * a; }; + const int64_t kqv_m = pad_up(dv, 64); + const int64_t tile_n = pad_up(n_q_chunk, 32); + + static const int64_t kv_pitch_round = [] { + const char * e = getenv("GGML_OPENCL_FA_KV_PITCH_ROUND"); + const int64_t v = (e && e[0]) ? strtoll(e, nullptr, 10) : 32768; + return v > 0 && v <= INT_MAX && (v & (v - 1)) == 0 ? v : (int64_t) 0; + }(); + static const int64_t kv_pitch_round_min = [] { + const char * e = getenv("GGML_OPENCL_FA_KV_PITCH_ROUND_MIN"); + return (e && e[0]) ? strtoll(e, nullptr, 10) : (int64_t) 16384; + }(); + static const int64_t kv_pitch_round_max_dv = [] { + const char * e = getenv("GGML_OPENCL_FA_KV_PITCH_ROUND_MAX_DV"); + return (e && e[0]) ? strtoll(e, nullptr, 10) : (int64_t) 256; + }(); + + // Round long P and V^T rows to reduce cache conflicts, then add one cache line. + int64_t kv_pitch_value = n_kv + 64; + if (kv_pitch_round > 0 && n_kv > kv_pitch_round_min && dv <= kv_pitch_round_max_dv) { + const int64_t rounded_pitch = pad_up(n_kv, kv_pitch_round) + 64; + if (rounded_pitch <= INT_MAX && + (size_t) rounded_pitch <= SIZE_MAX / n_q_chunk / n_head && + (size_t) rounded_pitch <= SIZE_MAX / dv / n_head_kv) { + kv_pitch_value = rounded_pitch; + } + } + const int kv_pitch = (int) kv_pitch_value; + const size_t nblk = (size_t) kv_pitch / 32; + + backend_ctx->prealloc_fa_pq.allocate(backend_ctx->context, (size_t) kv_pitch * n_q_chunk * n_head); + backend_ctx->prealloc_fa_pd.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); + backend_ctx->prealloc_fa_bmax.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); + backend_ctx->prealloc_fa_bsum.allocate(backend_ctx->context, nblk * n_q_chunk * n_head * sizeof(float)); + backend_ctx->prealloc_fa_kqv.allocate(backend_ctx->context, (size_t)(kqv_m * tile_n * (n_head + 1)) * sizeof(float)); + backend_ctx->prealloc_fa_sums.allocate(backend_ctx->context, (size_t)(n_q_chunk * n_head) * sizeof(float)); + + // Direct PV reads the original V cache and needs no transposed copy. + if (!kqv_direct) { + backend_ctx->prealloc_fa_vtq.allocate(backend_ctx->context, (size_t) kv_pitch * dv * n_head_kv); + backend_ctx->prealloc_fa_vtd.allocate(backend_ctx->context, nblk * dv * n_head_kv * sizeof(cl_half)); + + ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *)v->extra; + cl_kernel kernel = backend_ctx->fa.kernel_fa_v_transpose_q8; + + const cl_ulong offset_v = extra_v->offset + v->view_offs; + const cl_ulong v_nb1 = v->nb[1]; + const cl_ulong v_nb2 = v->nb[2]; + const cl_ulong v_nb3 = v->nb[3]; + const int n_kv_i = (int) n_kv; + const int dv_i = (int) dv; + const int n_head_kv_i = (int) n_head_kv; + + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_head_kv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &v_nb3)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); + + size_t gws[3] = { (size_t)((dv + 31) / 32) * 32, (size_t)((n_kv + 31) / 32) * 8, (size_t) n_head_kv }; + size_t lws[3] = { 32, 8, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + if (kq_int8) { + ggml_cl_fa_kq_int8_prepare(backend, dst, n_q_chunk); + } + + ggml_tensor_extra_cl extra_kqv; + ggml_tensor kqv; + + for (int64_t q0 = 0; q0 < n_q; q0 += n_q_chunk) { + const int64_t nqc = MIN(n_q_chunk, n_q - q0); + + ggml_cl_fa_kq_p8_dispatch(backend, q, k, mask, sinks, dst, q0, nqc, scale, max_bias, kv_pitch, kq_int8); + + ggml_cl_fa_decompose_scratch_tensor(kqv, extra_kqv, backend_ctx->prealloc_fa_kqv.buffer, GGML_TYPE_F32, dv, nqc, n_head); + + if (kqv_direct) { + GGML_ASSERT(q0 == 0 && nqc == n_q); + ggml_cl_fa_pv_direct(backend, dst, kv_pitch); + } else { + const cl_ulong zero = 0; + const int dv_i = dv; + const int nkv_i = n_kv; + const int nqc_i = nqc; + const int nh_i = n_head; + const int nhkv_i = n_head_kv; + + cl_kernel kernel = backend_ctx->fa.kernel_mul_mm_q8_f32_kqv; + + cl_uint a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_vtd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pq.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_pd.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &backend_ctx->prealloc_fa_kqv.buffer)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &zero)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &dv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nkv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nqc_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nh_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nhkv_i)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &kv_pitch)); + size_t gws[3] = {(size_t)(dv / 64) * 64, (size_t)(n_head / n_head_kv) * ((nqc + 31) / 32), (size_t) n_head_kv}; + size_t lws[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); + } + + ggml_cl_fa_decompose_write_chunk(backend, kqv, q0, dst); + } +} + +// Decomposed flash attention prefill. +// +// On Adreno the fused prefill tile is slow at large head sizes, while the +// KQ / KQV image GEMMs are fast. -fa 0 uses those GEMMs, but it keeps KQ for +// the whole ubatch in the graph. Here the FLASH_ATTN_EXT node stays, and the +// queries are split into chunks. For each chunk: KQ -> softmax -> KQV into +// backend scratch, so the scratch size depends on the chunk and not on the +// ubatch, and the KV cache keeps the flash attention layout. +// +// Returns false when the shape is not supported, then the fused tile runs. +// GGML_OPENCL_FA_DECOMPOSE=0 disables it, =1 enables it for any Adreno GPU and +// head size. GGML_OPENCL_FA_DECOMPOSE_MB sets the KQ scratch budget (default 256). +// GGML_OPENCL_FA_KQ_P8=0 disables U8 probabilities and int8 KQV. +// GGML_OPENCL_FA_KQV_DIRECT=0 disables direct PV for small query batches. +// GGML_OPENCL_FA_KQ_INT8=0 keeps F16 KQ; =1 enables int8 KQ for supported shapes. +static bool ggml_cl_flash_attn_decompose_dispatch( + ggml_backend_t backend, + const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst +) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + + if (backend_ctx->gpu_family != ADRENO) { + return false; + } + + static const int env = []{ + const char * e = getenv("GGML_OPENCL_FA_DECOMPOSE"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + + if (env == 0) { + return false; + } + + const int64_t n_q = q->ne[1]; + const int64_t n_kv = k->ne[1]; + const int64_t dk = q->ne[0]; + const int64_t dv = v->ne[0]; + const int64_t n_head = q->ne[2]; + const int64_t n_head_kv = k->ne[2]; + + const bool measured_gen = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E; + + if (n_q < 2) { + return false; + } + if (q->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32 || + k->type != GGML_TYPE_F16 || v->type != GGML_TYPE_F16) { + return false; + } + if (q->ne[3] != 1 || k->ne[3] != 1 || v->ne[3] != 1 || dst->ne[3] != 1) { + return false; + } + if (n_head_kv <= 0 || n_head < n_head_kv || n_head % n_head_kv != 0) { + return false; + } + if (k->nb[0] != ggml_type_size(k->type) || v->nb[0] != ggml_type_size(v->type)) { + return false; + } + // K and Q must be packed [dk, head, row], as the KV cache and the permuted Q + // are. mul_mat sends the KQ to the image KQ kernel only for this layout; + // other K views can reach the KQV image kernel there and give wrong results. + if (k->nb[2] != (size_t) dk * sizeof(ggml_fp16_t) || k->nb[1] != (size_t) dk * n_head_kv * sizeof(ggml_fp16_t) || + q->nb[0] != sizeof(float) || q->nb[2] != (size_t) dk * sizeof(float) || q->nb[1] != (size_t) dk * n_head * sizeof(float)) { + return false; + } + + // soft_max applies scale, mask, ALiBi and sinks, but not the softcap. + float scale; + float max_bias; + float logit_softcap; + memcpy(&scale, (const float *) dst->op_params + 0, sizeof(float)); + memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float)); + memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float)); + if (logit_softcap != 0.0f) { + return false; + } + + // The deferred softmax kernel needs an f16 mask and rows that divide by 4. + if (mask == nullptr || mask->type != GGML_TYPE_F16 || mask->ne[0] < n_kv || (n_kv % 4) != 0) { + return false; + } + + const std::pair dk_dv = {(int) dk, (int) dv}; + if (backend_ctx->fa.v_transpose_f16.count(dk_dv) == 0) { + return false; + } + + static const char * p8_env = getenv("GGML_OPENCL_FA_KQ_P8"); + const bool kq_p8 = (!p8_env || p8_env[0] != '0') && measured_gen && + backend_ctx->fa.kernel_mul_mm_f16_f32_kq_p8 != nullptr && + backend_ctx->fa.kernel_mul_mm_q8_f32_kqv != nullptr && + backend_ctx->fa.kernel_fa_v_transpose_q8 != nullptr && + n_kv <= INT_MAX - 64 && k->nb[1] <= INT_MAX && + (n_kv % 64) == 0 && (dk % 16) == 0 && (dv % 64) == 0 && + mask->ne[2] == 1 && mask->ne[3] == 1 && mask->nb[0] == sizeof(ggml_fp16_t) && + (mask->nb[1] % sizeof(ggml_fp16_t)) == 0 && + k->nb[1] * n_kv / 16 <= backend_ctx->image_max_buffer_size; + + // Keep DK64 with attention sinks opt-in until its accuracy is validated. + const bool dk64_ok = kq_p8 && dst->src[4] == nullptr && n_head / n_head_kv >= 2 && + n_kv >= 1024 && n_q <= n_kv / 2; + const int min_dk = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? (dk64_ok ? 64 : 128) : 256; + if (env != 1 && !(measured_gen && dk >= min_dk)) { + return false; + } + + static const char * direct_env = getenv("GGML_OPENCL_FA_KQV_DIRECT"); + const bool kqv_direct = (!direct_env || direct_env[0] != '0') && kq_p8 && + backend_ctx->fa.kernel_fa_kqv_direct_f16 != nullptr && backend_ctx->fa.kernel_fa_kqv_direct_reduce != nullptr && + v->ne[1] == n_kv && v->ne[2] == n_head_kv && + n_q <= 32 / (n_head / n_head_kv) && dv >= 128 && dv <= INT_MAX && (dv % 128) == 0 && + n_head <= INT_MAX / (n_q * dv) && (v->nb[1] % 4) == 0 && (v->nb[2] % 4) == 0; + const bool small_p8 = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && + kq_p8 && dk >= 128 && n_kv >= 1024; + // Small batches without direct PV need P8 and a long KV cache on X2E. + if (n_q < 32 && !kqv_direct && !small_p8) { + return false; + } + + // Chunk size: a byte budget for KQ, at least 8 tiles of 32 queries so the + // GEMMs get usable shapes, and below the image1d_buffer limit of the KQ dst. + static const size_t budget_bytes = []{ + const char * e = getenv("GGML_OPENCL_FA_DECOMPOSE_MB"); + const int mb = (e && e[0]) ? atoi(e) : 256; + return (size_t)(mb > 0 ? mb : 256) * 1024 * 1024; + }(); + + const size_t kq_row_bytes = (size_t) n_kv * n_head * sizeof(float); + int64_t n_q_chunk = MIN((int64_t)(budget_bytes / kq_row_bytes), n_q); + n_q_chunk = MAX(n_q_chunk, MIN((int64_t) 8 * 32, n_q)); + + if (!kq_p8) { + n_q_chunk = MIN(n_q_chunk, (int64_t)(backend_ctx->image_max_buffer_size / (n_kv * n_head))); + } + if (n_q_chunk < 32 && n_q_chunk < n_q) { + return false; + } + + static const int kq_int8_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + static const int dk512_env = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_DK512_F16"); + return (e && e[0]) ? (e[0] != '0' ? 1 : 0) : -1; + }(); + const bool dk512 = dk > 256 && dk <= 512 && n_q >= 32 && + (dk512_env == 1 || (dk512_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E)); + const bool kq_int8_possible = kq_p8 && (dk <= 256 || dk512) && dk % 32 == 0 && + backend_ctx->fa.kernel_fa_q8_rows_f16 != nullptr && backend_ctx->fa.kernel_fa_q8_rows_f32 != nullptr && + n_head <= INT_MAX && n_head_kv <= INT_MAX && + n_q <= INT_MAX / n_head / (dk / 32) && n_kv <= INT_MAX / n_head_kv / (dk / 32) && + (dst->src[4] == nullptr || dk > 64) && + (kq_int8_env == 1 || (kq_int8_env < 0 && backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && n_kv >= 2048)) && + backend_ctx->get_kernel_workgroup_size(backend_ctx->fa.kernel_fa_q8_rows_f16) >= 64 && + backend_ctx->get_kernel_workgroup_size(backend_ctx->fa.kernel_fa_q8_rows_f32) >= 64; + cl_kernel kq_int8_kernel = nullptr; + if (kq_int8_possible) { + kq_int8_kernel = dk <= 256 ? backend_ctx->fa.kernel_mul_mm_q8_kq_p8 : backend_ctx->fa.kernel_mul_mm_q8_kq_p8_dk512; + } + const bool kq_int8 = kq_int8_kernel != nullptr && backend_ctx->get_kernel_workgroup_size(kq_int8_kernel) >= 64; + + // Fewer query tiles per KV block reduce cache pressure in the int8 KQ kernel. + static const int64_t kq_int8_max_chunk = [] { + const char * e = getenv("GGML_OPENCL_FA_KQ_INT8_MAX_CHUNK"); + const int v = (e && e[0]) ? atoi(e) : 96; + return (int64_t) (v >= 32 ? (v / 32) * 32 : 96); + }(); + if (kq_int8) { + n_q_chunk = MIN(n_q_chunk, kq_int8_max_chunk); + } + + // even out the chunks, then align to the 32-wide n-tile + const int64_t n_chunks = (n_q + n_q_chunk - 1) / n_q_chunk; + n_q_chunk = MIN(n_q_chunk, ((n_q + n_chunks - 1) / n_chunks + 31) & ~(int64_t) 31); + + if (kq_p8) { + ggml_cl_flash_attn_decompose_kq_p8(backend, q, k, dst, n_q_chunk, scale, max_bias, kqv_direct, kq_int8); + } else { + ggml_cl_flash_attn_decompose(backend, q, k, dst, n_q_chunk, scale, max_bias); + } + return true; +} + +void ggml_cl_flash_attn(ggml_backend_t backend, const ggml_tensor * q, const ggml_tensor * k, ggml_tensor * dst) { + const ggml_tensor * v = dst->src[2]; + const ggml_tensor * mask = dst->src[3]; + const ggml_tensor * sinks = dst->src[4]; + + GGML_ASSERT(q->extra); + GGML_ASSERT(k->extra); + GGML_ASSERT(v->extra); + GGML_ASSERT(dst->extra); + + if (mask) { + GGML_ASSERT(mask->extra); + } + if (sinks) { + GGML_ASSERT(sinks->extra); + } + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + const int n_q = q->ne[1]; + const int n_kv = k->ne[1]; + const int d_head_q = q->ne[0]; + const int d_head_v = v->ne[0]; + const int n_head = q->ne[2]; + const int n_head_kv = k->ne[2]; + const int n_batch = q->ne[3]; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (ggml_cl_adreno_xmem_attn_can_use(backend_ctx, q, k, dst)) { + ggml_cl_adreno_xmem_attn_run(backend, q, k, dst); + return; + } +#endif + + // Compile DK512 decode separately from the prefill programs. + const bool fa_decode_only_512 = (d_head_q == 512); + + // per-variant lazy compile for this (dk, dv) + // DK=512 decode (n_q==1) needs no prepass + // DK=512 prefill (n_q>1) does, so compile it only when needed + if (!fa_decode_only_512 || n_q > 1) { + ggml_opencl_ensure_fa_pre_kernels(backend_ctx, d_head_q, d_head_v); + } + + cl_kernel kernel = NULL; + bool use_prefill_k_img = false; // K is image1d_buffer_t for DK=512 prefill + + const bool is_f16 = q->type == GGML_TYPE_F16; + const bool is_mixed = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_F16 && v->type == GGML_TYPE_F16; + const bool is_q8_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q8_0 && v->type == GGML_TYPE_Q8_0; + const bool is_q4_0 = q->type == GGML_TYPE_F32 && k->type == GGML_TYPE_Q4_0 && v->type == GGML_TYPE_Q4_0; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_fa_bin_kernels_prefill(backend_ctx, q, k, v)) { + // We support the prefill path of flash attn with a specialized d_head = 64/128/256 + ggml_cl_flash_attn_prefill_bin(backend, q, k, dst); + return; + } +#endif + + if (is_f16) { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F16); + } else if (is_mixed) { + if (fa_decode_only_512 && n_q == 1) { + GGML_ASSERT(ggml_opencl_ensure_fa_f32_f16_vec_512(backend_ctx)); + } else { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F32_F16); + } + if (fa_decode_only_512) { + // DK=512: the BM-tile prefill kernels are specifically compiled from + // FA_PREFILL_ONLY + if (n_q > 1) { + ggml_opencl_ensure_fa_f32_f16_prefill_512(backend_ctx, /*split=*/false); + ggml_opencl_ensure_fa_f32_f16_prefill_512(backend_ctx, /*split=*/true); + } + } else { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F32_F16_SPLIT); + } + } else if (is_q8_0) { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q8_0); + if (d_head_q == 96 && d_head_v == 96) { + ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 96, 96, /*quant_bm=*/16, /*quant_n_split=*/3, /*is_q8_0=*/true); + } else if (d_head_q == 256 && d_head_v == 256) { + ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 256, 256, /*quant_bm=*/16, /*quant_n_split=*/8, /*is_q8_0=*/true); + } else { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q8_0_SPLIT); + } + } else if (is_q4_0) { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q4_0); + if (d_head_q == 96 && d_head_v == 96) { + ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 96, 96, /*quant_bm=*/16, /*quant_n_split=*/3, /*is_q8_0=*/false); + } else if (d_head_q == 256 && d_head_v == 256) { + ggml_opencl_ensure_fa_quant_split_override(backend_ctx, 256, 256, /*quant_bm=*/16, /*quant_n_split=*/8, /*is_q8_0=*/false); + } else { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_Q4_0_SPLIT); + } + } else { + ggml_opencl_ensure_fa_variant(backend_ctx, d_head_q, d_head_v, FA_VARIANT_F32); + } + + const std::pair dk_dv = {d_head_q, d_head_v}; + const int mq_gqa = n_head_kv > 0 ? n_head / n_head_kv : 0; + const std::tuple mq_decode_key = {d_head_q, d_head_v, mq_gqa}; + // X2E also takes GQA 2 and 6 at head size 256 (gemma-4 SWA layers, Qwen3.5-27B), + // GQA 16 at 512 and 128 (gemma-4-12b global layers, muse-glimmer) and GQA 2 at 512 (gemma-4-E4B MTP drafter) + const bool mq_decode_x2e = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && + ((d_head_q == 256 && (mq_gqa == 2 || mq_gqa == 6)) || + (d_head_q == 512 && (mq_gqa == 2 || mq_gqa == 16)) || + (d_head_q == 128 && mq_gqa == 16 && backend_ctx->has_subgroup_shuffle)); + const bool mq_decode_kernel = backend_ctx->gpu_family == ADRENO && is_mixed && + d_head_q == d_head_v && n_head_kv > 0 && n_head % n_head_kv == 0 && + ((((d_head_q == 64 && mq_gqa == 8) || (d_head_q == 128 && mq_gqa == 4)) && + backend_ctx->has_subgroup_shuffle) || + ((d_head_q == 256 || d_head_q == 512) && (mq_gqa == 4 || mq_gqa == 8)) || + mq_decode_x2e); + const bool mq_decode_shape = mq_decode_kernel && n_q == 1; + // compile on the first call for this shape (the warmup is a prefill), not on the first decode + if (mq_decode_kernel) { + ggml_opencl_ensure_fa_f32_f16_mq_decode(backend_ctx, d_head_q, d_head_v, mq_gqa); + } + + // after all lazy compiles, so the decode kernels are built during warmup as on the fused path + if (n_q > 1 && ggml_cl_flash_attn_decompose_dispatch(backend, q, k, dst)) { + return; + } + const bool use_native_q8_0_q1 = is_q8_0 && n_q == 1 && + backend_ctx->fa.f32_q8_0_q1.count(dk_dv) > 0; + // Native q8_0 prefill - reads q8_0 directly, wg_size = cfg->bm. + const bool use_native_q8_0 = is_q8_0 && n_q > 1 && + backend_ctx->fa.f32_q8_0.count(dk_dv) > 0; + const bool use_native_q4_0_q1 = is_q4_0 && n_q == 1 && + backend_ctx->fa.f32_q4_0_q1.count(dk_dv) > 0; + const bool use_native_q4_0 = is_q4_0 && n_q > 1 && + backend_ctx->fa.f32_q4_0.count(dk_dv) > 0; + const int block_m = n_q > 1 + ? (is_mixed ? backend_ctx->fa.f32_f16_bm.at(dk_dv) : backend_ctx->fa.bm.at(dk_dv)) + : 0; + // block_n is only used by the n_q > 1 prefill path; its map is not + // populated for DK=512 decode, so do not read it for decode. + const int block_n = (n_q > 1) + ? (is_mixed ? backend_ctx->fa.f32_f16_bn.at(dk_dv) + : backend_ctx->fa.bn.at(dk_dv)) + : 0; + // Pick split variant only when n_kv crosses the per-(dk,dv) threshold. + // the N_SPLIT>1 prefill tile reduces DK partials via subgroup shuffle, + // on Intel it uses the non-split BM tile and does not depend on subgroup size + const bool use_split_kernel = (n_q > 1 && is_mixed && + backend_ctx->gpu_family != INTEL && + backend_ctx->fa.f32_f16_split.count(dk_dv) > 0 && + n_kv >= backend_ctx->fa.f32_f16_split_nkv_threshold.at(dk_dv)); + const bool use_split_q8_0 = (use_native_q8_0 && backend_ctx->gpu_family != INTEL && + backend_ctx->fa.f32_q8_0_split.count(dk_dv) > 0 && + n_kv >= backend_ctx->fa.f32_q8_0_split_nkv_threshold.at(dk_dv)); + const bool use_split_q4_0 = (use_native_q4_0 && backend_ctx->gpu_family != INTEL && + backend_ctx->fa.f32_q4_0_split.count(dk_dv) > 0 && + n_kv >= backend_ctx->fa.f32_q4_0_split_nkv_threshold.at(dk_dv)); + const int wg_size_fa = (n_q > 1 && is_mixed) + ? (use_split_kernel + ? backend_ctx->fa.f32_f16_split_wg_size.at(dk_dv) + : backend_ctx->fa.f32_f16_wg_size.at(dk_dv)) + : block_m; + + ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *)q->extra; + ggml_tensor_extra_cl * extra_o = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl * extra_mask = mask ? (ggml_tensor_extra_cl *)mask->extra : NULL; + ggml_tensor_extra_cl * extra_sinks = sinks ? (ggml_tensor_extra_cl *)sinks->extra : NULL; + + // SoA q8_0/q4_0 K/V: data_device aliases the `q` subbuffer; reconstruct + // AoS into a temp buffer below. AoS tensors use extra_k/v->data_device. + const bool k_soa = ggml_cl_is_q8_0_soa(k) || ggml_cl_is_q4_0_soa(k); + const bool v_soa = ggml_cl_is_q8_0_soa(v) || ggml_cl_is_q4_0_soa(v); + ggml_tensor_extra_cl * extra_k = k_soa ? nullptr : (ggml_tensor_extra_cl *)k->extra; + ggml_tensor_extra_cl * extra_v = v_soa ? nullptr : (ggml_tensor_extra_cl *)v->extra; + + cl_ulong offset_q = extra_q->offset + q->view_offs; + cl_ulong offset_k = k_soa ? 0 : extra_k->offset + k->view_offs; + cl_ulong offset_v = v_soa ? 0 : extra_v->offset + v->view_offs; + cl_ulong offset_o = extra_o->offset + dst->view_offs; + cl_mem mask_buffer = extra_mask ? extra_mask->data_device : NULL; + cl_ulong offset_mask = extra_mask ? extra_mask->offset + mask->view_offs : 0; + cl_mem sinks_buffer = extra_sinks ? extra_sinks->data_device : NULL; + cl_ulong offset_sinks = extra_sinks ? extra_sinks->offset + sinks->view_offs : 0; + + const cl_ulong q_nb1 = q->nb[1]; + const cl_ulong q_nb2 = q->nb[2]; + const cl_ulong q_nb3 = q->nb[3]; + + cl_ulong k_nb1 = k->nb[1]; + cl_ulong k_nb2 = k->nb[2]; + cl_ulong k_nb3 = k->nb[3]; + + cl_ulong v_nb1 = v->nb[1]; + cl_ulong v_nb2 = v->nb[2]; + cl_ulong v_nb3 = v->nb[3]; + + const cl_ulong o_nb1 = dst->nb[1]; + const cl_ulong o_nb2 = dst->nb[2]; + const cl_ulong o_nb3 = dst->nb[3]; + + const cl_ulong mask_nb1 = mask ? mask->nb[1] : 0; + const cl_ulong mask_nb2 = mask ? mask->nb[2] : 0; + const cl_ulong mask_nb3 = mask ? mask->nb[3] : 0; + const int mask_ne2 = mask ? mask->ne[2] : 0; + const int mask_ne3 = mask ? mask->ne[3] : 0; + + float scale; + float max_bias; + float logit_softcap; + + const float * params = (const float *)dst->op_params; + scale = params[0]; + max_bias = params[1]; + logit_softcap = params[2]; + + bool use_q1_vec = false; + bool use_q1_vec_mq = false; + bool use_local_tile = false; + // KV-head-coalesced gate: gqa_ratio == compile-time MQ_GQA + // restricts to DK=DV=256 for now due to local memory size + const int gqa_ratio_dispatch = n_head_kv > 0 ? (n_head / n_head_kv) : 0; + if (n_q == 1) { + if (use_native_q8_0_q1) { + if (d_head_v >= 256 && + backend_ctx->fa.f32_q8_0_q1_vec.count(dk_dv) > 0) { + kernel = backend_ctx->fa.f32_q8_0_q1_vec.at(dk_dv); + use_q1_vec = true; + } else { + kernel = backend_ctx->fa.f32_q8_0_q1.at(dk_dv); + } + } else if (use_native_q4_0_q1) { + // q4_0 vec kernel uses per-lane dp4a (cl_khr_integer_dot_product) + const char * q4vec_env = getenv("GGML_OPENCL_FA_Q4_VEC"); + const bool q4vec_off = (q4vec_env != NULL) && (q4vec_env[0] == '0'); + if (!q4vec_off && d_head_v >= 256 && + backend_ctx->fa.f32_q4_0_q1_vec.count(dk_dv) > 0) { + kernel = backend_ctx->fa.f32_q4_0_q1_vec.at(dk_dv); + use_q1_vec = true; + } else { + kernel = backend_ctx->fa.f32_q4_0_q1.at(dk_dv); + } + } else if (is_mixed) { + static const char * lt_env = getenv("GGML_OPENCL_FA_LOCAL_TILE"); + static const bool lt_on = (lt_env != NULL) && (lt_env[0] != '0'); + if (lt_on && d_head_q == 128 && d_head_v == 128 && + backend_ctx->fa.f32_f16_q1_local_tile.count(dk_dv) > 0) { + kernel = backend_ctx->fa.f32_f16_q1_local_tile.at(dk_dv); + use_local_tile = true; + } else { + static const char * f16_vec_dk128_env = getenv("GGML_OPENCL_FA_F16_VEC_DK128"); + static const bool f16_vec_dk128_off = (f16_vec_dk128_env != NULL) && (f16_vec_dk128_env[0] == '0'); + const int dv_gate = f16_vec_dk128_off ? 256 : 128; + if (d_head_v >= dv_gate && + backend_ctx->fa.f32_f16_q1_vec.count(dk_dv) > 0) { + kernel = backend_ctx->fa.f32_f16_q1_vec.at(dk_dv); + use_q1_vec = true; + } else { + kernel = backend_ctx->fa.f32_f16_q1.at(dk_dv); + } + } + } else if (is_f16) { + kernel = backend_ctx->fa.f16_q1.at(dk_dv); + } else { + kernel = backend_ctx->fa.f32_q1.at(dk_dv); + } + } else { + if (use_native_q8_0) { + kernel = use_split_q8_0 + ? backend_ctx->fa.f32_q8_0_split.at(dk_dv) + : backend_ctx->fa.f32_q8_0.at(dk_dv); + } else if (use_native_q4_0) { + kernel = use_split_q4_0 + ? backend_ctx->fa.f32_q4_0_split.at(dk_dv) + : backend_ctx->fa.f32_q4_0.at(dk_dv); + } else if (is_mixed) { + if (use_split_kernel) { + // DK=512 prefill: opt-in texture-cache K reads (image1d_buffer_t). + static const char * pkimg_env = getenv("GGML_OPENCL_FA_PREFILL_K_IMG"); + const bool pkimg_on = (pkimg_env != NULL) && (pkimg_env[0] != '0'); + if (d_head_q == 512 && pkimg_on && + backend_ctx->fa.f32_f16_split_k_img.count(dk_dv) > 0) { + kernel = backend_ctx->fa.f32_f16_split_k_img.at(dk_dv); + use_prefill_k_img = true; + } else { + kernel = backend_ctx->fa.f32_f16_split.at(dk_dv); + } + } else { + kernel = backend_ctx->fa.f32_f16.at(dk_dv); + } + } else if (is_f16) { + kernel = backend_ctx->fa.f16.at(dk_dv); + } else { + kernel = backend_ctx->fa.f32.at(dk_dv); + } + } + + // Intel goes to the basic q1 kernel + if (backend_ctx->gpu_family == INTEL && n_q == 1) { + use_q1_vec = use_q1_vec_mq = use_local_tile = false; + if (is_mixed && backend_ctx->fa.f32_f16_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_f16_q1.at(dk_dv); } + else if (is_f16 && backend_ctx->fa.f16_q1.count(dk_dv)) { kernel = backend_ctx->fa.f16_q1.at(dk_dv); } + else if (is_q8_0 && backend_ctx->fa.f32_q8_0_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_q8_0_q1.at(dk_dv); } + else if (is_q4_0 && backend_ctx->fa.f32_q4_0_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_q4_0_q1.at(dk_dv); } + else if (backend_ctx->fa.f32_q1.count(dk_dv)) { kernel = backend_ctx->fa.f32_q1.at(dk_dv); } + } + GGML_ASSERT(kernel != NULL); + + ggml_cl_flash_attn_temp_buffer temp_k; + ggml_cl_flash_attn_temp_buffer temp_v; + ggml_cl_flash_attn_temp_buffer temp_k_pad; + ggml_cl_flash_attn_temp_buffer temp_v_pad; + ggml_cl_flash_attn_temp_buffer temp_mask_pad; + ggml_cl_flash_attn_temp_buffer temp_blk; + const ggml_type kv_target_type = is_f16 ? GGML_TYPE_F16 : GGML_TYPE_F32; + + cl_mem k_data_device = k_soa ? NULL : extra_k->data_device; + cl_mem v_data_device = v_soa ? NULL : extra_v->data_device; + + // SoA q8_0/q4_0 -> reconstruct AoS for downstream kernels that expect + // tight records (no-op when k/v is already AoS). + ggml_cl_flash_attn_temp_buffer temp_k_aos; + ggml_cl_flash_attn_temp_buffer temp_v_aos; + ggml_cl_flash_attn_reconstruct_aos(backend_ctx, k, temp_k_aos, + k_data_device, offset_k, k_nb1, k_nb2, k_nb3); + ggml_cl_flash_attn_reconstruct_aos(backend_ctx, v, temp_v_aos, + v_data_device, offset_v, v_nb1, v_nb2, v_nb3); + + // currently FA kernels support KV cache with f16, f32, q4_0 and q8_0. + // there two cases that these kernels cannot cover, + // 1. KV cache types are q4_0 or q8_0, but the FA kernels fail to compile + // 2. KV cache types not currently supported by an FA kernel, e.g., q4_1 + // these two cases are supported here by dequantizing to f32/f16 and this + // causes performance degradation. + // For q4_0 or q8_0 cases that fail kernel compilation, dequant happens in GPU; + // for types that do not have FA kernels, dequant happens on host. + if (!use_native_q8_0_q1 && !use_native_q8_0 && + !use_native_q4_0_q1 && !use_native_q4_0) { + // for q4_0, q8_0 FA kernels that fail to compile + bool k_done = false; + bool v_done = false; + if (k->type == GGML_TYPE_Q8_0 || k->type == GGML_TYPE_Q4_0) { + k_done = ggml_cl_flash_attn_dequant_kv_gpu( + backend_ctx, k, kv_target_type, k_data_device, offset_k, k_nb1, k_nb2, k_nb3, + temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); + } + if (v->type == GGML_TYPE_Q8_0 || v->type == GGML_TYPE_Q4_0) { + v_done = ggml_cl_flash_attn_dequant_kv_gpu( + backend_ctx, v, kv_target_type, v_data_device, offset_v, v_nb1, v_nb2, v_nb3, + temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); + } + if (!k_done) { + ggml_cl_flash_attn_prepare_quantized_tensor( + backend_ctx, k, kv_target_type, temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); + } + if (!v_done) { + ggml_cl_flash_attn_prepare_quantized_tensor( + backend_ctx, v, kv_target_type, temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); + } + // Asymmetric KV on the F32 fallback path: convert the F16 side to F32 + // too. (Symmetric F16 / mixed paths handle F16 directly.) + if (kv_target_type == GGML_TYPE_F32 && !is_mixed && !is_f16) { + ggml_cl_flash_attn_convert_f16_to_f32(backend_ctx, k, temp_k, k_data_device, offset_k, k_nb1, k_nb2, k_nb3); + ggml_cl_flash_attn_convert_f16_to_f32(backend_ctx, v, temp_v, v_data_device, offset_v, v_nb1, v_nb2, v_nb3); + } + } + + cl_mem k_pad_buffer = NULL; + cl_mem v_pad_buffer = NULL; + cl_mem mask_pad_buffer = NULL; + cl_mem blk_buffer = NULL; + cl_ulong mask_pad_nb1 = 0; + cl_ulong mask_pad_nb2 = 0; + cl_ulong mask_pad_nb3 = 0; + + // Flash-Decoding K-split decision. Resolved here, before the prefill + // prepass, because KV-pad and blk prepass are pure overhead when FD fires. + // Do not infer causality from tensor shapes: a NULL mask means full + // (bidirectional) attention, e.g. ViT encoders, where n_q == n_kv as well. + // Causal attention in llama.cpp always comes with an explicit KQ mask. + // Inferring is_causal here corrupted mmproj output on OpenCL (see #23800). + const int is_causal = 0; + const int fd_max_n_q = (d_head_q <= FD_MAX_DK_MULTI) ? FD_MAX_N_Q_MULTI : 1; + cl_kernel fd_k_split = NULL; + bool use_fd_mq = false; + bool use_fd_mq_decode = false; + int fd_head_sub = 1; + size_t fd_mq_wg = 256; // MQ_GQA=4 kernel: Q1_WG_SIZE(64) * MQ_NSG_SPLIT(4) + bool use_fa_k_img = false; // K bound as image1d_buffer_t instead of (buf, offset) + + { + const char * mq_env = getenv("GGML_OPENCL_FA_MQ"); + const bool mq_enabled = (mq_env == NULL) ? true : (mq_env[0] != '0'); + const bool mq_kv_ok = is_mixed || is_q8_0 || is_q4_0; + + const char * lmq_env = getenv("GGML_OPENCL_FA_LOCAL_MQ_SPLIT"); + const bool lmq_on = (lmq_env != NULL) && (lmq_env[0] != '0'); + + static const char * vec_nq_env = getenv("GGML_OPENCL_FA_VEC_NQ"); + static const int N_MAX_VEC_NQ = (vec_nq_env != NULL && vec_nq_env[0] != '\0') + ? atoi(vec_nq_env) : 1; + + const bool nq_in_vec_range = (n_q >= 1) && (n_q <= N_MAX_VEC_NQ); + const bool nq1_only = (n_q == 1); + + // Cluster-parallel decode default on for Adreno X2E/X1E + static const int c8_env_state = []{ + const char * e = getenv("GGML_OPENCL_FA_C8"); + if (e == NULL || e[0] == '\0') { return -1; } + return (e[0] != '0') ? 1 : 0; + }(); + const bool c8_default_on = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E; + const bool c8_f16_on = (c8_env_state >= 0) ? (c8_env_state == 1) : c8_default_on; + // Quant-KV (q4_0/q8_0) GQA4 c8: default-on X2E + X1E + const bool c8_quant_on = (c8_env_state >= 0) ? (c8_env_state == 1) : c8_default_on; + if (mq_enabled && mq_kv_ok && nq_in_vec_range && !is_causal && + backend_ctx->gpu_family != INTEL && + !use_local_tile && + n_kv >= (mq_decode_shape ? 32 : FD_MIN_N_KV) && + backend_ctx->fa.f32_merge.count(dk_dv) > 0) { + if (mq_decode_shape && backend_ctx->fa.f32_f16_mq_decode.count(mq_decode_key) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_mq_decode.at(mq_decode_key); + fd_mq_wg = backend_ctx->fa.f32_f16_mq_decode_wg.at(mq_decode_key); + fd_head_sub = backend_ctx->fa.f32_f16_mq_decode_hs.at(mq_decode_key); + use_fd_mq = true; + use_fd_mq_decode = true; + } else if (nq1_only && lmq_on && is_mixed && d_head_q == 128 && d_head_v == 128 && + gqa_ratio_dispatch == 8 && + backend_ctx->fa.f32_f16_q1_local_mq_split_g8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_local_mq_split_g8.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 64; + } else if (nq1_only && lmq_on && is_mixed && d_head_q == 128 && d_head_v == 128 && + gqa_ratio_dispatch == 4 && + backend_ctx->fa.f32_f16_q1_local_mq_split.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_local_mq_split.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 64; + } else if (nq1_only && is_mixed && gqa_ratio_dispatch == 4 && + ((d_head_q == 256 && d_head_v == 256) || + (d_head_q == 128 && d_head_v == 128)) && + backend_ctx->fa.f32_f16_q1_vec_mq_split.count(dk_dv) > 0) { + const bool k_img_on = d_head_q == 128 && d_head_v == 128 && + getenv("GGML_OPENCL_FA_K_IMG") != NULL && + getenv("GGML_OPENCL_FA_K_IMG")[0] != '0' && + backend_ctx->fa.f32_f16_q1_vec_mq_split_k_img.count(dk_dv) > 0; + // Cluster-parallel decode + const bool c8_env = d_head_q == 128 && d_head_v == 128 && c8_f16_on; + if (c8_env && backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.at(dk_dv); + use_fd_mq = true; + } else if (c8_env && backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 128; + } else if (k_img_on) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_k_img.at(dk_dv); + use_fd_mq = true; + use_fa_k_img = true; + } else { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split.at(dk_dv); + use_fd_mq = true; + } + // Cluster-parallel decode, DK=DV=256 GQA=8 + } else if (nq1_only && is_mixed && gqa_ratio_dispatch == 8 && + d_head_q == 256 && d_head_v == 256 && + c8_env_state == 1 && + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c32.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c32.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 128; + // Cluster-parallel decode for the g8 + } else if (is_mixed && gqa_ratio_dispatch == 8 && + d_head_q == 128 && d_head_v == 128 && + c8_f16_on && + (backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.count(dk_dv) > 0 || + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8_ns2.count(dk_dv) > 0)) { + if (backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8.at(dk_dv); + fd_mq_wg = 192; + } else { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_c8_ns2.at(dk_dv); + fd_mq_wg = 128; + } + use_fd_mq = true; + } else if (is_mixed && gqa_ratio_dispatch == 8 && + d_head_q == 128 && d_head_v == 128 && + getenv("GGML_OPENCL_FA_K_IMG") != NULL && + getenv("GGML_OPENCL_FA_K_IMG")[0] != '0' && + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_k_img.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8_k_img.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 192; + use_fa_k_img = true; + } else if (is_mixed && gqa_ratio_dispatch == 8 && + d_head_q == 128 && d_head_v == 128 && + backend_ctx->fa.f32_f16_q1_vec_mq_split_g8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 192; + } else if (nq1_only && is_q8_0 && gqa_ratio_dispatch == 8 && + d_head_q == 128 && d_head_v == 128 && + backend_ctx->fa.f32_q8_0_q1_vec_mq_split_g8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_q8_0_q1_vec_mq_split_g8.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 192; + } else if (nq1_only && is_q8_0 && gqa_ratio_dispatch == 4 && + d_head_q == 128 && d_head_v == 128 && + backend_ctx->fa.f32_q8_0_q1_vec_mq_split.count(dk_dv) > 0) { + // Cluster-parallel q8_0 GQA4 + if (c8_quant_on && + backend_ctx->fa.f32_q8_0_q1_vec_mq_split_c8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_q8_0_q1_vec_mq_split_c8.at(dk_dv); + fd_mq_wg = 128; + } else { + fd_k_split = backend_ctx->fa.f32_q8_0_q1_vec_mq_split.at(dk_dv); + } + use_fd_mq = true; + } else if (nq1_only && is_q4_0) { + const char * q4_mq_env = getenv("GGML_OPENCL_FA_Q4_MQ"); + const bool q4_mq_on = (q4_mq_env != NULL) && (q4_mq_env[0] != '0'); + // Cluster-parallel q4_0 + const bool q4_c8_on = c8_env_state == 1 && + backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8_c8.count(dk_dv) > 0; + if (q4_c8_on && gqa_ratio_dispatch == 8 && + d_head_q == 64 && d_head_v == 64) { + fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8_c8.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 128; + } else if (q4_mq_on && gqa_ratio_dispatch == 8 && + d_head_q == 128 && d_head_v == 128 && + backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split_g8.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 192; + } else if (gqa_ratio_dispatch == 4 && + d_head_q == 128 && d_head_v == 128 && + backend_ctx->fa.f32_q4_0_q1_vec_mq_split.count(dk_dv) > 0) { + // Cluster-parallel q4_0 GQA4 + if (c8_quant_on && + backend_ctx->fa.f32_q4_0_q1_vec_mq_split_c8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split_c8.at(dk_dv); + fd_mq_wg = 128; + } else { + fd_k_split = backend_ctx->fa.f32_q4_0_q1_vec_mq_split.at(dk_dv); + } + use_fd_mq = true; + } + } + } + } + // Intel cluster-parallel decode FA + if (fd_k_split == NULL && backend_ctx->gpu_family == INTEL && n_q == 1 && !is_causal && + is_mixed && gqa_ratio_dispatch == 4 && d_head_q == 128 && d_head_v == 128 && + n_kv >= FD_MIN_N_KV && + getenv("GGML_OPENCL_FA_C8") != NULL && getenv("GGML_OPENCL_FA_C8")[0] != '0' && + backend_ctx->fa.f32_merge.count(dk_dv) > 0) { + if (backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 128; + } else if (backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_c8_ns2.at(dk_dv); + use_fd_mq = true; + fd_mq_wg = 64; + } + } + if (fd_k_split == NULL && + n_q >= 1 && n_q <= fd_max_n_q && n_kv >= FD_MIN_N_KV && !is_causal && + d_head_q <= FD_MAX_DK && + backend_ctx->fa.f32_merge.count(dk_dv) > 0) { + if (is_mixed && backend_ctx->fa.f32_f16_q1_split.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_f16_q1_split.at(dk_dv); + } else if (is_q8_0 && backend_ctx->fa.f32_q8_0_q1_split.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_q8_0_q1_split.at(dk_dv); + } else if (is_q4_0 && backend_ctx->fa.f32_q4_0_q1_split.count(dk_dv) > 0) { + fd_k_split = backend_ctx->fa.f32_q4_0_q1_split.at(dk_dv); + } + } + const bool use_fd = (fd_k_split != NULL); + + const int n_q_blocks = n_q > 1 ? (n_q + block_m - 1) / block_m : 0; + const int n_kv_blocks = (n_kv > 0 && block_n > 0) ? (n_kv + block_n - 1) / block_n : 0; + // KV pad + blk prepass are pure overhead when FD will fire - skip them. + const bool use_mixed_prepass = is_mixed && n_q > 1 && !use_fd; + // make sure prepass kernels are compiled + const bool have_kv_pad = backend_ctx->fa.kv_pad_f16.count(dk_dv) > 0; + const bool have_blk = backend_ctx->fa.blk_f16.count(dk_dv) > 0; + const bool use_kv_pad = use_mixed_prepass && (n_kv % block_n != 0) && have_kv_pad; + // blk prepass: per-KV-tile mask class (0=masked, 1=mixed, 2=unmasked). + // Consumed identically by f32_f16, q8_0 and q4_0 prefill kernels. + const bool use_quant_prepass = (use_native_q8_0 || use_native_q4_0) && !use_fd; + const bool use_blk_mask = (use_mixed_prepass || use_quant_prepass) && mask_buffer != NULL && have_blk; + + if (use_kv_pad) { + cl_int err; + + const size_t k_pad_size = (size_t) k_nb1 * (size_t) block_n * (size_t) n_head_kv * (size_t) n_batch; + temp_k_pad.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, k_pad_size, NULL, &err); + CL_CHECK(err); + k_pad_buffer = temp_k_pad.data; + + const size_t v_pad_size = (size_t) v_nb1 * (size_t) block_n * (size_t) n_head_kv * (size_t) n_batch; + temp_v_pad.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, v_pad_size, NULL, &err); + CL_CHECK(err); + v_pad_buffer = temp_v_pad.data; + + cl_kernel kernel_kv_pad = backend_ctx->fa.kv_pad_f16.at(dk_dv); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 0, sizeof(cl_mem), &k_data_device)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 1, sizeof(cl_ulong), &offset_k)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 2, sizeof(cl_mem), &v_data_device)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 3, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 4, sizeof(cl_mem), &k_pad_buffer)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 5, sizeof(cl_mem), &v_pad_buffer)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 6, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 7, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 8, sizeof(int), &n_batch)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 9, sizeof(cl_ulong), &k_nb1)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 10, sizeof(cl_ulong), &k_nb2)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 11, sizeof(cl_ulong), &k_nb3)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 12, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 13, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(kernel_kv_pad, 14, sizeof(cl_ulong), &v_nb3)); + + size_t global_work_size[] = { (size_t) block_n, (size_t) n_head_kv, (size_t) n_batch }; + backend_ctx->enqueue_ndrange_kernel(kernel_kv_pad, 3, global_work_size, NULL, dst); + + if (mask_buffer != NULL) { + mask_pad_nb1 = (cl_ulong) block_n * (cl_ulong) sizeof(ggml_fp16_t); + mask_pad_nb2 = (cl_ulong) n_q * mask_pad_nb1; + mask_pad_nb3 = (cl_ulong) mask_ne2 * mask_pad_nb2; + + const size_t mask_pad_size = (size_t) mask_ne3 * (size_t) mask_pad_nb3; + temp_mask_pad.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, mask_pad_size, NULL, &err); + CL_CHECK(err); + mask_pad_buffer = temp_mask_pad.data; + + cl_kernel kernel_mask_pad = backend_ctx->fa.mask_pad_f16.at(dk_dv); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 0, sizeof(cl_mem), &mask_buffer)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 1, sizeof(cl_ulong), &offset_mask)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 2, sizeof(cl_mem), &mask_pad_buffer)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 3, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 4, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 5, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 6, sizeof(cl_ulong), &mask_nb2)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 7, sizeof(cl_ulong), &mask_nb3)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 8, sizeof(int), &mask_ne2)); + CL_CHECK(clSetKernelArg(kernel_mask_pad, 9, sizeof(int), &mask_ne3)); + + size_t global_work_size_mask[] = { (size_t) block_n, (size_t) n_q, (size_t) (mask_ne2 * mask_ne3) }; + backend_ctx->enqueue_ndrange_kernel(kernel_mask_pad, 3, global_work_size_mask, NULL, dst); + } + } + + if (use_blk_mask) { + cl_int err; + const size_t blk_size = (size_t) n_kv_blocks * (size_t) n_q_blocks * (size_t) mask_ne2 * (size_t) mask_ne3; + temp_blk.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, blk_size, NULL, &err); + if (err != CL_SUCCESS) { + // Flush before retry - reclaim deferred driver deallocations. + CL_CHECK(clFinish(backend_ctx->queue)); + temp_blk.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, blk_size, NULL, &err); + } + CL_CHECK(err); + blk_buffer = temp_blk.data; + + cl_kernel kernel_blk = backend_ctx->fa.blk_f16.at(dk_dv); + CL_CHECK(clSetKernelArg(kernel_blk, 0, sizeof(cl_mem), &mask_buffer)); + CL_CHECK(clSetKernelArg(kernel_blk, 1, sizeof(cl_ulong), &offset_mask)); + CL_CHECK(clSetKernelArg(kernel_blk, 2, sizeof(cl_mem), &blk_buffer)); + CL_CHECK(clSetKernelArg(kernel_blk, 3, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel_blk, 4, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel_blk, 5, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel_blk, 6, sizeof(cl_ulong), &mask_nb2)); + CL_CHECK(clSetKernelArg(kernel_blk, 7, sizeof(cl_ulong), &mask_nb3)); + CL_CHECK(clSetKernelArg(kernel_blk, 8, sizeof(int), &mask_ne2)); + CL_CHECK(clSetKernelArg(kernel_blk, 9, sizeof(int), &mask_ne3)); + + size_t global_work_size_blk[] = { (size_t) n_kv_blocks, (size_t) n_q_blocks, (size_t) (mask_ne2 * mask_ne3) }; + backend_ctx->enqueue_ndrange_kernel(kernel_blk, 3, global_work_size_blk, NULL, dst); + } + + const int n_head_log2_val = n_head > 0 ? 1u << (int)floorf(log2f((float)n_head)) : 0; + const float n_head_log2_f = n_head_log2_val > 0 ? (float)n_head_log2_val : 1.0f; + const float m0 = powf(2.0f, -(max_bias) / n_head_log2_f); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2_f); + + if (use_fd) { + static const int fd_env_kv_per_split = []{ + const char * e = getenv("GGML_OPENCL_FD_KV_PER_SPLIT"); + return (e && e[0]) ? atoi(e) : 0; + }(); + static const int fd_env_max_splits = []{ + const char * e = getenv("GGML_OPENCL_FD_MAX_SPLITS"); + return (e && e[0]) ? atoi(e) : 0; + }(); + + int fd_kv_per_split = use_fd_mq ? FD_MQ_KV_PER_SPLIT + : (is_mixed ? FD_KV_PER_SPLIT_F16 : FD_KV_PER_SPLIT); + int fd_max_splits = use_fd_mq ? FD_MQ_MAX_SPLITS : FD_MAX_SPLITS; + if (fd_env_kv_per_split > 0) { fd_kv_per_split = fd_env_kv_per_split; } + if (fd_env_max_splits > 0) { fd_max_splits = fd_env_max_splits; } + int n_splits = (n_kv + fd_kv_per_split - 1) / fd_kv_per_split; + if (n_splits < FD_MIN_SPLITS) { n_splits = FD_MIN_SPLITS; } + if (n_splits > fd_max_splits) { n_splits = fd_max_splits; } + if (use_fd_mq_decode) { + const size_t wg_per_split = (size_t) n_head_kv * n_batch; + const size_t wg_target = 4 * (size_t) backend_ctx->fa.compute_units; + while (wg_per_split * n_splits < wg_target && n_splits < fd_max_splits && + n_kv / (n_splits + 1) >= 32) { + n_splits++; + } + } + const int kv_per_split = (n_kv + n_splits - 1) / n_splits; + + const int fa_partial_floats = 2 + d_head_v; + const size_t partial_size_bytes = + (size_t) n_batch * n_head * n_q * n_splits * fa_partial_floats * sizeof(float); + + ggml_cl_flash_attn_temp_buffer temp_partial; + cl_mem partial_buffer; + cl_int err; + if (use_fd_mq_decode) { + auto & pool = backend_ctx->fa.fd_partial; + if (partial_size_bytes > pool.size) { + CL_CHECK(clFinish(backend_ctx->queue)); + pool.allocate(backend_ctx->context, partial_size_bytes); + } + partial_buffer = pool.buffer; + } else { + temp_partial.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, + partial_size_bytes, NULL, &err); + if (err != CL_SUCCESS) { + CL_CHECK(clFinish(backend_ctx->queue)); + temp_partial.data = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, + partial_size_bytes, NULL, &err); + } + CL_CHECK(err); + partial_buffer = temp_partial.data; + } + + cl_kernel k_split = fd_k_split; + int argi = 0; + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &extra_q->data_device)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_q)); + if (use_fa_k_img) { + const size_t nb00_bytes = sizeof(uint16_t); + const size_t k_bytes_span = + (size_t)(n_kv > 0 ? n_kv - 1 : 0) * (size_t)k_nb1 + + (size_t)(n_head_kv > 0 ? n_head_kv - 1 : 0) * (size_t)k_nb2 + + (size_t)(n_batch > 0 ? n_batch - 1 : 0) * (size_t)k_nb3 + + (size_t)d_head_q * nb00_bytes; + const size_t k_bytes = (k_bytes_span + 7) & ~(size_t)7; + const size_t k_pixels = k_bytes >> 3; + cl_mem k_img = nullptr; + if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { + k_img = ggml_cl_img_pool_get_or_create( + backend_ctx, backend_ctx->kq_img_pool, + k_data_device, offset_k, k_bytes, CL_HALF_FLOAT); + } + + // if image creation fails, fallback to buffer based kernels + if (k_img == nullptr) { + if (gqa_ratio_dispatch == 4 && + backend_ctx->fa.f32_f16_q1_vec_mq_split.count(dk_dv) > 0) { + k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split.at(dk_dv); + } else { + k_split = backend_ctx->fa.f32_f16_q1_vec_mq_split_g8.at(dk_dv); + } + use_fa_k_img = false; + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &k_data_device)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_k)); + } else { + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &k_img)); + } + } else { + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &k_data_device)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_k)); + } + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &v_data_device)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &q_nb1)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &q_nb2)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &q_nb3)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &k_nb1)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &k_nb2)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &k_nb3)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &v_nb3)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_head_log2_val)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(float), &logit_softcap)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &mask_buffer)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &offset_mask)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &mask_nb2)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_ulong), &mask_nb3)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &mask_ne2)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &mask_ne3)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(cl_mem), &partial_buffer)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &n_splits)); + CL_CHECK(clSetKernelArg(k_split, argi++, sizeof(int), &kv_per_split)); + + // MQ split kernel uses MQ_NSG_SPLIT subgroups and one WG per (kv_head, batch, split) + // matches Q1_WG_SIZE * NSG (MQ_GQA=4 -> 256; MQ_GQA=8 -> 192) + const size_t fd_wg = use_fd_mq ? fd_mq_wg : 64; + const size_t fd_head_dim = use_fd_mq + ? (size_t)(n_head_kv * fd_head_sub * n_batch) + : (size_t)(n_head * n_batch); + size_t fd_lws[3] = { fd_wg, 1, 1 }; + // gid(2) packs q_idx * n_splits + split_idx. + size_t fd_gws[3] = { fd_wg, fd_head_dim, (size_t)(n_splits * n_q) }; + backend_ctx->enqueue_ndrange_kernel(k_split, 3, fd_gws, fd_lws, dst); + + cl_kernel k_merge = backend_ctx->fa.f32_merge.at(dk_dv); + argi = 0; + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_mem), &partial_buffer)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_mem), &extra_o->data_device)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &offset_o)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(int), &n_splits)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &o_nb1)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &o_nb2)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &o_nb3)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_mem), &sinks_buffer)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(cl_ulong), &offset_sinks)); + CL_CHECK(clSetKernelArg(k_merge, argi++, sizeof(int), &n_q)); + + const size_t merge_wg = (size_t) (d_head_v / 4); // one lane per float4 + size_t merge_lws[3] = { merge_wg, 1, 1 }; + size_t merge_gws[3] = { merge_wg, (size_t)(n_head * n_batch), (size_t) n_q }; + backend_ctx->enqueue_ndrange_kernel(k_merge, 3, merge_gws, merge_lws, dst); + return; + } + + cl_mem prefill_k_img = nullptr; + if (use_prefill_k_img) { + const size_t nb00_bytes = sizeof(uint16_t); + const size_t k_bytes_span = + (size_t)(n_kv > 0 ? n_kv - 1 : 0) * (size_t)k_nb1 + + (size_t)(n_head_kv > 0 ? n_head_kv - 1 : 0) * (size_t)k_nb2 + + (size_t)(n_batch > 0 ? n_batch - 1 : 0) * (size_t)k_nb3 + + (size_t)d_head_q * nb00_bytes; + const size_t k_bytes = (k_bytes_span + 7) & ~(size_t)7; + const size_t k_pixels = k_bytes >> 3; + if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { + prefill_k_img = ggml_cl_img_pool_get_or_create( + backend_ctx, backend_ctx->kq_img_pool, + k_data_device, offset_k, k_bytes, CL_HALF_FLOAT); + } + if (prefill_k_img == nullptr) { + kernel = backend_ctx->fa.f32_f16_split.at(dk_dv); + use_prefill_k_img = false; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_q->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), use_prefill_k_img ? &prefill_k_img : &k_data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_k)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &v_data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset_v)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra_o->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset_o)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n_q)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n_kv)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &is_causal)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &q_nb1)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &q_nb2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &q_nb3)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &k_nb1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &k_nb2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &k_nb3)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &v_nb1)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &v_nb2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &v_nb3)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &o_nb1)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &o_nb2)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &o_nb3)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(int), &n_head_log2_val)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(float), &logit_softcap)); + CL_CHECK(clSetKernelArg(kernel, 30, sizeof(int), &n_head_kv)); + CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_mem), &mask_buffer)); + CL_CHECK(clSetKernelArg(kernel, 32, sizeof(cl_ulong), &offset_mask)); + CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_ulong), &mask_nb1)); + CL_CHECK(clSetKernelArg(kernel, 34, sizeof(cl_ulong), &mask_nb2)); + CL_CHECK(clSetKernelArg(kernel, 35, sizeof(cl_ulong), &mask_nb3)); + CL_CHECK(clSetKernelArg(kernel, 36, sizeof(int), &mask_ne2)); + CL_CHECK(clSetKernelArg(kernel, 37, sizeof(int), &mask_ne3)); + CL_CHECK(clSetKernelArg(kernel, 38, sizeof(cl_mem), &sinks_buffer)); + CL_CHECK(clSetKernelArg(kernel, 39, sizeof(cl_ulong), &offset_sinks)); + if (n_q > 1 && is_mixed) { + CL_CHECK(clSetKernelArg(kernel, 40, sizeof(cl_mem), &k_pad_buffer)); + CL_CHECK(clSetKernelArg(kernel, 41, sizeof(cl_mem), &v_pad_buffer)); + CL_CHECK(clSetKernelArg(kernel, 42, sizeof(cl_mem), &mask_pad_buffer)); + CL_CHECK(clSetKernelArg(kernel, 43, sizeof(cl_mem), &blk_buffer)); + CL_CHECK(clSetKernelArg(kernel, 44, sizeof(int), &n_kv_blocks)); + CL_CHECK(clSetKernelArg(kernel, 45, sizeof(cl_ulong), &mask_pad_nb1)); + CL_CHECK(clSetKernelArg(kernel, 46, sizeof(cl_ulong), &mask_pad_nb2)); + CL_CHECK(clSetKernelArg(kernel, 47, sizeof(cl_ulong), &mask_pad_nb3)); + } else if (use_native_q8_0 || use_native_q4_0) { + // arg 40 = blk classification buffer (NULL disables prepass opt). + CL_CHECK(clSetKernelArg(kernel, 40, sizeof(cl_mem), &blk_buffer)); + } + + if (n_q == 1) { + if (use_local_tile) { + const size_t lt_wg = 128; + size_t local_work_size[] = { lt_wg, 1, 1 }; + size_t global_work_size[] = { lt_wg, (size_t) n_head, (size_t) n_batch }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else { + // q1_vec dispatches with NSG subgroups + const size_t q1_wg = backend_ctx->gpu_family == INTEL ? 32 : 64; + const size_t wg_size = use_q1_vec ? 256 : q1_wg; + const size_t head_dim_global = use_q1_vec_mq + ? (size_t)(n_head_kv * n_batch) + : (size_t)(n_head * n_batch); + size_t local_work_size[] = { wg_size, 1 }; + size_t global_work_size[] = { wg_size, head_dim_global }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); + } + } else if (use_native_q8_0 || use_native_q4_0) { + // Native quant prefill. The split variant may override BLOCK_M + // (e.g. DK=96 quant uses BM=16). + const bool use_split = use_native_q8_0 ? use_split_q8_0 : use_split_q4_0; + int bm; + size_t wg_size; + if (use_split) { + bm = use_native_q8_0 ? backend_ctx->fa.f32_q8_0_split_bm.at(dk_dv) + : backend_ctx->fa.f32_q4_0_split_bm.at(dk_dv); + wg_size = use_native_q8_0 ? backend_ctx->fa.f32_q8_0_split_wg_size.at(dk_dv) + : backend_ctx->fa.f32_q4_0_split_wg_size.at(dk_dv); + } else { + bm = backend_ctx->fa.bm.at(dk_dv); + wg_size = (size_t) bm; + } + size_t local_work_size[] = { wg_size, 1 }; + size_t global_work_size[] = { (size_t)((n_q + bm - 1) / bm) * wg_size, (size_t)(n_head * n_batch) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); + } else { + const size_t wg_size = (size_t) wg_size_fa; + size_t local_work_size[] = { wg_size, 1 }; + size_t global_work_size[] = { (size_t)((n_q + block_m - 1) / block_m) * wg_size, (size_t)(n_head * n_batch) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/gated_delta_net.cpp b/ggml/src/ggml-opencl/ops/gated_delta_net.cpp new file mode 100644 index 000000000000..c4158351cc61 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/gated_delta_net.cpp @@ -0,0 +1,328 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_gated_delta_net(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // gated_delta_net: one kernel per (S_V, KDA, tgpp, replay). + { + #ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gated_delta_net.cl.h" + }; + #else + const std::string kernel_src = read_file("gated_delta_net.cl"); + #endif + + const int gdn_sizes[4] = { 16, 32, 64, 128 }; + const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1; + if (sg_size < 0) { + GGML_LOG_ERROR("Unsupported GPU Family: only Adreno and Intel are supported.\n"); + exit(1); + } + + for (int si = 0; si < 4; si++) { + const int S_V = gdn_sizes[si]; + + // MUST match the dispatcher heuristic in ggml_cl_gated_delta_net exactly. + int lanes_per_column; + if (S_V >= 128) { + lanes_per_column = 8; + } else { + lanes_per_column = std::min(S_V, sg_size); + } + + // Round LANES_PER_COLUMN down until it is: + // * power-of-two + // * divides both S_V and sg_size + while (lanes_per_column > 1 && + (((lanes_per_column & (lanes_per_column - 1)) != 0) || + (S_V % lanes_per_column) != 0 || + (sg_size % lanes_per_column) != 0)) { + lanes_per_column >>= 1; + } + + GGML_ASSERT(lanes_per_column >= 1); + GGML_ASSERT(((lanes_per_column & (lanes_per_column - 1)) == 0)); + GGML_ASSERT((S_V % lanes_per_column) == 0); + GGML_ASSERT((sg_size % lanes_per_column) == 0); + + const bool is_partial_reduce = (lanes_per_column != 1) && (lanes_per_column < sg_size); + int use_qcom_shuffle = 0; + if (is_partial_reduce) { + if (backend_ctx->has_qcom_subgroup_shuffle) { + use_qcom_shuffle = 1; + } + } + for (int kda = 0; kda < 2; kda++) { + for (int tgpp = 0; tgpp < 2; tgpp++) { + const int cpl = (tgpp == 0) ? 1 : 4; + const int spw = (tgpp == 0) ? 1 : 1; + + std::string opts = compile_opts; + opts += " -DS_V=" + std::to_string(S_V); + opts += " -DKDA=" + std::to_string(kda); + opts += " -DSUBGROUP_SIZE=" + std::to_string(sg_size); + opts += " -DLANES_PER_COLUMN=" + std::to_string(lanes_per_column); + opts += " -DCOLS_PER_LANE_GROUP=" + std::to_string(cpl); + opts += " -DUSE_QCOM_SUBGROUP_SHUFFLE=" + std::to_string(use_qcom_shuffle); + + // Since spw=1 is found to be optimal, SUBGROUPS_PER_WG > 1 code in + // the kernel is removed. If you want to experiment with spw > 1, + // Please remember to implement code to handle it. + opts += " -DSUBGROUPS_PER_WG=" + std::to_string(spw); + + for (int replay = 0; replay < 2; replay++) { + const std::string opts_rep = opts + " -DREPLAY=" + std::to_string(replay); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts_rep); + + CL_CHECK((backend_ctx->gated_delta_net.kernel_gated_delta_net_f32[si][kda][tgpp][replay] = + clCreateKernel(prog, "kernel_gated_delta_net", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + } + } + } + GGML_LOG_CONT("."); + } +} + +void ggml_cl_gated_delta_net(ggml_backend_t backend, ggml_tensor * dst) { + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + const ggml_tensor * src_q = dst->src[0]; + const ggml_tensor * src_k = dst->src[1]; + const ggml_tensor * src_v = dst->src[2]; + const ggml_tensor * src_g = dst->src[3]; + const ggml_tensor * src_beta = dst->src[4]; + const ggml_tensor * src_state = dst->src[5]; + + GGML_ASSERT(src_q && src_q->extra); + GGML_ASSERT(src_k && src_k->extra); + GGML_ASSERT(src_v && src_v->extra); + GGML_ASSERT(src_g && src_g->extra); + GGML_ASSERT(src_beta && src_beta->extra); + GGML_ASSERT(src_state && src_state->extra); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const cl_uint S_v = (cl_uint) src_v->ne[0]; + const cl_uint H_v = (cl_uint) src_v->ne[1]; + const cl_uint n_tokens = (cl_uint) src_v->ne[2]; + const cl_uint n_seqs = (cl_uint) src_v->ne[3]; + const cl_uint K = (cl_uint) ggml_get_op_params_i32(dst, 0); + const bool replay = dst->src[6] != nullptr; + const cl_uint n_pend = replay ? (cl_uint) ggml_get_op_params_i32(dst, 1) : 0; + const cl_uint keep = replay ? (cl_uint) ggml_get_op_params_i32(dst, 2) : 0; + + int si; + switch (S_v) { + case 16: si = 0; break; + case 32: si = 1; break; + case 64: si = 2; break; + case 128: si = 3; break; + default: + GGML_ASSERT(false && "ggml_cl_gated_delta_net: unsupported S_v"); + } + + const int kda = (src_g->ne[0] == (int64_t) S_v) ? 1 : 0; + + // TODO: Optimize when S_v!=128. Not necessary for now as Qwen3.5/6 are all S_v=128 + // token generation mode (tgpp=0): + // process 1 token at a time, so columns per lane (cpl) == 1 + // prompt processing mode (tgpp=1): + // cpl=4 to process 4 tokens for single-token. 4 is chosen for Adreno 750 as per + // work-item/thread has at most 128 registers. + // All Qwen3.5/6 models are S_v == 128, so LANES_PER_COLUMN == 8 + // such that ROWS_PER_LANE = 128/8 = 16 + // Variables in the kernel: + // k_reg, q_reg, g_exp are all 16 floats + // s_shard has cpl*ROWS_PER_LANE = 4*16 = 64 floats + // Total 112 registers used. + // subgroups_per_workgroup (spw) can be set to 1,2,4,8,16 for tg and 1,2,4 for pp + // for S_v=128. + // Empirically found that when spw=1, we get the best performance for both tg and pp + const int tgpp = (n_tokens == 1) ? 0 : 1; + const int cpl = (tgpp == 0) ? 1 : 4; + // spw needs adjustment when S_v != 128 + const int spw = (tgpp == 0) ? 1 : 1; + + cl_kernel kernel = backend_ctx->gated_delta_net.kernel_gated_delta_net_f32[si][kda][tgpp][replay]; + GGML_ASSERT(kernel != nullptr); + + const cl_uint s_off = S_v * H_v * n_tokens * n_seqs; + + const cl_uint sq1 = (cl_uint)(src_q->nb[1] / sizeof(float)); + const cl_uint sq2 = (cl_uint)(src_q->nb[2] / sizeof(float)); + const cl_uint sq3 = (cl_uint)(src_q->nb[3] / sizeof(float)); + const cl_uint sk1 = (cl_uint)(src_k->nb[1] / sizeof(float)); + const cl_uint sk2 = (cl_uint)(src_k->nb[2] / sizeof(float)); + const cl_uint sk3 = (cl_uint)(src_k->nb[3] / sizeof(float)); + const cl_uint sv1 = (cl_uint)(src_v->nb[1] / sizeof(float)); + const cl_uint sv2 = (cl_uint)(src_v->nb[2] / sizeof(float)); + const cl_uint sv3 = (cl_uint)(src_v->nb[3] / sizeof(float)); + const cl_uint sb1 = (cl_uint)(src_beta->nb[1] / sizeof(float)); + const cl_uint sb2 = (cl_uint)(src_beta->nb[2] / sizeof(float)); + const cl_uint sb3 = (cl_uint)(src_beta->nb[3] / sizeof(float)); + + const cl_uint H_k = (cl_uint) src_q->ne[1]; + const cl_uint rq3 = (cl_uint)(src_v->ne[3] / src_q->ne[3]); + + const float scale = 1.0f / sqrtf((float) S_v); + + ggml_tensor_extra_cl * extra_q = (ggml_tensor_extra_cl *) src_q->extra; + ggml_tensor_extra_cl * extra_k = (ggml_tensor_extra_cl *) src_k->extra; + ggml_tensor_extra_cl * extra_v = (ggml_tensor_extra_cl *) src_v->extra; + ggml_tensor_extra_cl * extra_g = (ggml_tensor_extra_cl *) src_g->extra; + ggml_tensor_extra_cl * extra_beta = (ggml_tensor_extra_cl *) src_beta->extra; + ggml_tensor_extra_cl * extra_state = (ggml_tensor_extra_cl *) src_state->extra; + ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong off_q = extra_q->offset + src_q->view_offs; + const cl_ulong off_k = extra_k->offset + src_k->view_offs; + const cl_ulong off_v = extra_v->offset + src_v->view_offs; + const cl_ulong off_g = extra_g->offset + src_g->view_offs; + const cl_ulong off_beta = extra_beta->offset + src_beta->view_offs; + const cl_ulong off_state = extra_state->offset + src_state->view_offs; + const cl_ulong off_dst = extra_dst->offset + dst->view_offs; + + int idx = 0; + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_q->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_q)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_k->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_k)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_v->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_v)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_g->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_g)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_beta->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_beta)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_state->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_state)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_dst->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_dst)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_v)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_tokens)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_seqs)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &s_off)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sq3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sk3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sv3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sb1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sb2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &sb3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &H_k)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &rq3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(float), &scale)); + + if (replay) { + const ggml_tensor * src_pk = dst->src[6]; + const ggml_tensor * src_pv = dst->src[7]; + const ggml_tensor * src_pgb = dst->src[8]; + const ggml_tensor * src_rep = dst->src[9]; + + GGML_ASSERT(src_pk && src_pk->extra); + GGML_ASSERT(src_pv && src_pv->extra); + GGML_ASSERT(src_pgb && src_pgb->extra); + GGML_ASSERT(src_rep && src_rep->extra); + + const ggml_tensor_extra_cl * extra_pk = (const ggml_tensor_extra_cl *) src_pk->extra; + const ggml_tensor_extra_cl * extra_pv = (const ggml_tensor_extra_cl *) src_pv->extra; + const ggml_tensor_extra_cl * extra_pgb = (const ggml_tensor_extra_cl *) src_pgb->extra; + const ggml_tensor_extra_cl * extra_rep = (const ggml_tensor_extra_cl *) src_rep->extra; + + const cl_ulong off_pk = extra_pk->offset + src_pk->view_offs; + const cl_ulong off_pv = extra_pv->offset + src_pv->view_offs; + const cl_ulong off_pgb = extra_pgb->offset + src_pgb->view_offs; + const cl_ulong off_rep = extra_rep->offset + src_rep->view_offs; + + const cl_ulong spk1 = src_pk->nb[1] / sizeof(float); + const cl_ulong spk2 = src_pk->nb[2] / sizeof(float); + const cl_ulong spk3 = src_pk->nb[3] / sizeof(float); + const cl_ulong spv1 = src_pv->nb[1] / sizeof(float); + const cl_ulong spv2 = src_pv->nb[2] / sizeof(float); + const cl_ulong spv3 = src_pv->nb[3] / sizeof(float); + const cl_ulong spg1 = src_pgb->nb[1] / sizeof(float); + const cl_ulong spg2 = src_pgb->nb[2] / sizeof(float); + const cl_ulong spg3 = src_pgb->nb[3] / sizeof(float); + + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &n_pend)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &keep)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pk->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pk)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spk3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pv->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pv)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spv3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_pgb->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_pgb)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg1)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg2)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &spg3)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_mem), &extra_rep->data_device)); + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_ulong), &off_rep)); + } + CL_CHECK(clSetKernelArg(kernel, idx++, sizeof(cl_uint), &K)); + + // Subgroup size is 64 for Adreno and 32 for Intel + const int sg_size = backend_ctx->gpu_family == GPU_FAMILY::ADRENO ? 64 : backend_ctx->gpu_family == GPU_FAMILY::INTEL ? 32 : -1; + if (sg_size < 0) { + GGML_LOG_ERROR("Unsupported GPU Family: only Adreno and Intel are supported.\n"); + exit(1); + } + + // For the subgroup-shuffle kernel, we can safely prefer 8 lanes/column for S_v>=128 + // For the subgroup-shuffle kernel: + // S_v >= 128 -> prefer 8 lanes/column (good occupancy & register pressure tradeoff) + // else -> min(S_v, subgroup_size) + int lanes_per_column; + if ((int)S_v >= 128) { + lanes_per_column = 8; + } else { + lanes_per_column = std::min((int)S_v, sg_size); + } + + // Max workgroup size for Adreno 750 is 1024 + const int wg_size = sg_size * spw; + + // Ensure lanes_per_column is a power-of-two and divides both S_v and subgroup_size. + // (Required for lane-group shuffle-xor reduction correctness.) + while (lanes_per_column > 1 && + (((lanes_per_column & (lanes_per_column - 1)) != 0) || + (((int)S_v % lanes_per_column) != 0) || + (sg_size % lanes_per_column) != 0)) { + lanes_per_column >>= 1; + } + GGML_ASSERT(lanes_per_column >= 1); + GGML_ASSERT(((lanes_per_column & (lanes_per_column - 1)) == 0)); + GGML_ASSERT(((int)S_v % lanes_per_column) == 0); + GGML_ASSERT((sg_size % lanes_per_column) == 0); + + const int cols_per_wg = spw * (sg_size / lanes_per_column) * cpl; + GGML_ASSERT(cols_per_wg > 0); + GGML_ASSERT(((int)S_v % cols_per_wg) == 0); + + size_t global_work_size[3]; + size_t local_work_size[3]; + + global_work_size[0] = (size_t) H_v * (size_t) wg_size; + global_work_size[1] = (size_t) n_seqs; + global_work_size[2] = (size_t) S_v / (size_t) cols_per_wg; + + local_work_size[0] = (size_t) wg_size; + local_work_size[1] = 1; + local_work_size[2] = 1; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/gelu.cpp b/ggml/src/ggml-opencl/ops/gelu.cpp new file mode 100644 index 000000000000..a7f450176600 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/gelu.cpp @@ -0,0 +1,142 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_gelu(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // gelu + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gelu.cl.h" + }; +#else + const std::string kernel_src = read_file("gelu.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->gelu.kernel_gelu = clCreateKernel(prog, "kernel_gelu", &err), err)); + CL_CHECK((backend_ctx->gelu.kernel_gelu_4 = clCreateKernel(prog, "kernel_gelu_4", &err), err)); + CL_CHECK((backend_ctx->gelu.kernel_gelu_erf = clCreateKernel(prog, "kernel_gelu_erf", &err), err)); + CL_CHECK((backend_ctx->gelu.kernel_gelu_erf_4 = clCreateKernel(prog, "kernel_gelu_erf_4", &err), err)); + CL_CHECK((backend_ctx->gelu.kernel_gelu_quick = clCreateKernel(prog, "kernel_gelu_quick", &err), err)); + CL_CHECK((backend_ctx->gelu.kernel_gelu_quick_4 = clCreateKernel(prog, "kernel_gelu_quick_4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_gelu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel; + + int n = ggml_nelements(dst); + + if (n % 4 == 0) { + kernel = backend_ctx->gelu.kernel_gelu_4; + n /= 4; + } else { + kernel = backend_ctx->gelu.kernel_gelu; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +void ggml_cl_gelu_erf(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel; + + int n = ggml_nelements(dst); + + if (n % 4 == 0) { + kernel = backend_ctx->gelu.kernel_gelu_erf_4; + n /= 4; + } else { + kernel = backend_ctx->gelu.kernel_gelu_erf; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +void ggml_cl_gelu_quick(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel; + + int n = ggml_nelements(dst); + + if (n % 4 == 0) { + kernel = backend_ctx->gelu.kernel_gelu_quick_4; + n /= 4; + } else { + kernel = backend_ctx->gelu.kernel_gelu_quick; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/get_rows.cpp b/ggml/src/ggml-opencl/ops/get_rows.cpp new file mode 100644 index 000000000000..60da7276aa5d --- /dev/null +++ b/ggml/src/ggml-opencl/ops/get_rows.cpp @@ -0,0 +1,107 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_get_rows(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // get_rows + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "get_rows.cl.h" + }; +#else + const std::string kernel_src = read_file("get_rows.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->get_rows.kernel_get_rows_f32 = clCreateKernel(prog, "kernel_get_rows_f32", &err), err)); + CL_CHECK((backend_ctx->get_rows.kernel_get_rows_i32 = clCreateKernel(prog, "kernel_get_rows_i32", &err), err)); + CL_CHECK((backend_ctx->get_rows.kernel_get_rows_f16 = clCreateKernel(prog, "kernel_get_rows_f16", &err), err)); + CL_CHECK((backend_ctx->get_rows.kernel_get_rows_q4_0 = clCreateKernel(prog, "kernel_get_rows_q4_0", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_get_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel; + + switch (src0->type) { + case GGML_TYPE_F32: + kernel = backend_ctx->get_rows.kernel_get_rows_f32; + break; + case GGML_TYPE_I32: + kernel = backend_ctx->get_rows.kernel_get_rows_i32; + break; + case GGML_TYPE_F16: + kernel = backend_ctx->get_rows.kernel_get_rows_f16; + break; + case GGML_TYPE_Q4_0: + kernel = backend_ctx->get_rows.kernel_get_rows_q4_0; + break; + default: + GGML_ASSERT(false && "not implemented"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb3)); + + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + int nth = 1; + while (nth < ne00 && 2*nth <= max_workgroup_size) { + nth *= 2; + } + + int nchunks = 1; + if (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_I32) { + const int chunk_target = nth * 4; + nchunks = (ne00 + chunk_target - 1) / chunk_target; + nchunks = MAX(1, MIN(nchunks, 64)); + } + + size_t global_work_size[] = {(size_t)ne10*nth*nchunks, (size_t)ne11, (size_t)ne12}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/glu.cpp b/ggml/src/ggml-opencl/ops/glu.cpp new file mode 100644 index 000000000000..09d930af129a --- /dev/null +++ b/ggml/src/ggml-opencl/ops/glu.cpp @@ -0,0 +1,159 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_glu(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // glu + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "glu.cl.h" + }; +#else + const std::string kernel_src = read_file("glu.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->glu.kernel_geglu = clCreateKernel(prog, "kernel_geglu", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_reglu = clCreateKernel(prog, "kernel_reglu", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_swiglu = clCreateKernel(prog, "kernel_swiglu", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_swiglu_oai = clCreateKernel(prog, "kernel_swiglu_oai", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_swiglu_clamp = clCreateKernel(prog, "kernel_swiglu_clamp", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_geglu_erf = clCreateKernel(prog, "kernel_geglu_erf", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_geglu_quick = clCreateKernel(prog, "kernel_geglu_quick", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_geglu_f16 = clCreateKernel(prog, "kernel_geglu_f16", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_reglu_f16 = clCreateKernel(prog, "kernel_reglu_f16", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_swiglu_f16 = clCreateKernel(prog, "kernel_swiglu_f16", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_swiglu_oai_f16 = clCreateKernel(prog, "kernel_swiglu_oai_f16", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_swiglu_clamp_f16 = clCreateKernel(prog, "kernel_swiglu_clamp_f16", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_geglu_erf_f16 = clCreateKernel(prog, "kernel_geglu_erf_f16", &err), err)); + CL_CHECK((backend_ctx->glu.kernel_geglu_quick_f16 = clCreateKernel(prog, "kernel_geglu_quick_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_glu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT(ggml_is_contiguous_1(src0)); + + if (src1) { + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(ggml_are_same_shape(src0, src1)); + } + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + cl_kernel kernel; + switch (ggml_get_glu_op(dst)) { + case GGML_GLU_OP_GEGLU: + if (dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->glu.kernel_geglu; + } else { + kernel = backend_ctx->glu.kernel_geglu_f16; + } + break; + case GGML_GLU_OP_REGLU: + if (dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->glu.kernel_reglu; + } else { + kernel = backend_ctx->glu.kernel_reglu_f16; + } + break; + case GGML_GLU_OP_SWIGLU: + if (dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->glu.kernel_swiglu; + } else { + kernel = backend_ctx->glu.kernel_swiglu_f16; + } + break; + case GGML_GLU_OP_SWIGLU_OAI: + if (dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->glu.kernel_swiglu_oai; + } else { + kernel = backend_ctx->glu.kernel_swiglu_oai_f16; + } + break; + case GGML_GLU_OP_SWIGLU_CLAMP: + if (dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->glu.kernel_swiglu_clamp; + } else { + kernel = backend_ctx->glu.kernel_swiglu_clamp_f16; + } + break; + case GGML_GLU_OP_GEGLU_ERF: + if (dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->glu.kernel_geglu_erf; + } else { + kernel = backend_ctx->glu.kernel_geglu_erf_f16; + } + break; + case GGML_GLU_OP_GEGLU_QUICK: + if (dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->glu.kernel_geglu_quick; + } else { + kernel = backend_ctx->glu.kernel_geglu_quick_f16; + } + break; + default: + GGML_ABORT("Unsupported glu op"); + } + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + ggml_tensor_extra_cl * extra1 = src1 ? (ggml_tensor_extra_cl *)src1->extra : nullptr; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_ulong offset1 = extra1 ? extra1->offset + src1->view_offs : offset0; + + const int ne0 = dst->ne[0]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb11 = src1 ? src1->nb[1] : nb01; + + const cl_ulong nb1 = dst->nb[1]; + + const int swp = ggml_get_op_params_i32(dst, 1); + const float alpha = ggml_get_op_params_f32(dst, 2); + const float limit = ggml_get_op_params_f32(dst, 3); + + const int ne00_off = src1 ? 0 : (swp ? ne0 : 0); + const int ne10_off = src1 ? 0 : (swp ? 0 : ne0); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), src1 ? &extra1->data_device : &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00_off)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10_off)); + + if (ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU_OAI || ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU_CLAMP) { + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float), &limit)); + } + if (ggml_get_glu_op(dst) == GGML_GLU_OP_SWIGLU_OAI) { + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha)); + } + + const size_t nrows = ggml_nrows(src0); + size_t nth = backend_ctx->max_workgroup_size < 512 ? backend_ctx->max_workgroup_size : 512; + size_t global_work_size[] = {nrows*nth, 1, 1}; + size_t local_work_size[] = {nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/group_norm.cpp b/ggml/src/ggml-opencl/ops/group_norm.cpp new file mode 100644 index 000000000000..ab2986dda8b4 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/group_norm.cpp @@ -0,0 +1,122 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_group_norm(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // group_norm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "group_norm.cl.h" + }; +#else + const std::string kernel_src = read_file("group_norm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->group_norm.kernel_group_norm = clCreateKernel(prog, "kernel_group_norm", &err), err)); + CL_CHECK((backend_ctx->group_norm.kernel_group_norm_mul_add = clCreateKernel(prog, "kernel_group_norm_mul_add", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_opencl_op_group_norm_fused(ggml_backend_t backend, ggml_tensor * gn_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor) { + GGML_ASSERT(gn_tensor && mul_tensor && add_tensor); + + const ggml_tensor * src0 = gn_tensor->src[0]; + const ggml_tensor * src1 = mul_tensor->src[0] == gn_tensor ? mul_tensor->src[1] : mul_tensor->src[0]; + const ggml_tensor * src2 = add_tensor->src[0] == mul_tensor ? add_tensor->src[1] : add_tensor->src[0]; + const ggml_tensor * dst = add_tensor; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offset2 = extra2->offset + src2->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + int groups; + float eps; + memcpy(&groups, gn_tensor->op_params, sizeof(int)); + memcpy(&eps, (char *)gn_tensor->op_params + sizeof(int), sizeof(float)); + + cl_kernel kernel = backend_ctx->group_norm.kernel_group_norm_mul_add; + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + int ne = ggml_nelements(src0); + int group_size = ne / groups; + + size_t lws[] = { (size_t)MIN(max_workgroup_size, group_size) }; + size_t gws[] = { (size_t)groups * lws[0] }; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &group_size)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(float), &eps)); + + backend_ctx->enqueue_ndrange_kernel(kernel, 1, gws, lws, dst); +} + +void ggml_cl_group_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int32_t n_groups = ((const int32_t *) dst->op_params)[0]; + int32_t group_size = src0->ne[0] * src0->ne[1] * ((src0->ne[2] + n_groups - 1) / n_groups); + float eps = ((const float *) dst->op_params)[1]; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne = ne00*ne01*ne02; + + cl_kernel kernel = backend_ctx->group_norm.kernel_group_norm; + + size_t sgs = 64; + if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + } else if (backend_ctx->gpu_family == INTEL) { + sgs = 32; + } else { + GGML_ASSERT(false && "Unsupported GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &group_size)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(float), &eps)); + + size_t global_work_size[] = {(size_t)n_groups*sgs, (size_t)src0->ne[3], 1}; + size_t local_work_size[] = {(size_t)sgs, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/im2col.cpp b/ggml/src/ggml-opencl/ops/im2col.cpp new file mode 100644 index 000000000000..bb650f8327ac --- /dev/null +++ b/ggml/src/ggml-opencl/ops/im2col.cpp @@ -0,0 +1,123 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_im2col(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // im2col_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "im2col_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("im2col_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->im2col.kernel_im2col_f32 = clCreateKernel(prog, "kernel_im2col_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // im2col_f16 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "im2col_f16.cl.h" + }; +#else + const std::string kernel_src = read_file("im2col_f16.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->im2col.kernel_im2col_f16 = clCreateKernel(prog, "kernel_im2col_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_im2col(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + // src0 - filter, src1 - input + GGML_ASSERT(src1->type == GGML_TYPE_F32); + GGML_ASSERT(dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F32); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int32_t s0 = ((const int32_t*)(dst->op_params))[0]; + const int32_t s1 = ((const int32_t*)(dst->op_params))[1]; + const int32_t p0 = ((const int32_t*)(dst->op_params))[2]; + const int32_t p1 = ((const int32_t*)(dst->op_params))[3]; + const int32_t d0 = ((const int32_t*)(dst->op_params))[4]; + const int32_t d1 = ((const int32_t*)(dst->op_params))[5]; + + const bool is_2D = ((const int32_t*)(dst->op_params))[6] == 1; + + const cl_long IC = src1->ne[is_2D ? 2 : 1]; + const cl_long IH = is_2D ? src1->ne[1] : 1; + const cl_long IW = src1->ne[0]; + + const cl_long KH = is_2D ? src0->ne[1] : 1; + const cl_long KW = src0->ne[0]; + + const cl_long OH = is_2D ? dst->ne[2] : 1; + const cl_long OW = dst->ne[1]; + + // nb is byte offset, src is type float32 + const cl_ulong delta_offset = src1->nb[is_2D ? 2 : 1]/4; + const cl_long batch = src1->ne[is_2D ? 3 : 2]; + const cl_ulong batch_offset = src1->nb[is_2D ? 3 : 2]/4; + + const cl_long pelements = OW*KW*KH; + const cl_long CHW = IC*KH*KW; + + cl_kernel kernel; + + if(dst->type == GGML_TYPE_F16) { + kernel = backend_ctx->im2col.kernel_im2col_f16; + } else { + kernel = backend_ctx->im2col.kernel_im2col_f32; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &batch_offset)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &delta_offset)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_long), &IW)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_long), &IH)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_long), &IC)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_long), &OW)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &OH)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_long), &KW)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_long), &KH)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_long), &pelements)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_long), &CHW)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &s0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &s1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &p0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &p1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &d0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &d1)); + + const int num_blocks = (pelements + 256 - 1) / 256; + size_t global_work_size[] = {(size_t)num_blocks*256, (size_t)OH, (size_t)batch*IC}; + size_t local_work_size[] = {256, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/im2col_3d.cpp b/ggml/src/ggml-opencl/ops/im2col_3d.cpp new file mode 100644 index 000000000000..ec9da1559546 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/im2col_3d.cpp @@ -0,0 +1,134 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_im2col_3d(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + + // im2col_3d_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "im2col_3d_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("im2col_3d_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->im2col_3d.kernel_im2col_3d_f32 = clCreateKernel(prog, "kernel_im2col_3d_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // im2col_3d_f16 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "im2col_3d_f16.cl.h" + }; +#else + const std::string kernel_src = read_file("im2col_3d_f16.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->im2col_3d.kernel_im2col_3d_f16 = clCreateKernel(prog, "kernel_im2col_3d_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_im2col_3d(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT(src1->type == GGML_TYPE_F32); + GGML_ASSERT(dst->type == GGML_TYPE_F16 || dst->type == GGML_TYPE_F32); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int32_t s0 = ((const int32_t *)(dst->op_params))[0]; + const int32_t s1 = ((const int32_t *)(dst->op_params))[1]; + const int32_t s2 = ((const int32_t *)(dst->op_params))[2]; + const int32_t p0 = ((const int32_t *)(dst->op_params))[3]; + const int32_t p1 = ((const int32_t *)(dst->op_params))[4]; + const int32_t p2 = ((const int32_t *)(dst->op_params))[5]; + const int32_t d0 = ((const int32_t *)(dst->op_params))[6]; + const int32_t d1 = ((const int32_t *)(dst->op_params))[7]; + const int32_t d2 = ((const int32_t *)(dst->op_params))[8]; + const cl_long IC = ((const int32_t *)(dst->op_params))[9]; + + const cl_long N = src1->ne[3] / IC; + const cl_long ID = src1->ne[2]; + const cl_long IH = src1->ne[1]; + const cl_long IW = src1->ne[0]; + + const cl_long KD = src0->ne[2]; + const cl_long KH = src0->ne[1]; + const cl_long KW = src0->ne[0]; + + const cl_long OD = dst->ne[3] / N; + const cl_long OH = dst->ne[2]; + const cl_long OW = dst->ne[1]; + + const size_t es = ggml_element_size(src1); + const cl_long stride_x = src1->nb[0] / es; + const cl_long stride_y = src1->nb[1] / es; + const cl_long stride_z = src1->nb[2] / es; + const cl_long stride_q = src1->nb[3] / es; + + const cl_long IC_KD_KH_KW = IC * KD * KH * KW; + + cl_kernel kernel; + + if (dst->type == GGML_TYPE_F16) { + kernel = backend_ctx->im2col_3d.kernel_im2col_3d_f16; + } else { + kernel = backend_ctx->im2col_3d.kernel_im2col_3d_f32; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_long), &IC)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_long), &ID)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_long), &IH)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_long), &IW)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_long), &KD)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_long), &KH)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &KW)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_long), &OD)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_long), &OH)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_long), &OW)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_long), &N)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_long), &stride_x)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_long), &stride_y)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_long), &stride_z)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_long), &stride_q)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &s0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &s1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &s2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &p0)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &p1)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &p2)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &d0)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &d1)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(int), &d2)); + + const size_t local_col = 64; + const size_t num_blocks = (IC_KD_KH_KW + local_col - 1) / local_col; + size_t global_work_size[] = { num_blocks * local_col, (size_t) OW, (size_t) (N * OD * OH) }; + size_t local_work_size[] = { local_col, 1, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/l2_norm.cpp b/ggml/src/ggml-opencl/ops/l2_norm.cpp new file mode 100644 index 000000000000..2eb9307563bf --- /dev/null +++ b/ggml/src/ggml-opencl/ops/l2_norm.cpp @@ -0,0 +1,81 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_l2_norm(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // l2_norm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "l2_norm.cl.h" + }; +#else + const std::string kernel_src = read_file("l2_norm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->l2_norm.kernel_l2_norm_f32 = clCreateKernel(prog, "kernel_l2_norm_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_l2_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + float eps; + memcpy(&eps, dst->op_params, sizeof(float)); + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + + size_t sgs; + if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + } else if (backend_ctx->gpu_family == INTEL) { + sgs = 32; + } else { + GGML_ASSERT(false && "Unsupported GPU"); + } + + cl_kernel kernel = backend_ctx->l2_norm.kernel_l2_norm_f32; + + int nth = sgs; + while (nth < ne00 && nth < (int)backend_ctx->get_kernel_workgroup_size(kernel)) { + nth *= 2; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(float), &eps)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float)*nth/sgs, NULL)); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/lightning_indexer.cpp b/ggml/src/ggml-opencl/ops/lightning_indexer.cpp new file mode 100644 index 000000000000..b103e4df5ca8 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/lightning_indexer.cpp @@ -0,0 +1,87 @@ +#include "../cl-common.h" + +void ggml_cl_load_kernels_lightning_indexer(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "lightning_indexer.cl.h" + }; +#else + const std::string kernel_src = read_file("lightning_indexer.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->lightning_indexer.kernel_lightning_indexer = clCreateKernel(prog, "kernel_lightning_indexer", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); +} + +void ggml_cl_lightning_indexer(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + cl_kernel kernel = backend_ctx->lightning_indexer.kernel_lightning_indexer; + const ggml_tensor * src2 = dst->src[2]; + const ggml_tensor * src3 = dst->src[3]; + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *) src2->extra; + ggml_tensor_extra_cl * extra3 = (ggml_tensor_extra_cl *) src3->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offset1 = extra1->offset + src1->view_offs; + const cl_ulong offset2 = extra2->offset + src2->view_offs; + const cl_ulong offset3 = extra3->offset + src3->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int head_size = src0->ne[0]; + const int n_heads = src0->ne[1]; + const int n_tokens = src0->ne[2]; + const int n_keys = src1->ne[2]; + const int n_masks = src3->ne[3]; + // Keep the local-memory reduction for small grids or few heads. + const int use_shuffle = head_size == 128 && backend_ctx->has_khr_subgroup_shuffle && n_heads >= 32 && ggml_nelements(dst) >= 1024; + // BF16 tensors are stored as F16 on the device. + const int type_k = src1->type == GGML_TYPE_F32 ? 0 : 1; + + const cl_ulong nbq1 = src0->nb[1]; + const cl_ulong nbq2 = src0->nb[2]; + const cl_ulong nbq3 = src0->nb[3]; + const cl_ulong nbk2 = src1->nb[2]; + const cl_ulong nbk3 = src1->nb[3]; + const cl_ulong nbw1 = src2->nb[1]; + const cl_ulong nbw3 = src2->nb[3]; + const cl_ulong nbm1 = src3->nb[1]; + const cl_ulong nbm3 = src3->nb[3]; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra3->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset3)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &head_size)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &n_heads)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &n_tokens)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &n_keys)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &n_masks)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &type_k)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nbq1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nbq2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nbq3)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nbk2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nbk3)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nbw1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nbw3)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &nbm1)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &nbm3)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &use_shuffle)); + + const int keys_per_group = use_shuffle ? 16 : 4; + size_t global_work_size[] = { (size_t) ((src1->ne[2] + keys_per_group - 1)/keys_per_group)*64, (size_t) src0->ne[2], (size_t) src0->ne[3] }; + size_t local_work_size[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/mean.cpp b/ggml/src/ggml-opencl/ops/mean.cpp new file mode 100644 index 000000000000..d7b4dc96a190 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/mean.cpp @@ -0,0 +1,85 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_mean(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // mean + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mean.cl.h" + }; +#else + const std::string kernel_src = read_file("mean.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mean.kernel_mean_f32 = clCreateKernel(prog, "kernel_mean_f32", &err), err)); + CL_CHECK((backend_ctx->mean.kernel_mean_f32_4 = clCreateKernel(prog, "kernel_mean_f32_4", &err), err)); + + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_mean(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_UNUSED(src1); + + GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type)); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel; + + const bool is_c4 = ne00 % 4 == 0; + if (is_c4) { + kernel = backend_ctx->mean.kernel_mean_f32_4; + } else { + kernel = backend_ctx->mean.kernel_mean_f32; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb3)); + + size_t global_work_size[] = {64 * (size_t)ne01, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/mul.cpp b/ggml/src/ggml-opencl/ops/mul.cpp new file mode 100644 index 000000000000..6c093ce2edc5 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/mul.cpp @@ -0,0 +1,163 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_mul(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // mul + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul.cl.h" + }; +#else + const std::string kernel_src = read_file("mul.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul.kernel_mul = clCreateKernel(prog, "kernel_mul", &err), err)); + CL_CHECK((backend_ctx->mul.kernel_mul_row = clCreateKernel(prog, "kernel_mul_row", &err), err)); + CL_CHECK((backend_ctx->mul.kernel_mul_f16 = clCreateKernel(prog, "kernel_mul_f16", &err), err)); + CL_CHECK((backend_ctx->mul.kernel_mul_row_f16 = clCreateKernel(prog, "kernel_mul_row_f16", &err), err)); + CL_CHECK((backend_ctx->mul.kernel_mul_mat_scale = clCreateKernel(prog, "kernel_mul_mat_scale", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_mul(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT(src0->type == src1->type); + GGML_ASSERT(src0->type == dst->type); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne10 = src1->ne[0]; + const int ne11 = src1->ne[1]; + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; UNUSED(ne13); + + const cl_ulong nb10 = src1->nb[0]; + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; UNUSED(nb13); + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + const int ne2 = dst->ne[2]; + const int ne3 = dst->ne[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + bool bcast_row = false; + cl_kernel kernel; + + if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) { + GGML_ASSERT(ggml_is_contiguous(src0)); + + // src1 is a row + GGML_ASSERT(ne11 == 1); + + bcast_row = true; + int ne = ne10 / 4; + + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->mul.kernel_mul_row; + } else { + kernel = backend_ctx->mul.kernel_mul_row_f16; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->mul.kernel_mul; + } else { + kernel = backend_ctx->mul.kernel_mul_f16; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne3)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb3)); + } + + if (bcast_row) { + int n = ggml_nelements(dst)/4; + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); + } else { + unsigned int nth = MIN(64, ne0); + size_t global_work_size[] = {ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/mul_mat.cpp b/ggml/src/ggml-opencl/ops/mul_mat.cpp new file mode 100644 index 000000000000..412d4a8f8033 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/mul_mat.cpp @@ -0,0 +1,6723 @@ +#include "../cl-common.h" +#include "../ops.h" + +static std::string ggml_cl_q2_k_mm_options(const ggml_backend_opencl_context * backend_ctx) { + const bool x2 = backend_ctx->gpu_family == ADRENO && + (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + int bk = x2 ? 16 : 32; + bool half = x2; + if (const char * env = getenv("GGML_OPENCL_LM_BK")) { + const int value = atoi(env); + if (value == 16 || value == 32) { + bk = value; + } + } + if (const char * env = getenv("GGML_OPENCL_LM_HALF")) { + half = atoi(env) != 0; + } + return " -DBK=" + std::to_string(bk) + " -DLM_HALF=" + std::to_string(half ? 1 : 0); +} + +static std::string ggml_cl_q3_k_mm_options(const ggml_backend_opencl_context * backend_ctx) { + const bool x2 = backend_ctx->gpu_family == ADRENO && + (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + int bk = x2 ? 16 : 32; + bool half = x2; + if (const char * env = getenv("GGML_OPENCL_LM_BK")) { + const int value = atoi(env); + if (value == 16 || value == 32) { + bk = value; + } + } + if (const char * env = getenv("GGML_OPENCL_LM_HALF")) { + half = atoi(env) != 0; + } + return " -DBK=" + std::to_string(bk) + " -DLM_HALF=" + std::to_string(half ? 1 : 0); +} + +void ggml_cl_load_kernels_mul_mat(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + + // mul_mv_q4_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_0_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32 = clCreateKernel(prog, "kernel_mul_mat_q4_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_0_f32_v + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_0_f32_v.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_0_f32_v.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_v = clCreateKernel(prog, "kernel_mul_mat_q4_0_f32_v", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_0_f32_8x_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_0_f32_8x_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_0_f32_8x_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_8x_flat = clCreateKernel(prog, "kernel_mul_mat_q4_0_f32_8x_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_0_f32_1d_8x_flat + // This kernel does not compiler on Adreno cl compiler 38.01. Skip it for + // those compiler versions since it is anyway not used for Adreno. + if (backend_ctx->gpu_family != ADRENO || + backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 38, 11, 0) || + backend_ctx->adreno_cl_compiler_version.type == E17 || + backend_ctx->adreno_cl_compiler_version.type == DX) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_0_f32_1d_8x_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_0_f32_1d_8x_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_1d_8x_flat = clCreateKernel(prog, "kernel_mul_mat_q4_0_f32_1d_8x_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_0_f32_1d_16x_flat + // This kernel does not compiler on Adreno cl compiler 38.01. Skip it for + // those compiler versions since it is anyway not used for Adreno. + if (backend_ctx->gpu_family != ADRENO || + backend_ctx->adreno_cl_compiler_version.newer_than_or_same(E031, 38, 11, 0) || + backend_ctx->adreno_cl_compiler_version.type == DX) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_0_f32_1d_16x_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_0_f32_1d_16x_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_1d_16x_flat = clCreateKernel(prog, "kernel_mul_mat_q4_0_f32_1d_16x_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_1_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_1_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_1_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q4_1_f32 = clCreateKernel(prog, "kernel_mul_mv_q4_1_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_1_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_1_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_1_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q4_1_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q4_1_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_k_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q4_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q4_K_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q4_k_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q4_k_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q4_k_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q4_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q4_K_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q5_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q5_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q5_0_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q5_0_f32 = clCreateKernel(prog, "kernel_mul_mv_q5_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q5_0_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q5_0_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q5_0_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q5_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q5_0_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q5_1_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q5_1_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q5_1_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q5_1_f32 = clCreateKernel(prog, "kernel_mul_mv_q5_1_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q5_1_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q5_1_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q5_1_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q5_1_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q5_1_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q2_k_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q2_k_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q2_k_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q2_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q2_K_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q2_k_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q2_k_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q2_k_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + ggml_cl_q2_k_mm_options(backend_ctx)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q2_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q2_k_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q2_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q2_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q2_k_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q2_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q2_K_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q3_k_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q3_k_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q3_k_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q3_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q3_K_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q3_k_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q3_k_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q3_k_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + ggml_cl_q3_k_mm_options(backend_ctx)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q3_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q3_k_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q3_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q3_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q3_k_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q3_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q3_K_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q5_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q5_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q5_k_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q5_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q5_K_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q5_k_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q5_k_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q5_k_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q5_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q5_K_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + + // mul_mv_q6_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q6_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q6_k_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q6_K_f32 = clCreateKernel(prog, "kernel_mul_mv_q6_K_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q6_k_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q6_k_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q6_k_f32_flat.cl"); +#endif + const std::string q6k_opts = backend_ctx->q6_k_flat_old_compiler + ? compile_opts + " -DADRENO_OLD_COMPILER=1" + : compile_opts; + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q6k_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q6_K_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q6_K_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q8_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q8_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q8_0_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q8_0_f32 = clCreateKernel(prog, "kernel_mul_mv_q8_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q8_0_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q8_0_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q8_0_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q8_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q8_0_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q1_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q1_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q1_0_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q1_0_f32 = clCreateKernel(prog, "kernel_mul_mv_q1_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q1_0_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q1_0_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q1_0_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q1_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q1_0_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq4_nl_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq4_nl_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq4_nl_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq4_nl_f32 = clCreateKernel(prog, "kernel_mul_mv_iq4_nl_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq4_nl_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq4_nl_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq4_nl_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq4_nl_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq4_nl_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_mxfp4_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_mxfp4_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_mxfp4_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_mxfp4_f32 = clCreateKernel(prog, "kernel_mul_mv_mxfp4_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_mxfp4_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_mxfp4_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_mxfp4_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_mxfp4_f32_flat = clCreateKernel(prog, "kernel_mul_mv_mxfp4_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_f16_f16 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_f16_f16.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_f16_f16.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f16 = clCreateKernel(prog, "kernel_mul_mat_f16_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_f16_f32_1row + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_f16_f32_1row.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_f16_f32_1row.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_1row = clCreateKernel(prog, "kernel_mul_mat_f16_f32_1row", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_f16_f32_mrow (multi-row decode GEMV) + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_f16_f32_mrow.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_f16_f32_mrow.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow = clCreateKernel(prog, "kernel_mul_mat_f16_f32_mrow", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_r2 = clCreateKernel(prog, "kernel_mul_mat_f16_f32_mrow_r2", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_r4 = clCreateKernel(prog, "kernel_mul_mat_f16_f32_mrow_r4", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_h8 = clCreateKernel(prog, "kernel_mul_mat_f16_f32_mrow_h8", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_h8r2 = clCreateKernel(prog, "kernel_mul_mat_f16_f32_mrow_h8r2", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_f16_f32_l4 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_f16_f32_l4.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_f16_f32_l4.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4 = clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr = clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_dr", &err), err)); + if (backend_ctx->gpu_family == ADRENO) { + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr_ls = clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_dr_ls", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr_lq = clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_dr_lq", &err), err)); + } + + cl_int err_x8 = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8 = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_x8", &err_x8); + if (err_x8 != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8 = nullptr; } + + cl_int err_x8p = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_pair = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_x8_pair", &err_x8p); + if (err_x8p != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_pair = nullptr; } + + cl_int err_x8g = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4 = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_x8_gqa4", &err_x8g); + if (err_x8g != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4 = nullptr; } + + cl_int err_y8 = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8 = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_y8", &err_y8); + if (err_y8 != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8 = nullptr; } + + cl_int err_y8g = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_y8_gqa", &err_y8g); + if (err_y8g != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa = nullptr; } + + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_f16_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_f16_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_f16_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32 = clCreateKernel(prog, "kernel_mul_mat_f16_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_f32_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_f32_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_f32_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f32_f32 = clCreateKernel(prog, "kernel_mul_mat_f32_f32", &err), err)); + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X) { + cl_kernel kernel = clCreateKernel(prog, "kernel_mul_mv_f32_f32_r2", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (max_workgroup >= 64) { + backend_ctx->mul_mat.kernel_mul_mv_f32_f32_r2 = kernel; + } else { + CL_CHECK(clReleaseKernel(kernel)); + } + } + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mat_f16_f32_tiled + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mat_f16_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mat_f16_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mat_f16_f32_tiled = clCreateKernel(prog, "mul_mat_f16_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_f32_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_f32_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_f32_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_f32_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_f32_f32_l4_lm", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_f32_f32_mc = clCreateKernel(prog, "kernel_gemv_f32_f32_mc", &err), err)); + cl_kernel mcr = clCreateKernel(prog, "kernel_gemv_f32_f32_mcr", &err); + if (err == CL_SUCCESS) { + if (backend_ctx->get_kernel_workgroup_size(mcr) >= 64) { + backend_ctx->mul_mat.kernel_gemv_f32_f32_mcr = mcr; + } else { + CL_CHECK(clReleaseKernel(mcr)); + } + } + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_f16_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_f16_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_f16_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_f16_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_f16_f32_l4_lm", &err), err)); + + const std::string narrow_opts = compile_opts + " -DBN=8 -DTN=1 -DKERNEL_NAME_LM=kernel_mul_mm_f16_f32_l4_lm_n8"; + cl_program narrow_prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), narrow_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_f16_f32_l4_lm_n8 = clCreateKernel(narrow_prog, "kernel_mul_mm_f16_f32_l4_lm_n8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + CL_CHECK(clReleaseProgram(narrow_prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q4_0_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q4_0_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q4_0_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q4_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q4_0_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q4_1_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q4_1_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q4_1_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q4_1_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q4_1_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q5_0_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q5_0_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q5_0_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q5_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q5_0_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q5_1_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q5_1_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q5_1_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q5_1_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q5_1_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q8_0_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q8_0_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q8_0_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q8_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q8_0_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q1_0_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q1_0_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q1_0_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q1_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q1_0_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq4_nl_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq4_nl_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq4_nl_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq4_nl_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq4_nl_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q4_k_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q4_k_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q4_k_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q4_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q4_k_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q6_k_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q6_k_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q6_k_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q6_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q6_k_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q5_k_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q5_k_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q5_k_f32_l4_lm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q5_k_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q5_k_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq2_s_grid_src { + #include "iq2_s_grid.cl.h" + }; +#else + const std::string iq2_s_grid_src = read_file("iq2_s_grid.cl"); +#endif + + // mul_mv_iq2_s_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq2_s_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq2_s_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq2_s_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq2_s_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq2_s_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq2_s_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq2_s_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq2_s_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq2_s_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq2_xs_grid_src { + #include "iq2_xs_grid.cl.h" + }; +#else + const std::string iq2_xs_grid_src = read_file("iq2_xs_grid.cl"); +#endif + + // mul_mv_iq2_xs_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq2_xs_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq2_xs_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq2_xs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq2_xs_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq2_xs_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq2_xs_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq2_xs_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq2_xs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq2_xs_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq2_xxs_grid_src { + #include "iq2_xxs_grid.cl.h" + }; +#else + const std::string iq2_xxs_grid_src = read_file("iq2_xxs_grid.cl"); +#endif + + // mul_mv_iq2_xxs_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq2_xxs_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq2_xxs_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq2_xxs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq2_xxs_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq2_xxs_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq2_xxs_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq2_xxs_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq2_xxs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq2_xxs_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq2_xxs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq2_xxs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq2_xxs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq2_xxs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq2_xxs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq2_xs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq2_xs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq2_xs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq2_xs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq2_xs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq2_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq2_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq2_s_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq2_s_f32 = clCreateKernel(prog, "kernel_mul_mv_iq2_s_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // fwht + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "fwht.cl.h" + }; +#else + const std::string kernel_src = read_file("fwht.cl"); +#endif + for (int i = 0; i < 2; ++i) { + const std::string opts = compile_opts + (i == 0 ? " -DSRC_TYPE=float" : " -DSRC_TYPE=half"); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + CL_CHECK((backend_ctx->mul_mat.kernel_fwht[i] = clCreateKernel(prog, "kernel_fwht", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + size_t nth = 128; + const size_t max_workgroup = backend_ctx->get_kernel_workgroup_size(backend_ctx->mul_mat.kernel_fwht[i]); + while (nth > max_workgroup) { + nth /= 2; + } + backend_ctx->mul_mat.fwht_workgroup_size[i] = nth; + } + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq1_s_grid_src { + #include "iq1_s_grid.cl.h" + }; +#else + const std::string iq1_s_grid_src = read_file("iq1_s_grid.cl"); +#endif + + // mul_mv_iq1_s_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq1_s_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq1_s_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq1_s_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq1_s_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq1_s_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq1_s_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq1_s_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq1_s_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq1_s_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq1_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq1_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq1_s_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq1_s_f32 = clCreateKernel(prog, "kernel_mul_mv_iq1_s_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq1_m_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq1_m_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq1_m_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq1_m_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq1_m_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq1_m_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq1_m_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq1_m_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq1_m_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq1_m_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq1_m_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq1_m_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq1_m_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq1_m_f32 = clCreateKernel(prog, "kernel_mul_mv_iq1_m_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq3_s_grid_src { + #include "iq3_s_grid.cl.h" + }; +#else + const std::string iq3_s_grid_src = read_file("iq3_s_grid.cl"); +#endif + + // mul_mv_iq3_s_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq3_s_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq3_s_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq3_s_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq3_s_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq3_s_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq3_s_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq3_s_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq3_s_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq3_s_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq3_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq3_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq3_s_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq3_s_f32 = clCreateKernel(prog, "kernel_mul_mv_iq3_s_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq3_xxs_grid_src { + #include "iq3_xxs_grid.cl.h" + }; +#else + const std::string iq3_xxs_grid_src = read_file("iq3_xxs_grid.cl"); +#endif + + // mul_mv_iq3_xxs_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq3_xxs_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq3_xxs_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq3_xxs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq3_xxs_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq3_xxs_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq3_xxs_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq3_xxs_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq3_xxs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq3_xxs_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq3_xxs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq3_xxs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq3_xxs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq3_xxs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq3_xxs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq4_xs_grid_src { + #include "iq4_xs_grid.cl.h" + }; +#else + const std::string iq4_xs_grid_src = read_file("iq4_xs_grid.cl"); +#endif + + // mul_mv_iq4_xs_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq4_xs_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq4_xs_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq4_xs_f32_flat = clCreateKernel(prog, "kernel_mul_mv_iq4_xs_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_iq4_xs_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_iq4_xs_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_iq4_xs_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_iq4_xs_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_iq4_xs_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_iq4_xs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_iq4_xs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_iq4_xs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_iq4_xs_f32 = clCreateKernel(prog, "kernel_mul_mv_iq4_xs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q2_0_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q2_0_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q2_0_f32_flat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q2_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_q2_0_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q2_0_f32_l4_lm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_q2_0_f32_l4_lm.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_q2_0_f32_l4_lm.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_q2_0_f32_l4_lm = clCreateKernel(prog, "kernel_mul_mm_q2_0_f32_l4_lm", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_q2_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_q2_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_q2_0_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mv_q2_0_f32 = clCreateKernel(prog, "kernel_mul_mv_q2_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +// Copy a noncontiguous tensor to contiguous tensor. ne[] remains the same but +// nb[] is recalculated such that tensor is contiguous. +static void ggml_cl_copy_to_contiguous(ggml_backend_t backend, const ggml_tensor * src, cl_mem dst, + cl_ulong &nb0, cl_ulong &nb1, cl_ulong &nb2, cl_ulong &nb3) { + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + const int tensor_type_size = ggml_type_size(src->type); + + const int ne00 = src->ne[0]; + const int ne01 = src->ne[1]; + const int ne02 = src->ne[2]; + const int ne03 = src->ne[3]; + + const cl_ulong nb00 = src->nb[0]; + const cl_ulong nb01 = src->nb[1]; + const cl_ulong nb02 = src->nb[2]; + const cl_ulong nb03 = src->nb[3]; + + const int ne0 = src->ne[0]; + const int ne1 = src->ne[1]; + const int ne2 = src->ne[2]; + const int ne3 = src->ne[3]; + + nb0 = tensor_type_size; + nb1 = tensor_type_size*ne00; + nb2 = tensor_type_size*ne00*ne01; + nb3 = tensor_type_size*ne00*ne01*ne02; + + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *)src->extra; + + cl_ulong offset0 = extra->offset + src->view_offs; + cl_ulong offsetd = 0; + + cl_kernel kernel; + + switch (src->type) { + case GGML_TYPE_F32: + kernel = backend_ctx->cpy.kernel_cpy_f32_f32; + break; + case GGML_TYPE_F16: + case GGML_TYPE_BF16: // stored as f16 on device + kernel = backend_ctx->cpy.kernel_cpy_f16_f16; + break; + default: + GGML_ASSERT(false && "not implemented"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne3)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb3)); + + const int nth = MIN(64, ne00); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, src); +} + +// Dequant a possibly-strided q4_0/q8_0 tensor to tight-packed f16. Returns a +// temp cl_mem the caller must release. SoA inputs are reconstructed into a +// temp AoS buffer reported via *extra_reconstruct (also caller-released). +// this is for quantized K cache without FA. +static cl_mem ggml_cl_mul_mat_dequant_quant_to_f16( + ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * tensor, + cl_mem * extra_reconstruct /* out, may be NULL */ +) { + GGML_ASSERT(tensor->type == GGML_TYPE_Q4_0 || tensor->type == GGML_TYPE_Q8_0); + + if (extra_reconstruct) { + *extra_reconstruct = NULL; + } + + cl_mem src_buf; + cl_ulong src_offset; + cl_ulong src_nb1; + cl_ulong src_nb2; + cl_ulong src_nb3; + + uintptr_t pool_key_buf = 0; + cl_ulong pool_key_off = (cl_ulong) tensor->view_offs; + + const bool is_soa = tensor->type == GGML_TYPE_Q4_0 + ? ggml_cl_is_q4_0_soa(tensor) + : ggml_cl_is_q8_0_soa(tensor); + + cl_mem aos = nullptr; + if (is_soa) { + // Reconstruct full parent AoS; view's own nb[] then index it correctly. + const ggml_tensor * parent = tensor->view_src ? tensor->view_src : tensor; + const ggml_tensor * soa_src = parent; + const size_t block_bytes = (size_t) ggml_type_size(tensor->type); + const size_t blck_size = (size_t) ggml_blck_size(tensor->type); + const size_t parent_row_blocks = (size_t) parent->ne[0] / blck_size; + const size_t parent_row_bytes = parent_row_blocks * block_bytes; + const size_t parent_nbytes = (size_t) ggml_nelements(parent) / blck_size * block_bytes; + + cl_int err; + aos = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, parent_nbytes, NULL, &err); + CL_CHECK(err); + + // large q4_0/q8_0 WEIGHTS are stored transposed and small weights + // (and the AoS KV-cache, handled in the else branch above) are not. + // choose a proper restore kernel based on this. + bool restored = false; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + const int p_ne00 = (int) parent->ne[0]; + const int p_ne01 = (int) parent->ne[1]; + if (tensor->type == GGML_TYPE_Q8_0 && enable_adreno_trans_weight(backend_ctx, parent)) { + auto * extra = (ggml_tensor_extra_cl_q8_0 *) soa_src->extra; + pool_key_buf = (uintptr_t) extra->q; + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q8_0_trans; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &p_ne00)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &p_ne01)); + size_t gws[] = { (size_t)(((p_ne01 + 63) / 64) * 64), 1, 1 }; + size_t lws[] = { 64, 1, 1 }; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, gws, lws, 0, NULL, NULL)); + restored = true; + } else if (tensor->type == GGML_TYPE_Q4_0 && + use_adreno_kernels(backend_ctx, parent) && + !use_adreno_moe_kernels(backend_ctx, parent)) { + auto * extra = (ggml_tensor_extra_cl_q4_0 *) soa_src->extra; + pool_key_buf = (uintptr_t) extra->q; + const size_t size_q = (size_t) ggml_nelements(parent) / blck_size * (blck_size / 2); + const size_t size_d = (size_t) ggml_nelements(parent) / blck_size * sizeof(ggml_fp16_t); + + cl_int err; + cl_mem buf_tq = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size_q, NULL, &err); + CL_CHECK(err); + + cl_mem buf_td = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, size_d, NULL, &err); + CL_CHECK(err); + transpose_2d_as_16b(backend_ctx, extra->q, buf_tq, size_q, p_ne01, p_ne00 / 4); + transpose_2d_as_16b(backend_ctx, extra->d, buf_td, size_d, p_ne01, p_ne00 / 32); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_0_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_tq)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_td)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); + + const size_t n_blk = parent_nbytes / block_bytes; + size_t gws[] = { n_blk, 1, 1 }; + size_t lws[] = { 1, 1, 1 }; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, gws, lws, 0, NULL, NULL)); + + CL_CHECK(clReleaseMemObject(buf_tq)); + CL_CHECK(clReleaseMemObject(buf_td)); + restored = true; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + if (!restored) { + cl_kernel kernel; + if (tensor->type == GGML_TYPE_Q8_0) { + auto * extra = (ggml_tensor_extra_cl_q8_0 *) soa_src->extra; + kernel = backend_ctx->repack.kernel_restore_block_q8_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); + pool_key_buf = (uintptr_t) extra->q; + } else { + auto * extra = (ggml_tensor_extra_cl_q4_0 *) soa_src->extra; + kernel = backend_ctx->repack.kernel_restore_block_q4_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &aos)); + pool_key_buf = (uintptr_t) extra->q; + } + + const size_t n_blocks = parent_nbytes / block_bytes; + size_t gws_rec[] = { n_blocks, 1, 1 }; + size_t lws_rec[] = { 1, 1, 1 }; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, kernel, 3, NULL, gws_rec, lws_rec, 0, NULL, NULL)); + } + + (void) parent_row_blocks; + (void) parent_row_bytes; + src_buf = aos; + src_offset = tensor->view_offs; + src_nb1 = tensor->nb[1]; + src_nb2 = tensor->nb[2]; + src_nb3 = tensor->nb[3]; + + if (extra_reconstruct) { + *extra_reconstruct = aos; + } + } else { + auto * extra = (ggml_tensor_extra_cl *) tensor->extra; + GGML_ASSERT(extra && extra->data_device); + src_buf = extra->data_device; + src_offset = extra->offset + tensor->view_offs; + src_nb1 = tensor->nb[1]; + src_nb2 = tensor->nb[2]; + src_nb3 = tensor->nb[3]; + pool_key_buf = (uintptr_t) extra->data_device; + pool_key_off = (cl_ulong) src_offset; + } + + const cl_int nblk0 = (cl_int) (tensor->ne[0] / ggml_blck_size(tensor->type)); + const cl_int ne1_ = (cl_int) tensor->ne[1]; + const cl_int ne2_ = (cl_int) tensor->ne[2]; + const cl_int ne3_ = (cl_int) tensor->ne[3]; + + const size_t out_bytes = (size_t) ggml_nelements(tensor) * sizeof(ggml_fp16_t); + + // reuse a pooled f16 buffer for this KV-cache view across decode steps instead of + // allocating new one per attention op + cl_mem out = nullptr; + { + auto & pool = backend_ctx->dequant_f16_pool; + ggml_backend_opencl_context::ImagePoolKey key{pool_key_buf, (uint64_t) pool_key_off}; + auto it = pool.find(key); + if (it != pool.end() && it->second.k_bytes >= out_bytes && it->second.image) { + out = it->second.image; + } else { + if (it != pool.end()) { + if (it->second.image) { CL_CHECK(clReleaseMemObject(it->second.image)); } + pool.erase(it); + } + cl_int err = CL_SUCCESS; + out = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, out_bytes, NULL, &err); + CL_CHECK(err); + ggml_backend_opencl_context::ImagePoolEntry entry; + entry.image = out; + entry.k_bytes = out_bytes; + pool[key] = entry; + } + } + + cl_kernel dq_kernel = tensor->type == GGML_TYPE_Q8_0 + ? backend_ctx->repack.kernel_dequant_q8_0_f16_view_aos + : backend_ctx->repack.kernel_dequant_q4_0_f16_view_aos; + + CL_CHECK(clSetKernelArg(dq_kernel, 0, sizeof(cl_mem), &src_buf)); + CL_CHECK(clSetKernelArg(dq_kernel, 1, sizeof(cl_ulong), &src_offset)); + CL_CHECK(clSetKernelArg(dq_kernel, 2, sizeof(cl_ulong), &src_nb1)); + CL_CHECK(clSetKernelArg(dq_kernel, 3, sizeof(cl_ulong), &src_nb2)); + CL_CHECK(clSetKernelArg(dq_kernel, 4, sizeof(cl_ulong), &src_nb3)); + CL_CHECK(clSetKernelArg(dq_kernel, 5, sizeof(cl_int), &nblk0)); + CL_CHECK(clSetKernelArg(dq_kernel, 6, sizeof(cl_int), &ne1_)); + CL_CHECK(clSetKernelArg(dq_kernel, 7, sizeof(cl_int), &ne2_)); + CL_CHECK(clSetKernelArg(dq_kernel, 8, sizeof(cl_int), &ne3_)); + CL_CHECK(clSetKernelArg(dq_kernel, 9, sizeof(cl_mem), &out)); + + size_t gws[3] = { (size_t) nblk0, (size_t) ne1_, (size_t) (ne2_ * ne3_) }; + size_t lws[3] = { 1, 1, 1 }; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, dq_kernel, 3, NULL, gws, lws, 0, NULL, NULL)); + + // release the reconstructed aos if + // 1. it was actually reconstructed + // 2. the caller didn't request it to be returned + // src_buf may refer to aos, so we should release after this enqueue + if (aos && !extra_reconstruct) { + CL_CHECK(clReleaseMemObject(aos)); + } + return out; +} + +static int ggml_cl_mcr_lpr_log2(int ne00) { + int lpr_log2 = 6; + while (lpr_log2 > 2 && ((ne00 / 4) >> lpr_log2) < 4) { + lpr_log2--; + } + return lpr_log2; +} + +static bool ggml_cl_mcr_wide_enough(int ne00, int ne01) { + const int rows_per_wg = 64 >> ggml_cl_mcr_lpr_log2(ne00); + return CEIL_DIV((size_t) ne01, rows_per_wg) >= 256; +} + +static bool ggml_cl_mm_f32_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + // Small-N f32 GEMV for the spec/MTP verify batch: the tiled GEMM + // below always computes a full 64x64 tile, so at ne11=3 with a + // skinny f32 weight (GDN ssm_alpha/ssm_beta, M=32) it launches one + // under-occupied WG at ~2.3% tile utilization. Route to a per-output + // (m,n) GEMV (64-thread WG, K-split + __local reduce) instead. + // 2D contiguous, small N + skinny M only. Default on for X2E, GGML_OPENCL_F32_MC=0/1 forces it. + static const int f32_mc_env = [] { + const char * env = getenv("GGML_OPENCL_F32_MC"); + return env ? atoi(env) : -1; + }(); + const bool f32_mc = f32_mc_env >= 0 ? f32_mc_env != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; + + static const int f32_mcr_env = [] { + const char * env = getenv("GGML_OPENCL_F32_MCR"); + return env && *env ? atoi(env) : -1; + }(); + const bool f32_mcr = f32_mcr_env >= 0 ? f32_mcr_env != 0 : + (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X); + const bool f32_mcr_allowed = f32_mc_env >= 0 ? f32_mc_env != 0 : !adreno_e17_compiler_quirks(backend_ctx); + + if (f32_mcr && f32_mcr_allowed && backend_ctx->mul_mat.kernel_gemv_f32_f32_mcr != nullptr && + ne11 >= 2 && ne11 <= 8 && ne00 > 0 && ne00 <= INT_MAX && ne01 > 0 && ne01 <= 512 && + (size_t) ne01 <= SIZE_MAX / 64 && (ne00 % 4 == 0) && + ne02 == 1 && ne03 == 1 && ne12 == 1 && ne13 == 1 && + dst->ne[2] == 1 && dst->ne[3] == 1 && + ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) && + offset0 % 16 == 0 && offset1 % 16 == 0 && offsetd % sizeof(float) == 0 && + ggml_cl_mcr_wide_enough((int) ne00, (int) ne01) + ) { + const int K = (int) ne00; + const int M = (int) ne01; + const int N = (int) ne11; + + const int stride_a = K; + const int stride_b = K; + const int stride_d = M; + + const int lpr_log2 = ggml_cl_mcr_lpr_log2(K); + const int rows_per_wg = 64 >> lpr_log2; + + cl_kernel mcr = backend_ctx->mul_mat.kernel_gemv_f32_f32_mcr; + + CL_CHECK(clSetKernelArg(mcr, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(mcr, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(mcr, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(mcr, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(mcr, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(mcr, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(mcr, 6, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(mcr, 7, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(mcr, 8, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(mcr, 9, sizeof(int), &stride_a)); + CL_CHECK(clSetKernelArg(mcr, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(mcr, 11, sizeof(int), &stride_d)); + CL_CHECK(clSetKernelArg(mcr, 12, sizeof(int), &lpr_log2)); + + size_t global[] = {CEIL_DIV((size_t) M, rows_per_wg) * 64, 1, 1}; + size_t local[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(mcr, 3, global, local, dst); + return true; + } + + if (f32_mc && ne11 >= 2 && ne11 <= 8 && ne01 <= 512 && (ne00 % 4 == 0) && + ne02 == 1 && ne12 == 1 && ne13 == 1 && + ggml_is_contiguous(src0) && ggml_is_contiguous(src1)) { + cl_kernel kernel = backend_ctx->mul_mat.kernel_gemv_f32_f32_mc; + + int stride_a = ne00; + int stride_b = ne00; + int stride_d = ne01; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &stride_a)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &stride_d)); + size_t global_work_size[3] = {64, (size_t) ne01 * (size_t) ne11, 1}; + size_t local_work_size[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; + } + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_f32_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + cl_mem mem_src0 = extra0->data_device; + cl_mem mem_src1 = extra1->data_device; + + cl_ulong nb00_cont = nb00; + cl_ulong nb01_cont = nb01; + cl_ulong nb02_cont = nb02; + cl_ulong nb03_cont = nb03; + + cl_ulong nb10_cont = nb10; + cl_ulong nb11_cont = nb11; + cl_ulong nb12_cont = nb12; + cl_ulong nb13_cont = nb13; + + cl_ulong offset0_cont = offset0; + cl_ulong offset1_cont = offset1; + + if (!ggml_is_contiguous(src0)) { + backend_ctx->prealloc_src0.allocate(backend_ctx->context, ggml_nbytes(src0)); + ggml_cl_copy_to_contiguous(backend, src0, backend_ctx->prealloc_src0.buffer, + nb00_cont, nb01_cont, nb02_cont, nb03_cont); + mem_src0 = backend_ctx->prealloc_src0.buffer; + offset0_cont = 0; + } + + if (!ggml_is_contiguous(src1)) { + backend_ctx->prealloc_src1.allocate(backend_ctx->context, ggml_nbytes(src1)); + ggml_cl_copy_to_contiguous(backend, src1, backend_ctx->prealloc_src1.buffer, + nb10_cont, nb11_cont, nb12_cont, nb13_cont); + mem_src1 = backend_ctx->prealloc_src1.buffer; + offset1_cont = 0; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &mem_src0)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0_cont)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &mem_src1)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1_cont)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_f16_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (ggml_cl_can_use_adreno_xmem_gemm_f16_f32(backend_ctx, src0, src1, dst)) { + ggml_cl_mul_mat_f16_f32_adreno_xmem(backend, src0, src1, dst); + return true; + } +#endif + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + static const char * mm_narrow_n_env = getenv("GGML_OPENCL_MM_NARROW_N"); + const bool use_narrow_n = (mm_narrow_n_env == nullptr || mm_narrow_n_env[0] != '0') && ne11 >= 2 && ne11 <= 8; + cl_kernel kernel = use_narrow_n ? backend_ctx->mul_mat.kernel_mul_mm_f16_f32_l4_lm_n8 : backend_ctx->mul_mat.kernel_mul_mm_f16_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + cl_mem mem_src0 = extra0->data_device; + cl_mem mem_src1 = extra1->data_device; + + cl_ulong nb00_cont = nb00; + cl_ulong nb01_cont = nb01; + cl_ulong nb02_cont = nb02; + cl_ulong nb03_cont = nb03; + + cl_ulong nb10_cont = nb10; + cl_ulong nb11_cont = nb11; + cl_ulong nb12_cont = nb12; + cl_ulong nb13_cont = nb13; + + cl_ulong offset0_cont = offset0; + cl_ulong offset1_cont = offset1; + + if (!ggml_is_contiguous(src0)) { + backend_ctx->prealloc_src0.allocate(backend_ctx->context, ggml_nbytes(src0)); + ggml_cl_copy_to_contiguous(backend, src0, backend_ctx->prealloc_src0.buffer, + nb00_cont, nb01_cont, nb02_cont, nb03_cont); + mem_src0 = backend_ctx->prealloc_src0.buffer; + offset0_cont = 0; + } + + if (!ggml_is_contiguous(src1)) { + backend_ctx->prealloc_src1.allocate(backend_ctx->context, ggml_nbytes(src1)); + ggml_cl_copy_to_contiguous(backend, src1, backend_ctx->prealloc_src1.buffer, + nb10_cont, nb11_cont, nb12_cont, nb13_cont); + mem_src1 = backend_ctx->prealloc_src1.buffer; + offset1_cont = 0; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &mem_src0)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0_cont)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &mem_src1)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1_cont)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); + + // BN=8/TN=1 keeps 128 threads for small batches, including attention KQ/KQV. + const int bn = use_narrow_n ? 8 : 64; + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, bn)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static void ggml_cl_mul_mat_f16_f32_tiled(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int M = src0->ne[1]; + const int N = src1->ne[1]; + const int K = src0->ne[0]; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_tiled; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + + // Tiling parameters. These need to be tuned for optimal performance. + // They must match the #defines in the kernel mul_mat_f16_f32.cl. + // + // OPWM / OPWN: Output tile size per Work-Group. A work-group computes a tile of size OPWM x OPWN. + // TPWM / TPWN: Threads per Work-group. This is the work-group size. + // OPTM / OPTN: Output elements per Thread. Each thread computes OPTM x OPTN elements. + // + // The following relationships must hold: + // OPWM = TPWM * OPTM + // OPWN = TPWN * OPTN + // + const int OPWM = 64; + const int OPWN = 64; + const int TPWM = 16; + const int TPWN = 8; + + size_t local_work_size[2] = { TPWM, TPWN }; + size_t global_work_size[2] = { + (size_t) ((M + OPWM - 1) / OPWM) * TPWM, + (size_t) ((N + OPWN - 1) / OPWN) * TPWN, + }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); +} + +static bool ggml_cl_mm_q1_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl_q1_0 * extra0 = (ggml_tensor_extra_cl_q1_0 *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q1_0_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q2_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q2_0 * extra0_q2_0 = (ggml_tensor_extra_cl_q2_0 *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; +if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_q2_0_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q2_0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q2_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq3_s_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq3_s * extra0_iq3_s = (ggml_tensor_extra_cl_iq3_s *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq3_s_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_s->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_s->sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_s->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq3_s->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq3_s->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq3_xxs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq3_xxs * extra0_iq3_xxs = (ggml_tensor_extra_cl_iq3_xxs *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq3_xxs_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_xxs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_xxs->sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_xxs->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq4_xs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq4_xs * extra0_iq4_xs = (ggml_tensor_extra_cl_iq4_xs *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq4_xs_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_xs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_xs->sl)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq4_xs->sh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq4_xs->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq1_m_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq1_m * extra0_iq1_m = (ggml_tensor_extra_cl_iq1_m *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq1_m_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_m->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_m->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_m->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq1_s_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq1_s * extra0_iq1_s = (ggml_tensor_extra_cl_iq1_s *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq1_s_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_s->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_s->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_s->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq2_s_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq2_s * extra0_iq2_s = (ggml_tensor_extra_cl_iq2_s *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; +if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq2_s_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_s->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_s->sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_s->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq2_s->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq2_s->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq2_xs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq2_xs * extra0_iq2_xs = (ggml_tensor_extra_cl_iq2_xs *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; +if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq2_xs_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xs->sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xs->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq2_xxs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq2_xxs * extra0_iq2_xxs = (ggml_tensor_extra_cl_iq2_xxs *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = nullptr; + int nth0 = 0; +if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + kernel = backend_ctx->mul_mat.kernel_mul_mm_iq2_xxs_f32_l4_lm; + nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + offset0 = src0->view_offs; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xxs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xxs->sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xxs->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + + +static bool ggml_cl_mm_q4_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_0 * extra0 = (ggml_tensor_extra_cl_q4_0 *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q4_0_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q4_1_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_1 * extra0 = (ggml_tensor_extra_cl_q4_1 *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q4_1_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->m)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q5_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q5_0 * extra0 = (ggml_tensor_extra_cl_q5_0 *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q5_0_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q5_1_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q5_1 * extra0 = (ggml_tensor_extra_cl_q5_1 *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q5_1_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->m)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q8_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q8_0 * extra0 = (ggml_tensor_extra_cl_q8_0 *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q8_0_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_iq4_nl_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq4_nl * extra0 = (ggml_tensor_extra_cl_iq4_nl *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_iq4_nl_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q2_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q2_K * extra0 = (ggml_tensor_extra_cl_q2_K *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q2_k_f32_l4_lm; + const int nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q3_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q3_K * extra0 = (ggml_tensor_extra_cl_q3_K *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + int r2 = ne12/ne02; + int r3 = ne13/ne03; + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q3_k_f32_l4_lm; + const int nth0 = (backend_ctx->gpu_family == GPU_FAMILY::INTEL) ? 64 : 128; + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->hm)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); + + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)CEIL_DIV(ne11, 64), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q4_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_K * extra0 = (ggml_tensor_extra_cl_q4_K *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q4_k_f32_l4_lm; + // (BM*BN)/(TM*TN): Intel uses an 8x8 microtile (WG=64), others 4x8 (WG=128) + const int nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->s)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q5_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q5_K * extra0 = (ggml_tensor_extra_cl_q5_K *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q5_k_f32_l4_lm; + const int nth0 = (backend_ctx->gpu_family == INTEL) ? 64 : 128; // Intel 8x8 microtile + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0->dm)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static bool ggml_cl_mm_q6_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + if (ne11 < 32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1)) { + return false; + } + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q6_K * extra0 = (ggml_tensor_extra_cl_q6_K *) soa0_src->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mm_q6_k_f32_l4_lm; + const int nth0 = 128; // calculated as (BM*BN)/(TM*TN) + + int batch_stride_a = ne00*ne01; + int batch_stride_b = ne10*ne11; + int batch_stride_d = ne0*ne1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->ql)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); // stride_a + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne10)); // stride_b + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne01)); // stride_d + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &batch_stride_a)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &batch_stride_b)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &batch_stride_d)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); + + // 64 is block tile size BM and BN - change here when BM and BN in the kernel are changed. + size_t global_work_size[] = {(size_t)(CEIL_DIV(ne01, 64)*nth0), (size_t)(CEIL_DIV(ne11, 64)), (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; +} + +static void ggml_cl_mv_f32_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool f32_use_mv) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int nrows = 1; + cl_kernel kernel; + + //GGML_ASSERT(ne02 == ne12); + kernel = backend_ctx->mul_mat.kernel_mul_mat_f32_f32; + nrows = 4; + if (f32_use_mv && ne11 > 1 && backend_ctx->mul_mat.kernel_mul_mv_f32_f32_r2 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mv_f32_f32_r2; + } + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 32; + nth1 = 1; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); + + int64_t ny = (ne11 + nrows - 1)/nrows; + int64_t nx = kernel == backend_ctx->mul_mat.kernel_mul_mv_f32_f32_r2 ? CEIL_DIV(ne01, 2) : ne01; + + size_t global_work_size[] = {(size_t)nx*nth0, (size_t)ny*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_f16_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int nrows = 1; + cl_kernel kernel; + bool use_f16_mrow = false; + + //GGML_ASSERT(ne02 == ne12); + if (backend_ctx->gpu_family == INTEL) { + nth0 = 32; + nth1 = 1; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + // heuristic for packing more work for Adreno + const bool adreno_use_lane_split = + backend_ctx->gpu_family == ADRENO && + ne11 == 1 && + ne01 >= 8 && + ne00 % 4 == 0 && + r3 == 1 && r2 >= 1 && r2 <= 8 && + (ne12 % r2) == 0; + + if (ne11 * ne12 < 4) { + // Decode (single token): the legacy _1row runs one 64-lane + // subgroup per WG (one output row), under-utilizing BW. Route the + // wide f16 weight matmuls (attn proj + lm_head) to the multi-row + // variant: MROW rows per WG -> more loads in flight + activation + // staged once in __local. ne00<=8192 bounds the LDS. The mrow WG + // is 64 x MROW = 1024 work-items (> Intel's 512 max) and reduces + // within a 64-wide subgroup, so skip on Intel. + if (backend_ctx->f16_mrow && backend_ctx->gpu_family != INTEL && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow != nullptr && + ne00 >= 128 && ne01 >= 8 && ne00 % 4 == 0 && ne00 <= 8192) { + // The register-blocked / half8 variants cast the src0 row pointer to + // half4 / half8 (8- and 16-byte loads) with no scalar fallback inside + // the kernel. ne00 % 4 == 0 constrains the element count per row, NOT + // the byte stride between rows: a permuted or strided src0 (or a view + // at an odd offset) can leave nb01/nb02/nb03 unaligned. Only take them + // when every row this dispatch touches is aligned; the base mrow kernel + // re-checks per row and falls back to its scalar loop. + const cl_ulong row_addr_bits = offset0 | nb01 | nb02 | nb03; + const bool aligned8 = (row_addr_bits & 7) == 0; + const bool aligned16 = (row_addr_bits & 15) == 0; + + // Register-blocked variants: each subgroup does RPT rows (more + // weight loads in flight per lane). 8/16 use half8 (128-bit) + // loads, gated on ne00 % 8 == 0. + const int rpt = backend_ctx->f16_mrow_rpt; + if (rpt == 16 && ne00 % 8 == 0 && aligned16 && backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_h8r2 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_h8r2; + } else if (rpt == 8 && ne00 % 8 == 0 && aligned16 && backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_h8 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_h8; + } else if (rpt == 4 && aligned8 && backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_r4 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_r4; + } else if (rpt == 2 && aligned8 && backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_r2 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow_r2; + } else { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_mrow; + } + use_f16_mrow = true; + } else { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_1row; + } + } else if (adreno_use_lane_split && ne00 >= 64 && ne00 <= 128) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr_lq; + nrows = 1; + } else if (adreno_use_lane_split && r2 >= 2 && ne00 > 128 && ne00 <= 256) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr_ls; + nrows = 1; + } else if (ne00 >= 128 && ne01 >= 8 && ne00%4 == 0) { + // multi-output decode variants when Q is a single row + static const char * mm_force_l4_env = getenv("GGML_OPENCL_MM_F16_FORCE_L4"); + static const bool mm_force_l4_on = (mm_force_l4_env != nullptr && mm_force_l4_env[0] != '0'); + const bool can_multi_out = !mm_force_l4_on && ne11 == 1 && ne01 >= 64 && ne01 % 8 == 0; + // paired-K-row variant that doubles per-wave-cycle + static const char * mm_kq_pair_env = getenv("GGML_OPENCL_MM_KQ_PAIR"); + static const bool mm_kq_pair_on = (mm_kq_pair_env != nullptr && mm_kq_pair_env[0] != '0'); + // GQA-coalesced variant that reads each K-row once and + // emits gqa_ratio outputs + static const char * mm_kq_gqa_env = getenv("GGML_OPENCL_MM_KQ_GQA"); + static const bool mm_kq_gqa_on = (mm_kq_gqa_env != nullptr && mm_kq_gqa_env[0] != '0'); + // GQA-coalesced KQV variant (DK=128/r2=8/r3=1) that reads + // each V slab once per K-head and emits all r2 Q-heads + static const char * mm_kqv_gqa_env = getenv("GGML_OPENCL_MM_KQV_GQA"); + static const bool mm_kqv_gqa_on = (mm_kqv_gqa_env != nullptr && mm_kqv_gqa_env[0] != '0'); + if (can_multi_out && (ne01 % 16) == 0 && ne00 == 128 && r2 == 8 && r3 == 1 && mm_kq_gqa_on && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4; + nrows = 1; + } else if (can_multi_out && ne00 <= 256 && mm_kq_pair_on && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_pair != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_pair; + nrows = 1; + } else if (can_multi_out && ne00 <= 256 && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8; + nrows = 1; + } else if (can_multi_out && ne01 == 128 && r2 == 8 && r3 == 1 && mm_kqv_gqa_on && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa; + nrows = 1; + } else if (can_multi_out && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8 != nullptr) { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8; + nrows = 1; + } else if (ne11 == 1) { + // Decode shapes that don't satisfy the x8/y8 row + // constraints (ne01 < 64 or ne01 % 8 != 0) fall back to + // upstream's 4-output _dr kernel. + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr; + nrows = 1; // not used by this kernel + } else { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4; + nrows = ne11; + } + } else { + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32; + nrows = 4; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); + if (use_f16_mrow) { + const int MROW = 16; // must match MROW in mul_mv_f16_f32_mrow.cl + // rows-per-subgroup multiplier for the selected variant: + // 1/2/4 -> half4 register blocking; 8 -> half8(1 row); 16 -> half8(2 rows) + const int rpt = backend_ctx->f16_mrow_rpt; + int rmul; + if (rpt == 16) { + rmul = (ne00 % 8 == 0) ? 2 : 1; + } else if (rpt == 8) { + rmul = 1; + } else { + rmul = rpt; // 1,2,4 + } + + const int rows_per_wg = MROW * rmul; + // __local activation buffer: ne00 floats, rounded up for float4 access + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float) * ((ne00 + 3) / 4 * 4), nullptr)); + size_t mrow_global[] = { (size_t)((ne01 + rows_per_wg - 1) / rows_per_wg) * 64, (size_t)ne11 * MROW, (size_t)ne12 * ne13 }; + size_t mrow_local[] = { 64, (size_t)MROW, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, mrow_global, mrow_local, dst); + return; + } + + if (kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8 || + kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_pair || + kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8) { + // multi-output decode variants: each WG processes 8 outputs along ne01, ne11 == 1 + const int64_t n_wg_x = ne01 / 8; + size_t global_work_size[] = {(size_t)n_wg_x*nth0, (size_t)nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else if (kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4) { + // GQA-coalesced KQ: one WG per K-head emits N_K_ROWS_GQA=16 K-rows * r2 Q-heads + const int64_t n_wg_x = ne01 / 16; + size_t global_work_size[] = {(size_t)n_wg_x*nth0, (size_t)nth1, (size_t)ne02*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else if (kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa) { + // GQA-coalesced KQV: one WG per K-head emits 8 DV-rows * r2 Q-heads + const int64_t n_wg_x = ne01 / 8; + size_t global_work_size[] = {(size_t)n_wg_x*nth0, (size_t)nth1, (size_t)ne02*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else { + if (kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr) { + const int NDST_DR = 4; + size_t global_work_size[] = {(size_t)CEIL_DIV(ne01, NDST_DR)*nth0, (size_t)nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else if (kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr_ls) { + size_t global_work_size[] = {(size_t)CEIL_DIV(ne01, 2)*nth0, (size_t)nth1, (size_t)ne02*ne03}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else if (kernel == backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_dr_lq) { + size_t global_work_size[] = {(size_t)CEIL_DIV(ne01, 4)*nth0, (size_t)nth1, (size_t)ne02*ne03}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else { + int64_t ny = (ne11 + nrows - 1)/nrows; + + size_t global_work_size[] = {(size_t)ne01*nth0, (size_t)ny*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } + } + +} + +static void ggml_cl_mv_f16_f16(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int nrows = 4; + cl_kernel kernel; + + //GGML_ASSERT(ne02 == ne12); + if (backend_ctx->gpu_family == INTEL) { + nth0 = 32; + nth1 = 1; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f16; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); + + int64_t ny = (ne11 + nrows - 1)/nrows; + + size_t global_work_size[] = {(size_t)ne01*nth0, (size_t)ny*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q1_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl_q1_0 * extra0_q1_0 = (ggml_tensor_extra_cl_q1_0 *) src0->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q1_0_f32_flat; + + // nth0 - subgroup size + // nth1 - number of subgroups per workgroup + // ndst - number of output values per workgroup = output per subgroup * number of subgroups + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = nth1*4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = nth1*4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q1_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q1_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q1_0_f32; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = nth1*4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = nth1*4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q2_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q2_0 * extra0_q2_0 = (ggml_tensor_extra_cl_q2_0 *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; +if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q2_0_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q2_0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q2_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q2_0_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq3_xxs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq3_xxs * extra0_iq3_xxs = (ggml_tensor_extra_cl_iq3_xxs *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq3_xxs_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_xxs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_xxs->sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_xxs->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq3_xxs_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq4_xs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq4_xs * extra0_iq4_xs = (ggml_tensor_extra_cl_iq4_xs *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq4_xs_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_xs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_xs->sl)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq4_xs->sh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq4_xs->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq4_xs_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq3_s_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq3_s * extra0_iq3_s = (ggml_tensor_extra_cl_iq3_s *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq3_s_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq3_s->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq3_s->sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq3_s->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq3_s->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq3_s->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq3_s_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq1_m_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq1_m * extra0_iq1_m = (ggml_tensor_extra_cl_iq1_m *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq1_m_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_m->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_m->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_m->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq1_m_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq1_s_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq1_s * extra0_iq1_s = (ggml_tensor_extra_cl_iq1_s *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq1_s_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq1_s->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq1_s->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq1_s->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq1_s_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq2_s_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq2_s * extra0_iq2_s = (ggml_tensor_extra_cl_iq2_s *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; +if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq2_s_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_s->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_s->sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_s->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_iq2_s->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_iq2_s->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq2_s_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq2_xs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq2_xs * extra0_iq2_xs = (ggml_tensor_extra_cl_iq2_xs *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; +if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq2_xs_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xs->sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xs->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq2_xs_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq2_xxs_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq2_xxs * extra0_iq2_xxs = (ggml_tensor_extra_cl_iq2_xxs *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; +if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq2_xxs_f32_flat; + offset0 = src0->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq2_xxs->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq2_xxs->sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_iq2_xxs->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq2_xxs_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + + +static void ggml_cl_mv_q4_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + + // This should have been satisfied. + GGML_ASSERT(ne11 == ne1); + GGML_ASSERT(ne01 == ne0); + +#ifdef GGML_OPENCL_SOA_Q + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + + kernel = backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_8x_flat; + ndst = 8; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + + kernel = backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_8x_flat; + ndst =8; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#else // GGML_OPENCL_SOA_Q + if (backend_ctx->gpu_family == INTEL) { + // Use 1D local size. Each workgroup is a SIMD group. Each SIMD + // group produces N_DST (4 for Q4_0 kernel) values in the result. + // The number of workgroups on dim 0 (the leading dimension) is + // the nearest multiple of 4 that covers ne0 (equals ne01). + nth0 = 16; + nth1 = 1; + + kernel = backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + + kernel = backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_v; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q4_1_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_1 * extra0_q4_1 = (ggml_tensor_extra_cl_q4_1 *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + kernel = backend_ctx->mul_mat.kernel_mul_mv_q4_1_f32_flat; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_1->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_1->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_1->m)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r3)); +#else + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + kernel = backend_ctx->mul_mat.kernel_mul_mv_q4_1_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q5_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q5_0 * extra0_q5_0 = (ggml_tensor_extra_cl_q5_0 *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + kernel = backend_ctx->mul_mat.kernel_mul_mv_q5_0_f32_flat; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r3)); +#else + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + kernel = backend_ctx->mul_mat.kernel_mul_mv_q5_0_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q5_1_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q5_1 * extra0_q5_1 = (ggml_tensor_extra_cl_q5_1 *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + kernel = backend_ctx->mul_mat.kernel_mul_mv_q5_1_f32_flat; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_1->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_1->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_1->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_1->m)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r3)); +#else + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + kernel = backend_ctx->mul_mat.kernel_mul_mv_q5_1_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q8_0_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q8_0 * extra0_q8_0 = (ggml_tensor_extra_cl_q8_0 *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q8_0_f32_flat; + + // nth0 - subgroup size + // nth1 - number of subgroups per workgroup + // ndst - number of output values per workgroup = output per subgroup * number of subgroups + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = nth1*4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = nth1*4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q8_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q8_0_f32; + + // nth0 - subgroup size + // nth1 - number of subgroups per workgroup + // ndst - number of output values per workgroup = output per subgroup * number of subgroups + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = nth1*4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = nth1*4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_iq4_nl_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_iq4_nl * extra0_iq4_nl = (ggml_tensor_extra_cl_iq4_nl *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq4_nl_f32_flat; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 8; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 8; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_nl->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_nl->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_iq4_nl_f32; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + // Each subgroup produces N_DST values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q2_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q2_K * extra0_q2_K = (ggml_tensor_extra_cl_q2_K *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q2_K_f32_flat; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q2_K->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q2_K->sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q2_K->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q2_K_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif + + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q3_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q3_K * extra0_q3_K = (ggml_tensor_extra_cl_q3_K *) soa0_src->extra; + cl_ulong offset0 = src0->view_offs; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + int r2 = ne12/ne02; + int r3 = ne13/ne03; + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 2; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 2; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q3_K_f32_flat; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q3_K->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q3_K->hm)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q3_K->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q3_K->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q3_K_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q4_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_K * extra0_q4_K = (ggml_tensor_extra_cl_q4_K *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q4_K_f32_flat; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 16; // 8->16 rows per subgroup - matches N_DST in mul_mv_q4_k_f32_flat.cl (32 spills) + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = 16; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_K->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_K->s)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_K->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_K->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q4_K_f32; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(int), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + size_t global_work_size[] = {(size_t)(ne01+ndst*nth1-1)/(ndst*nth1)*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q5_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q5_K * extra0_q5_K = (ggml_tensor_extra_cl_q5_K *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q5_K_f32_flat; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 8; // 4->8 rows per subgroup (2x activation reuse) + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = 16; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_K->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_K->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_K->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_K->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_K->dm)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q5_K_f32; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(int), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + size_t global_work_size[] = {(size_t)(ne01+ndst*nth1-1)/(ndst*nth1)*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_q6_k_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_q6_K_f32_flat; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = 16; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r3)); + // The optimizer-barrier arg exists only in the ADRENO_OLD_COMPILER build of + // this kernel; conformant compilers get the original 17-arg signature. + if (backend_ctx->q6_k_flat_old_compiler) { + cl_uchar q6k_mask = 0xFF; // never 0xFE in prod; see the kernel note + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_uchar), &q6k_mask)); + } +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_q6_K_f32; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = 1; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = 1; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); +#endif // GGML_OPENCL_SOA_Q + + size_t global_work_size[] = {(size_t)(ne01+ndst*nth1-1)/(ndst*nth1)*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +static void ggml_cl_mv_mxfp4_f32(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + +#ifndef GGML_OPENCL_SOA_Q + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + cl_ulong offset0 = extra0->offset + src0->view_offs; +#endif + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_mxfp4 * extra0_mxfp4 = (ggml_tensor_extra_cl_mxfp4 *) soa0_src->extra; +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + int nth0 = 32; + int nth1 = 1; + int ndst = 4; + cl_kernel kernel; + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat.kernel_mul_mv_mxfp4_f32_flat; + + cl_mem q; + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = nth1*2; + + q = extra0_mxfp4->q; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = nth1*2; + + q = extra0_mxfp4->q_img; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_mxfp4->e)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r3)); +#else + kernel = backend_ctx->mul_mat.kernel_mul_mv_mxfp4_f32; + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 2; + ndst = nth1*2; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 2; + ndst = nth1*2; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &r3)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(float)*nth0,nullptr)); +#endif + + // Each SIMD group produces N_DST values in the result. Assuming each + // workgroup has N_SIMDGROUP SIMD groups, then each workgroup will + // produce N_DST*N_SIMDGROUP values in the result. + size_t global_work_size[] = {(size_t)(ne01 + ndst-1)/ndst*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +bool ggml_cl_mul_mat_can_use_fwht(const ggml_backend_opencl_context * backend_ctx, const ggml_tensor * op) { + const ggml_tensor * a = op->src[0]; + const ggml_tensor * b = op->src[1]; + const int64_t n = a->ne[0]; + + return ggml_get_op_params_i32(op, 1) == GGML_HINT_SRC0_IS_HADAMARD && + a->type == GGML_TYPE_F32 && op->type == GGML_TYPE_F32 && + (b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16) && + n >= 2 && n <= std::numeric_limits::max() && (n & (n - 1)) == 0 && a->ne[1] == n && + (uint64_t)n <= backend_ctx->local_mem_size/sizeof(float) && + ggml_is_contiguous_rows(b) && ggml_is_contiguous(op) && ggml_are_same_shape(b, op); +} + +static void ggml_cl_fwht(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst) { + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + auto * extra_src = (ggml_tensor_extra_cl *) src->extra; + auto * extra_dst = (ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset_src = extra_src->offset + src->view_offs; + const cl_ulong offset_dst = extra_dst->offset + dst->view_offs; + + const cl_ulong ne1 = src->ne[1]; + const cl_ulong ne2 = src->ne[2]; + const cl_ulong nb1 = src->nb[1]; + const cl_ulong nb2 = src->nb[2]; + const cl_ulong nb3 = src->nb[3]; + + const int n = src->ne[0]; + const float scale = 1.0f/sqrtf((float)n); + const int type_index = src->type == GGML_TYPE_F16 ? 1 : 0; + + cl_kernel kernel = backend_ctx->mul_mat.kernel_fwht[type_index]; + const size_t nth = std::min((size_t)n/2, backend_ctx->mul_mat.fwht_workgroup_size[type_index]); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset_src)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset_dst)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 11, n*sizeof(float), nullptr)); + + size_t global[] = { nth, (size_t)ggml_nrows(src) }; + size_t local[] = { nth, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst); +} + +void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + // bf16 is stored as f16 on device + const enum ggml_type src0t = (src0->type == GGML_TYPE_BF16) ? GGML_TYPE_F16 : src0->type; + const enum ggml_type src1t = src1->type; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + if (ggml_cl_mul_mat_can_use_fwht(backend_ctx, dst)) { + ggml_cl_fwht(backend, src1, dst); + return; + } + + // quant kv without FA + // used for non-contiguous src0 (the usual head-major permuted K view when n_head_kv>1) + // AND for the contiguous case that occurs when n_head_kv==1 (e.g. Gemma-4 E2B) + // Q4_0 bin kernels use a special weight layout, which the restore below does not support. + bool q4_0_bin_layout = false; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + q4_0_bin_layout = src0t == GGML_TYPE_Q4_0 && src0->view_src == nullptr && + ggml_is_contiguous(src0) && + src0->ne[2] == 1 && src0->ne[3] == 1 && + use_adreno_kernels(backend_ctx, src0) && + !use_adreno_moe_kernels(backend_ctx, src0) && + use_q4_0_bin_kernels(backend_ctx, src0); +#endif + if ((src0t == GGML_TYPE_Q4_0 || src0t == GGML_TYPE_Q8_0) && !q4_0_bin_layout && + (!ggml_is_contiguous(src0) || src1->ne[2] > src0->ne[2])) { + cl_mem f16_buf = ggml_cl_mul_mat_dequant_quant_to_f16(backend_ctx, src0, nullptr); + + ggml_tensor fake_src0 = *src0; + ggml_tensor_extra_cl fake_extra = {}; + fake_extra.data_device = f16_buf; + fake_extra.offset = 0; + fake_src0.type = GGML_TYPE_F16; + fake_src0.extra = &fake_extra; + fake_src0.view_src = nullptr; + fake_src0.view_offs = 0; + fake_src0.nb[0] = sizeof(ggml_fp16_t); + fake_src0.nb[1] = fake_src0.nb[0] * src0->ne[0]; + fake_src0.nb[2] = fake_src0.nb[1] * src0->ne[1]; + fake_src0.nb[3] = fake_src0.nb[2] * src0->ne[2]; + + ggml_cl_mul_mat(backend, &fake_src0, src1, dst); + return; + } + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + +#ifdef GGML_OPENCL_SOA_Q + // view->extra stays pre-SoA; cast to the SoA struct would SIGSEGV. + // Follow view_src to reach the real SoA extra. + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)soa0_src->extra; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_tensor_extra_cl_q2_0 * extra0_q2_0 = (ggml_tensor_extra_cl_q2_0 *)soa0_src->extra; + ggml_tensor_extra_cl_q2_K * extra0_q2_K = (ggml_tensor_extra_cl_q2_K *)soa0_src->extra; + ggml_tensor_extra_cl_q3_K * extra0_q3_K = (ggml_tensor_extra_cl_q3_K *)soa0_src->extra; + ggml_tensor_extra_cl_iq2_s * extra0_iq2_s = (ggml_tensor_extra_cl_iq2_s *)soa0_src->extra; + ggml_tensor_extra_cl_iq2_xs * extra0_iq2_xs = (ggml_tensor_extra_cl_iq2_xs *)soa0_src->extra; + ggml_tensor_extra_cl_iq2_xxs * extra0_iq2_xxs = (ggml_tensor_extra_cl_iq2_xxs *)soa0_src->extra; + ggml_tensor_extra_cl_iq1_m * extra0_iq1_m = (ggml_tensor_extra_cl_iq1_m *)soa0_src->extra; + ggml_tensor_extra_cl_iq1_s * extra0_iq1_s = (ggml_tensor_extra_cl_iq1_s *)soa0_src->extra; + ggml_tensor_extra_cl_iq3_s * extra0_iq3_s = (ggml_tensor_extra_cl_iq3_s *)soa0_src->extra; + ggml_tensor_extra_cl_iq3_xxs * extra0_iq3_xxs = (ggml_tensor_extra_cl_iq3_xxs *)soa0_src->extra; + ggml_tensor_extra_cl_iq4_xs * extra0_iq4_xs = (ggml_tensor_extra_cl_iq4_xs *)soa0_src->extra; +#endif // GGML_OPENCL_USE_ADRENO_KERNELS +#endif + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + int r2 = ne12/ne02; + int r3 = ne13/ne03; + + GGML_ASSERT(ne00 == ne10); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // adreno GEMM/GEMV kernels do not support broadcast, assuming ne2 and ne3 are 1 for src1 + // so we handle broadcast here + if ((ne12 > 1 || ne13 > 1) && ne02 == 1 && ne03 == 1 && + src0t != GGML_TYPE_F16 && src0t != GGML_TYPE_F32) { + for (int i13 = 0; i13 < ne13; ++i13) { + for (int i12 = 0; i12 < ne12; ++i12) { + ggml_tensor s1 = *src1; + s1.ne[2] = 1; s1.ne[3] = 1; + s1.view_offs = src1->view_offs + (size_t)i12*nb12 + (size_t)i13*nb13; + ggml_tensor d = *dst; + d.ne[2] = 1; d.ne[3] = 1; + d.view_offs = dst->view_offs + (size_t)i12*nb2 + (size_t)i13*nb3; + d.src[1] = &s1; + ggml_cl_mul_mat(backend, src0, &s1, &d); + } + } + return; + } +#endif + + int nth0 = 32; + int nth1 = 1; + + cl_kernel kernel; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (ggml_cl_mul_mat_f16_f32_attn_adreno(backend, src0, src1, dst)) { + return; + } +#endif + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (ne01 && ne1 && use_adreno_kernels(backend_ctx, src0)) { + // NOTE: Kernels using image1d_buffer_t (e.g., src0_q) would normally require + // a limit check, but q4_0 / q4_1 tensors are very unlikely to exceed that + // limit, so the check is omitted. + + // q1_0 x fp32 + if (src0t == GGML_TYPE_Q1_0 && src1t == GGML_TYPE_F32 && + enable_adreno_trans_weight(backend_ctx, src0)) { + ggml_cl_mul_mat_q1_0_f32_adreno(backend, src0, src1, dst); + return; + } + + // q2_0 x fp32 + if (src0t == GGML_TYPE_Q2_0 && src1t == GGML_TYPE_F32 && extra0_q2_0->noshuffle) { + ggml_cl_mul_mat_q2_0_f32_adreno(backend, src0, src1, dst); + return; + } + + // q4_0 x fp32 + if(src0t == GGML_TYPE_Q4_0 && src1t == GGML_TYPE_F32) { + ggml_cl_mul_mat_q4_0_f32_adreno(backend, src0, src1, dst); + return; + } + + // q4_1 x fp32 + if (src0t == GGML_TYPE_Q4_1 && src1t == GGML_TYPE_F32) { + ggml_cl_mul_mat_q4_1_f32_adreno(backend, src0, src1, dst); + return; + } + + // q5_0 x fp32 + if (src0t == GGML_TYPE_Q5_0 && src1t == GGML_TYPE_F32) { + ggml_cl_mul_mat_q5_0_f32_adreno(backend, src0, src1, dst); + return; + } + + // q5_1 x fp32 + if (src0t == GGML_TYPE_Q5_1 && src1t == GGML_TYPE_F32) { + ggml_cl_mul_mat_q5_1_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq4_nl x fp32 + if (src0t == GGML_TYPE_IQ4_NL && src1t == GGML_TYPE_F32) { + ggml_cl_mul_mat_iq4_nl_f32_adreno(backend, src0, src1, dst); + return; + } + + // q8_0 x fp32 + if (src0t == GGML_TYPE_Q8_0 && src1t == GGML_TYPE_F32 && + enable_adreno_trans_weight(backend_ctx, src0)) { + ggml_cl_mul_mat_q8_0_f32_adreno(backend, src0, src1, dst); + return; + } + + // q2_k x fp32 + if (src0t == GGML_TYPE_Q2_K && src1t == GGML_TYPE_F32 && extra0_q2_K->noshuffle) { + ggml_cl_mul_mat_q2_k_f32_adreno(backend, src0, src1, dst); + return; + } + + // q3_k x fp32 + if (src0t == GGML_TYPE_Q3_K && src1t == GGML_TYPE_F32 && extra0_q3_K->noshuffle) { + ggml_cl_mul_mat_q3_k_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq2_s x fp32 + if (src0t == GGML_TYPE_IQ2_S && src1t == GGML_TYPE_F32 && extra0_iq2_s->noshuffle) { + ggml_cl_mul_mat_iq2_s_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq2_xs x fp32 + if (src0t == GGML_TYPE_IQ2_XS && src1t == GGML_TYPE_F32 && extra0_iq2_xs->noshuffle) { + ggml_cl_mul_mat_iq2_xs_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq2_xxs x fp32 + if (src0t == GGML_TYPE_IQ2_XXS && src1t == GGML_TYPE_F32 && extra0_iq2_xxs->noshuffle) { + ggml_cl_mul_mat_iq2_xxs_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq3_s x fp32 + if (src0t == GGML_TYPE_IQ3_S && src1t == GGML_TYPE_F32 && extra0_iq3_s->noshuffle) { + ggml_cl_mul_mat_iq3_s_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq3_xxs x fp32 + if (src0t == GGML_TYPE_IQ3_XXS && src1t == GGML_TYPE_F32 && extra0_iq3_xxs->noshuffle) { + ggml_cl_mul_mat_iq3_xxs_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq4_xs x fp32 + if (src0t == GGML_TYPE_IQ4_XS && src1t == GGML_TYPE_F32 && extra0_iq4_xs->noshuffle) { + ggml_cl_mul_mat_iq4_xs_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq1_m x fp32 + if (src0t == GGML_TYPE_IQ1_M && src1t == GGML_TYPE_F32 && extra0_iq1_m->noshuffle) { + ggml_cl_mul_mat_iq1_m_f32_adreno(backend, src0, src1, dst); + return; + } + + // iq1_s x fp32 + if (src0t == GGML_TYPE_IQ1_S && src1t == GGML_TYPE_F32 && extra0_iq1_s->noshuffle) { + ggml_cl_mul_mat_iq1_s_f32_adreno(backend, src0, src1, dst); + return; + } + + // q4_k x fp32 + if (src0t == GGML_TYPE_Q4_K && src1t == GGML_TYPE_F32 && !use_flat_gemv_for_large_m_q4_K(backend_ctx, src0)) { + ggml_cl_mul_mat_q4_K_f32_adreno(backend, src0, src1, dst); + return; + } + + // q6_K x fp32 + if (src0t == GGML_TYPE_Q6_K && src1t == GGML_TYPE_F32 && !use_flat_gemv_for_large_m_q6_K(backend_ctx, src0)) { + ggml_cl_mul_mat_q6_K_f32_adreno(backend, src0, src1, dst); + return; + } + + // q5_K x fp32 + if (src0t == GGML_TYPE_Q5_K && src1t == GGML_TYPE_F32 && + enable_adreno_trans_weight_q5_K(backend_ctx, src0)) { + ggml_cl_mul_mat_q5_K_f32_adreno(backend, src0, src1, dst); + return; + } + } // if (ne01 && ne1) +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + // GEMM using local memory + // Current BK = 16, so ne00 % 16 == 0 + // + // Certain A7X compiler (E031.41) executes kernel_mul_mm_f32_f32_l4_lm poorly; + // matrices with ne11 <= 8 appears OK. + // Fallback to the MV style kernels for A7x and ne11 > 8. + // Override with GGML_OPENCL_A7X_F32_LM_BYPASS=0. + static const char * a7x_f32lm_env = getenv("GGML_OPENCL_A7X_F32_LM_BYPASS"); + static const bool a7x_f32lm_bypass = (a7x_f32lm_env == nullptr || a7x_f32lm_env[0] != '0'); + // The 64-column tile wastes work on small F32 matrices, including block rotations. + const bool f32_use_mv = (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || + (backend_ctx->mul_mat.kernel_mul_mv_f32_f32_r2 != nullptr && ne00 <= 512)) && + src0t == GGML_TYPE_F32 && ne00 >= 256 && ne00 <= 1024 && ne00 % 16 == 0 && ne01 <= 512 && ne11 <= 16 && + ne02 == 1 && ne12 == 1 && ne13 == 1 && + ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && (offset0 | offset1) % 16 == 0; + if (src1t == GGML_TYPE_F32 && + ne00 % 16 == 0 && + ne11 > 1 && !f32_use_mv && + !(a7x_f32lm_bypass && src0t == GGML_TYPE_F32 && ne11 > 8 && + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X)) { + switch(src0t) { + case GGML_TYPE_F32: + if (ggml_cl_mm_f32_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_F16: + if (ggml_cl_mm_f16_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q1_0: + if (ggml_cl_mm_q1_0_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q2_0: + if (ggml_cl_mm_q2_0_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q4_0: + if (ggml_cl_mm_q4_0_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q4_1: + if (ggml_cl_mm_q4_1_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q5_0: + if (ggml_cl_mm_q5_0_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q5_1: + if (ggml_cl_mm_q5_1_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q8_0: + if (ggml_cl_mm_q8_0_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ4_NL: + if (ggml_cl_mm_iq4_nl_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q2_K: + if (ggml_cl_mm_q2_k_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q3_K: + if (ggml_cl_mm_q3_k_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ3_S: + if (ggml_cl_mm_iq3_s_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ3_XXS: + if (ggml_cl_mm_iq3_xxs_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ4_XS: + if (ggml_cl_mm_iq4_xs_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ1_M: + if (ggml_cl_mm_iq1_m_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ1_S: + if (ggml_cl_mm_iq1_s_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ2_S: + if (ggml_cl_mm_iq2_s_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ2_XS: + if (ggml_cl_mm_iq2_xs_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_IQ2_XXS: + if (ggml_cl_mm_iq2_xxs_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q4_K: + if (ggml_cl_mm_q4_k_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q5_K: + if (ggml_cl_mm_q5_k_f32(backend, src0, src1, dst)) { + return; + } + break; + case GGML_TYPE_Q6_K: + if (ggml_cl_mm_q6_k_f32(backend, src0, src1, dst)) { + return; + } + break; + default: + break; + } + } + + if (src0t == GGML_TYPE_F16 && src1t == GGML_TYPE_F32 && + src0->ne[1] > 32 && // M > 32 + src1->ne[1] > 32 && // N > 32 + src0->ne[0] > 32 && // K > 32 + src0->ne[2] == 1 && src0->ne[3] == 1 && + src1->ne[2] == 1 && src1->ne[3] == 1 && + ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_tiled != NULL) { + ggml_cl_mul_mat_f16_f32_tiled(backend, src0, src1, dst); + return; + } + + if (!ggml_is_transposed(src0) && + !ggml_is_transposed(src1) && + src1t == GGML_TYPE_F32 && + ne00%32 == 0 && + ne11 > 2) { +#ifdef GGML_OPENCL_SOA_Q + // Set up kernel. + switch(src0t) { + case GGML_TYPE_Q4_0: + // This should have been satisfied. + GGML_ASSERT(ne11 == ne1); + GGML_ASSERT(ne01 == ne0); + + if (backend_ctx->gpu_family == INTEL) { + nth0 = 16; + nth1 = 1; + + kernel = backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_1d_16x_flat; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + nth1 = 1; + + kernel = backend_ctx->mul_mat.kernel_mul_mat_q4_0_f32_1d_8x_flat; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); + break; + default: + break; + } + + // Launch kernel. + if (src0t == GGML_TYPE_Q4_0) { + size_t global_work_size[] = {(size_t)(ne01 + 7)/8*nth0, (size_t)ne11*nth1, (size_t)ne12*ne13}; + size_t local_work_size[] = {(size_t)nth0, (size_t)nth1, 1}; + + if (backend_ctx->gpu_family == INTEL) { + // Set global size for Intel. It uses 16x output values. + global_work_size[0] = (size_t)(ne01 + 15)/16*nth0; + global_work_size[1] = (size_t)ne11*nth1; + global_work_size[2] = (size_t)ne12*ne13; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return; + } +#else // GGML_OPENCL_SOA_Q + // TODO: add block_q4_0 variant. +#endif // GGML_OPENCL_SOA_Q + } + + // use custom matrix x vector kernel + switch (src0t) { + case GGML_TYPE_F32: + GGML_ASSERT(src1t == GGML_TYPE_F32); + ggml_cl_mv_f32_f32(backend, src0, src1, dst, f32_use_mv); + return; + case GGML_TYPE_F16: + if (src1t == GGML_TYPE_F32) { + ggml_cl_mv_f16_f32(backend, src0, src1, dst); + } else { + ggml_cl_mv_f16_f16(backend, src0, src1, dst); + } + return; + case GGML_TYPE_Q1_0: + ggml_cl_mv_q1_0_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q2_0: + ggml_cl_mv_q2_0_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q4_0: + ggml_cl_mv_q4_0_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q4_1: + ggml_cl_mv_q4_1_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q5_0: + ggml_cl_mv_q5_0_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q5_1: + ggml_cl_mv_q5_1_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q8_0: + ggml_cl_mv_q8_0_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ4_NL: + ggml_cl_mv_iq4_nl_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q2_K: + ggml_cl_mv_q2_k_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q3_K: + ggml_cl_mv_q3_k_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ3_XXS: + ggml_cl_mv_iq3_xxs_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ4_XS: + ggml_cl_mv_iq4_xs_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ3_S: + ggml_cl_mv_iq3_s_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ1_M: + ggml_cl_mv_iq1_m_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ1_S: + ggml_cl_mv_iq1_s_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ2_S: + ggml_cl_mv_iq2_s_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ2_XS: + ggml_cl_mv_iq2_xs_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_IQ2_XXS: + ggml_cl_mv_iq2_xxs_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q4_K: + ggml_cl_mv_q4_k_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q5_K: + ggml_cl_mv_q5_k_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_Q6_K: + ggml_cl_mv_q6_k_f32(backend, src0, src1, dst); + return; + case GGML_TYPE_MXFP4: + ggml_cl_mv_mxfp4_f32(backend, src0, src1, dst); + return; + default: + GGML_ASSERT(false && "not implemented"); + } +} + +void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + const ggml_tensor * ids = dst->op == GGML_OP_MUL_MAT_ID ? dst->src[2] : nullptr; + if (ids) { + ggml_cl_mul_mat_id(backend, src0, src1, dst); + } else { + ggml_cl_mul_mat(backend, src0, src1, dst); + } + + const ggml_tensor * scale = ggml_get_src_scale(dst, 0); + if (!scale) { + return; + } + GGML_ASSERT(ggml_is_contiguous(dst) && dst->type == GGML_TYPE_F32 && scale->type == GGML_TYPE_F32); + + cl_ulong channel_stride = 0; + cl_ulong expert_stride = 0; + if (!ggml_is_scalar(scale)) { + if (ids && ggml_is_vector(scale) && scale->ne[0] == src0->ne[2]) { + expert_stride = scale->nb[0]; + } else { + channel_stride = scale->nb[0]; + expert_stride = ids ? scale->nb[1] : 0; + } + } + + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + auto * ed = (ggml_tensor_extra_cl *) dst->extra; + auto * es = (ggml_tensor_extra_cl *) scale->extra; + auto * ei = ids ? (ggml_tensor_extra_cl *) ids->extra : nullptr; + const cl_ulong offsetd = ed->offset + dst->view_offs; + const cl_ulong offsets = es->offset + scale->view_offs; + const cl_mem ids_buf = ids ? ei->data_device : nullptr; + const cl_ulong offseti = ids ? ei->offset + ids->view_offs : 0; + const cl_ulong ids_nb0 = ids ? ids->nb[0] : 0; + const cl_ulong ids_nb1 = ids ? ids->nb[1] : 0; + const cl_long n_expert = src0->ne[2]; + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + + cl_kernel kernel = backend_ctx->mul.kernel_mul_mat_scale; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &ed->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &es->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsets)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &channel_stride)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &expert_stride)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &ids_buf)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offseti)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &ids_nb0)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &ids_nb1)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &n_expert)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + + // few rows (decode): 1 element per work-item to keep enough work-items, else 8 + const size_t nth = 128; + const size_t nrows = (size_t) ne1*dst->ne[2]*dst->ne[3]; + const size_t elems_per_item = nrows < 32 ? 1 : 8; + const size_t nwg = CEIL_DIV((size_t) ne0, nth*elems_per_item); + size_t global_work_size[] = { nwg*nth, (size_t) ne1, (size_t) (dst->ne[2]*dst->ne[3]) }; + size_t local_work_size[] = { nth, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp b/ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp new file mode 100644 index 000000000000..653db979a04e --- /dev/null +++ b/ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp @@ -0,0 +1,10859 @@ +#include "../cl-common.h" +#include "../ops.h" + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static bool ggml_cl_coopk_dp4a_enabled(const ggml_backend_opencl_context * backend_ctx) { + static const char * const env = getenv("GGML_OPENCL_COOPK_DP4A"); + if (env && *env && atoi(env) == 0) { + return false; + } + if (!backend_ctx->has_integer_dot) { + return false; + } + if (backend_ctx->gpu_family == GPU_FAMILY::ADRENO) { + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::ADRENO_UNKNOWN || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X || + backend_ctx->adreno_gen == ADRENO_GPU_GEN::A7X) { + return false; + } + if (backend_ctx->adreno_cl_compiler_version.type == ADRENO_CL_COMPILER_TYPE::E17) { + return false; + } + } + return true; +} + +static bool ggml_cl_coopk_dp4a_narrow_on(const ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * op, int rows) { + if (!ggml_cl_coopk_dp4a_enabled(backend_ctx)) { + return false; + } + // Each lane handles rows output rows; subgroups split K for the same rows. + // Full row groups and 32-value K blocks avoid tail checks in the kernels. + return op->ne[1] >= 2 && op->ne[1] <= 4 + && rows > 0 && (op->src[0]->ne[1] % (64 * rows)) == 0 + && (op->src[0]->ne[0] % 32) == 0; +} + +// COOPK_NSG sizes the local reduction buffer, so a smaller workgroup requires a rebuild. +static cl_program ggml_cl_build_program_coopk(ggml_backend_opencl_context * backend_ctx, + const char * kernel_src, const char * kernel_name, + const std::string & opts_base, int & nsg, bool fatal = true) { + while (nsg >= 2) { + const std::string opts = opts_base + " -DCOOPK_NSG=" + std::to_string(nsg); + cl_program program = build_program_from_source(backend_ctx, kernel_src, opts, fatal); + if (program == nullptr) { + return nullptr; + } + cl_int err; + cl_kernel kernel = clCreateKernel(program, kernel_name, &err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + if (fatal) { + CL_CHECK(err); + } + return nullptr; + } + size_t max_workgroup_size = 0; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, + sizeof(max_workgroup_size), &max_workgroup_size, NULL)); + CL_CHECK(clReleaseKernel(kernel)); + if ((size_t) 64 * nsg <= max_workgroup_size) { + return program; + } + CL_CHECK(clReleaseProgram(program)); + nsg /= 2; + } + return nullptr; +} + +static void load_cl_kernel_coopk_q4_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a_bin_c8.cl"); +#endif + cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), + "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, + backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k_bin_c8, false); + if (program == nullptr) { + return; + } + + cl_int err; + + cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8", &err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + return; + } + + cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4", &err); + CL_CHECK(clReleaseProgram(program)); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseKernel(gemm)); + return; + } + + if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { + CL_CHECK(clReleaseKernel(gemm)); + CL_CHECK(clReleaseKernel(quant)); + return; + } + + backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 = gemm; + backend_ctx->mul_mat.kernel_quant_a_q8_1_k4 = quant; +} + +static void load_cl_kernel_coopk_q6_k_bin_c8(ggml_backend_opencl_context * backend_ctx) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a_bin_c8.cl"); +#endif + cl_program program = ggml_cl_build_program_coopk(backend_ctx, kernel_src.c_str(), + "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", backend_ctx->kernel_compile_opts, + backend_ctx->mul_mat.nsg_coopk_dp4a_q6_k_bin_c8, false); + if (program == nullptr) { + return; + } + + cl_int err; + + cl_kernel gemm = clCreateKernel(program, "kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8", &err); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseProgram(program)); + return; + } + + cl_kernel quant = clCreateKernel(program, "kernel_quant_a_q8_1_k4h", &err); + CL_CHECK(clReleaseProgram(program)); + if (err != CL_SUCCESS) { + CL_CHECK(clReleaseKernel(gemm)); + return; + } + + if (backend_ctx->get_kernel_workgroup_size(quant) < 64) { + CL_CHECK(clReleaseKernel(gemm)); + CL_CHECK(clReleaseKernel(quant)); + return; + } + + backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 = gemm; + backend_ctx->mul_mat.kernel_quant_a_q8_1_k4h = quant; +} + +static void ggml_cl_coopk_build_narrow(ggml_backend_opencl_context * backend_ctx, + const std::string & kernel_src, const char * kernel_name, + int rows, int & nsg, cl_kernel & kernel_c4, cl_kernel & kernel_c2) { + const std::string base_opts = backend_ctx->kernel_compile_opts + + " -DCOOPK_ROWS=" + std::to_string(rows); + for (int cols = 4; cols >= 2; cols -= 2) { + int nsg_eff = nsg; + cl_program program = ggml_cl_build_program_coopk( + backend_ctx, kernel_src.c_str(), kernel_name, + base_opts + " -DCOOPK_COLS=" + std::to_string(cols), nsg_eff); + if (program == nullptr) { + return; + } + cl_int err; + cl_kernel kernel = clCreateKernel(program, kernel_name, &err); + if (err != CL_SUCCESS) { kernel = nullptr; } + CL_CHECK(clReleaseProgram(program)); + if (cols == 4) { + kernel_c4 = kernel; + nsg = nsg_eff; + if (kernel == nullptr) { + return; + } + } else { + // Both widths share one stored subgroup count for launch. + if (kernel != nullptr && nsg_eff != nsg) { + CL_CHECK(clReleaseKernel(kernel)); + kernel = nullptr; + } + kernel_c2 = kernel; + } + } +} + +static void load_cl_kernels_gemm_coopk(ggml_backend_opencl_context * backend_ctx) { + if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO || !ggml_cl_coopk_dp4a_enabled(backend_ctx)) { + return; + } + + // Q4_0 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q4_0_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q4_0_q8_1_dp4a.cl"); +#endif + ggml_cl_coopk_build_narrow(backend_ctx, kernel_src, "kernel_gemm_coopk_q4_0_q8_1_dp4a", + backend_ctx->mul_mat.rows_coopk_dp4a_q4_0, backend_ctx->mul_mat.nsg_coopk_dp4a_q4_0, + backend_ctx->mul_mat.kernel_gemm_coopk_q4_0_q8_1_dp4a_c4, + backend_ctx->mul_mat.kernel_gemm_coopk_q4_0_q8_1_dp4a_c2); + GGML_LOG_CONT("."); + } + + // Q4_K + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q4_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q4_k_q8_1_dp4a.cl"); +#endif + ggml_cl_coopk_build_narrow(backend_ctx, kernel_src, "kernel_gemm_coopk_q4_k_q8_1_dp4a", + backend_ctx->mul_mat.rows_coopk_dp4a_q4_k, backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k, + backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_c4, + backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_c2); + + static const bool use_coopk_bin = [] { + const char * env = getenv("GGML_OPENCL_COOPK_Q4_K_BIN"); + return !env || !*env || atoi(env) != 0; + }(); + + if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { + const std::string base_opts = backend_ctx->kernel_compile_opts + + " -DCOOPK_Q_BIN=1 -DCOOPK_ROWS=" + std::to_string(backend_ctx->mul_mat.rows_coopk_dp4a_q4_k); + for (int cols = 4; cols >= 2; cols -= 2) { + int & nsg = (cols == 4) ? backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k_bin_c4 + : backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k_bin_c2; + int nsg_eff = nsg; + cl_program program = ggml_cl_build_program_coopk( + backend_ctx, kernel_src.c_str(), "kernel_gemm_coopk_q4_k_q8_1_dp4a", + base_opts + " -DCOOPK_COLS=" + std::to_string(cols), nsg_eff); + if (program == nullptr) { + continue; + } + cl_int err; + cl_kernel kernel = clCreateKernel(program, "kernel_gemm_coopk_q4_k_q8_1_dp4a", &err); + if (err != CL_SUCCESS) { kernel = nullptr; } + CL_CHECK(clReleaseProgram(program)); + if (cols == 4) { + backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 = kernel; + } else { + backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 = kernel; + } + nsg = nsg_eff; + } + load_cl_kernel_coopk_q4_k_bin_c8(backend_ctx); + } + GGML_LOG_CONT("."); + } + + // Q6_K + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_coopk_q6_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_coopk_q6_k_q8_1_dp4a.cl"); +#endif + ggml_cl_coopk_build_narrow(backend_ctx, kernel_src, "kernel_gemm_coopk_q6_k_q8_1_dp4a", + backend_ctx->mul_mat.rows_coopk_dp4a_q6_k, backend_ctx->mul_mat.nsg_coopk_dp4a_q6_k, + backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_c4, + backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_c2); + + static const bool use_coopk_bin = [] { + const char * env = getenv("GGML_OPENCL_COOPK_Q6_K_BIN"); + return !env || !*env || atoi(env) != 0; + }(); + + if (use_adreno_bin_kernels(backend_ctx) && use_coopk_bin) { + load_cl_kernel_coopk_q6_k_bin_c8(backend_ctx); + } + GGML_LOG_CONT("."); + } +} + +static void load_cl_kernels_coopmat(ggml_backend_opencl_context * backend_ctx) { + if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO || !strstr(backend_ctx->device_name.c_str(), "850")) { + return; + } + + cl_int err; + const std::string opts = "-cl-std=CL" + std::to_string(backend_ctx->opencl_c_version.major) + "." + + std::to_string(backend_ctx->opencl_c_version.minor) + + (backend_ctx->adreno_use_large_buffer ? " -qcom-enable-large-buffer" : ""); + + // pack_b_f16_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "pack_b_f16_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("pack_b_f16_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (!prog) { + return; + } + CL_CHECK((backend_ctx->mul_mat.kernel_pack_b_f16_coopmat = clCreateKernel(prog, "kernel_pack_b_f16_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q4_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q5_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q8_0_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q8_0_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q8_0_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q4_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q5_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_noshuffle_q6_k_f32_coopmat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q6_k_f32_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32_coopmat.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_coopmat = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_f32_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_moe_mxfp4_f32_ns_coopmat + // built only on A850 (see the check above), a failed build is not fatal. + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_mxfp4_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_mxfp4_f32_ns_coopmat.cl"); +#endif + // the router buffers are sub-buffers; read through texture promotion they give wrong values + std::string coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + // gemm_moe_q4_0_f32_ns_coopmat, same options as the mxfp4 one + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_0_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_0_f32_ns_coopmat.cl"); +#endif + std::string q4_0_coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q4_0_coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q4_0_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_moe_q4_1_f32_ns_coopmat, same options as the mxfp4 one + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_1_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_1_f32_ns_coopmat.cl"); +#endif + std::string q4_1_coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q4_1_coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q4_1_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_moe_q5_0_f32_ns_coopmat, same options as the mxfp4 one + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q5_0_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q5_0_f32_ns_coopmat.cl"); +#endif + std::string q5_0_coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q5_0_coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q5_0_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_moe_q5_1_f32_ns_coopmat, same options as the mxfp4 one + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q5_1_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q5_1_f32_ns_coopmat.cl"); +#endif + std::string q5_1_coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q5_1_coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q5_1_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_moe_q4_k_f32_ns_coopmat, same options as the mxfp4 one + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_k_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_k_f32_ns_coopmat.cl"); +#endif + std::string q4_k_coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q4_k_coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q4_k_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_moe_q5_k_f32_ns_coopmat, same options as the mxfp4 one + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q5_k_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q5_k_f32_ns_coopmat.cl"); +#endif + std::string q5_k_coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q5_k_coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q5_k_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + + // gemm_moe_q6_k_f32_ns_coopmat, same options as the mxfp4 one + backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_coopmat = nullptr; + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q6_k_f32_ns_coopmat.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q6_k_f32_ns_coopmat.cl"); +#endif + std::string q6_k_coopmat_opts = + " -cl-std=CL3.0 " + " -qcom-ray-tracing-kernel " + " -qcom-disable-promote-pointer-to-texture "; + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), q6_k_coopmat_opts, false); + if (prog) { + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_coopmat = clCreateKernel(prog, "kernel_gemm_moe_q6_k_f32_ns_coopmat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } +} +#endif + +void ggml_cl_load_kernels_mul_mat_adreno(ggml_backend_opencl_context * backend_ctx) { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + const auto opencl_c_std = + std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + + std::to_string(backend_ctx->opencl_c_version.minor); + + // transpose + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "transpose.cl.h" + }; +#else + const std::string kernel_src = read_file("transpose.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_transpose_32_16 = clCreateKernel(prog, "kernel_transpose_32_16", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_transpose_32 = clCreateKernel(prog, "kernel_transpose_32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_transpose_16 = clCreateKernel(prog, "kernel_transpose_16", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_transpose_8_buf = clCreateKernel(prog, "kernel_transpose_8_buf", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_transpose_16_buf = clCreateKernel(prog, "kernel_transpose_16_buf", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_transpose_32_buf = clCreateKernel(prog, "kernel_transpose_32_buf", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_transpose_16_4x1 = clCreateKernel(prog, "kernel_transpose_16_4x1", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q1_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q1_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q1_0_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q1_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q1_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q1_0_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src_CL_gemv_general { + #include "gemv_noshuffle_q1_0_f32.cl.h" + }; +#else + const std::string kernel_src_CL_gemv_general = read_file("gemv_noshuffle_q1_0_f32.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q1_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q1_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + + const char * nsg1_min_m_env = getenv("GGML_OPENCL_Q1_0_GEMV_NSG1_MIN_M"); + backend_ctx->min_m_gemv_nsg1_q1_0 = nsg1_min_m_env ? atoi(nsg1_min_m_env) : + (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 8192 : 0); + if (backend_ctx->min_m_gemv_nsg1_q1_0 > 0) { + const std::string nsg1_opts = CL_gemv_compile_opts + " -DN_SIMDGROUP=1"; + cl_program prog_nsg1 = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), nsg1_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q1_0_f32_nsg1 = clCreateKernel(prog_nsg1, "kernel_gemv_noshuffle_q1_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog_nsg1)); + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q2_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q2_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q2_k_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_k_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q2_k_q8_1_dp4a + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q2_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q2_k_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_k_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_k_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_k_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q3_k_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q3_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q3_k_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q3_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q3_k_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q3_k_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_q3_k_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string iq2_s_grid_src { + #include "iq2_s_grid.cl.h" + }; + const std::string iq2_xs_grid_src { + #include "iq2_xs_grid.cl.h" + }; + const std::string iq2_xxs_grid_src { + #include "iq2_xxs_grid.cl.h" + }; + const std::string iq1_s_grid_src { + #include "iq1_s_grid.cl.h" + }; + const std::string iq3_s_grid_src { + #include "iq3_s_grid.cl.h" + }; + const std::string iq3_xxs_grid_src { + #include "iq3_xxs_grid.cl.h" + }; + const std::string iq4_xs_grid_src { + #include "iq4_xs_grid.cl.h" + }; +#else + const std::string iq2_s_grid_src = read_file("iq2_s_grid.cl"); + const std::string iq2_xs_grid_src = read_file("iq2_xs_grid.cl"); + const std::string iq2_xxs_grid_src = read_file("iq2_xxs_grid.cl"); + const std::string iq1_s_grid_src = read_file("iq1_s_grid.cl"); + const std::string iq3_s_grid_src = read_file("iq3_s_grid.cl"); + const std::string iq3_xxs_grid_src = read_file("iq3_xxs_grid.cl"); + const std::string iq4_xs_grid_src = read_file("iq4_xs_grid.cl"); +#endif + + // gemm_noshuffle_q2_0_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q2_0_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q2_0_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_0_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_0_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_0_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q2_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q2_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q2_0_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q2_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q2_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q2_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q2_0_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_Q2_0_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8 || nsg == 16 || nsg == 32) { + backend_ctx->mul_mat.q2_0_mv_nsg = nsg; + } + } + for (int wide = 0; wide < 2; ++wide) { + const std::string opts = compile_opts + " -DQ2_0_MV_WIDE=" + std::to_string(wide); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_q2_0_f32", &err); + CL_CHECK(err); + CL_CHECK(clReleaseProgram(prog)); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + size_t workgroup = 512; + while (workgroup > max_workgroup) { + workgroup /= 2; + } + GGML_ASSERT(workgroup >= 64); + if (wide) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_q2_0_f32_wide = kernel; + backend_ctx->mul_mat.q2_0_mv_workgroup_size_wide = workgroup; + } else { + backend_ctx->mul_mat.kernel_gemv_noshuffle_q2_0_f32 = kernel; + backend_ctx->mul_mat.q2_0_mv_workgroup_size = workgroup; + } + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq2_s_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq2_s_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq2_s_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_s_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_s_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_s_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_s_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq2_xs_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq2_xs_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq2_xs_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq2_xxs_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq2_xxs_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq2_xxs_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq2_xxs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq2_xxs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq2_xxs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xxs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xxs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq2_xxs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq2_xxs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq2_xxs_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ2_XXS_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq2_xxs_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ2_XXS_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq2_xxs_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq2_xxs_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq2_xxs_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq2_xxs_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq2_xxs_f32 = kernel; + cl_kernel export_grid = clCreateKernel(prog, "kernel_iq2_xxs_grid_export", &err); + CL_CHECK(err); + backend_ctx->iq2_xxs_grid_buffer.allocate(backend_ctx->context, 512*sizeof(cl_uint)); + CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq2_xxs_grid_buffer.buffer)); + size_t global[] = { 512 }; + size_t local[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseKernel(export_grid)); + CL_CHECK(clReleaseProgram(prog)); + + cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = 512; + desc.buffer = backend_ctx->iq2_xxs_grid_buffer.buffer; + backend_ctx->iq2_xxs_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + CL_CHECK(err); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq2_xxs_mv_nsg > 1); + backend_ctx->mul_mat.iq2_xxs_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq2_xs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq2_xs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq2_xs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_xs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq2_xs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq2_xs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq2_xs_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ2_XS_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq2_xs_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ2_XS_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq2_xs_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq2_xs_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq2_xs_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq2_xs_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq2_xs_f32 = kernel; + cl_kernel export_grid = clCreateKernel(prog, "kernel_iq2_xs_grid_export", &err); + CL_CHECK(err); + backend_ctx->iq2_xs_grid_buffer.allocate(backend_ctx->context, 1024*sizeof(cl_uint)); + CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq2_xs_grid_buffer.buffer)); + size_t global[] = { 1024 }; + size_t local[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseKernel(export_grid)); + CL_CHECK(clReleaseProgram(prog)); + + cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = 1024; + desc.buffer = backend_ctx->iq2_xs_grid_buffer.buffer; + backend_ctx->iq2_xs_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + CL_CHECK(err); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq2_xs_mv_nsg > 1); + backend_ctx->mul_mat.iq2_xs_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq2_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq2_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq2_s_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_s_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq2_s_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq2_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq2_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq2_s_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ2_S_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq2_s_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ2_S_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq2_s_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq2_s_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq2_s_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq2_s_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq2_s_f32 = kernel; + cl_kernel export_grid = clCreateKernel(prog, "kernel_iq2_s_grid_export", &err); + CL_CHECK(err); + backend_ctx->iq2_s_grid_buffer.allocate(backend_ctx->context, 2048*sizeof(cl_uint)); + CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq2_s_grid_buffer.buffer)); + size_t global[] = { 2048 }; + size_t local[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseKernel(export_grid)); + CL_CHECK(clReleaseProgram(prog)); + + cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = 2048; + desc.buffer = backend_ctx->iq2_s_grid_buffer.buffer; + backend_ctx->iq2_s_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + CL_CHECK(err); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq2_s_mv_nsg > 1); + backend_ctx->mul_mat.iq2_s_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq1_s_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq1_s_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq1_s_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_s_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_s_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_s_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_s_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq1_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq1_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq1_s_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_s_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_s_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq1_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq1_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq1_s_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ1_S_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq1_s_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ1_S_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq1_s_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq1_s_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq1_s_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq1_s_f32 = kernel; + cl_kernel export_grid = clCreateKernel(prog, "kernel_iq1_s_grid_export", &err); + CL_CHECK(err); + backend_ctx->iq1_s_grid_buffer.allocate(backend_ctx->context, 2048*sizeof(cl_uint)); + CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq1_s_grid_buffer.buffer)); + size_t global[] = { 2048 }; + size_t local[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseKernel(export_grid)); + CL_CHECK(clReleaseProgram(prog)); + + cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = 2048; + desc.buffer = backend_ctx->iq1_s_grid_buffer.buffer; + backend_ctx->iq1_s_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + CL_CHECK(err); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq1_s_mv_nsg > 1); + backend_ctx->mul_mat.iq1_s_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq1_m_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq1_m_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq1_m_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_m_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_m_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_m_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_m_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq1_m_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq1_m_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq1_m_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_m_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq1_m_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq1_m_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq1_m_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq1_m_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ1_M_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq1_m_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ1_M_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq1_m_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq1_s_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq1_m_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq1_m_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq1_m_f32 = kernel; + CL_CHECK(clReleaseProgram(prog)); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq1_m_mv_nsg > 1); + backend_ctx->mul_mat.iq1_m_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq3_s_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq3_s_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq3_s_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_s_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_s_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_s_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_s_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq3_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq3_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq3_s_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_s_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_s_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq3_s_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq3_s_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq3_s_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ3_S_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq3_s_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ3_S_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq3_s_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq3_s_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq3_s_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq3_s_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq3_s_f32 = kernel; + cl_kernel export_grid = clCreateKernel(prog, "kernel_iq3_s_grid_export", &err); + CL_CHECK(err); + backend_ctx->iq3_s_grid_buffer.allocate(backend_ctx->context, 512*sizeof(cl_uint)); + CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq3_s_grid_buffer.buffer)); + size_t global[] = { 512 }; + size_t local[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseKernel(export_grid)); + CL_CHECK(clReleaseProgram(prog)); + + cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = 512; + desc.buffer = backend_ctx->iq3_s_grid_buffer.buffer; + backend_ctx->iq3_s_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + CL_CHECK(err); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq3_s_mv_nsg > 1); + backend_ctx->mul_mat.iq3_s_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq3_xxs_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq3_xxs_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq3_xxs_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq3_xxs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq3_xxs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq3_xxs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_xxs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq3_xxs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq3_xxs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq3_xxs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq3_xxs_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ3_XXS_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq3_xxs_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ3_XXS_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq3_xxs_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq3_xxs_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq3_xxs_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq3_xxs_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq3_xxs_f32 = kernel; + cl_kernel export_grid = clCreateKernel(prog, "kernel_iq3_xxs_grid_export", &err); + CL_CHECK(err); + backend_ctx->iq3_xxs_grid_buffer.allocate(backend_ctx->context, 256*sizeof(cl_uint)); + CL_CHECK(clSetKernelArg(export_grid, 0, sizeof(cl_mem), &backend_ctx->iq3_xxs_grid_buffer.buffer)); + size_t global[] = { 256 }; + size_t local[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(backend_ctx->queue, export_grid, 1, nullptr, global, local, 0, nullptr, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseKernel(export_grid)); + CL_CHECK(clReleaseProgram(prog)); + + cl_image_format format = { CL_R, CL_UNSIGNED_INT32 }; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = 256; + desc.buffer = backend_ctx->iq3_xxs_grid_buffer.buffer; + backend_ctx->iq3_xxs_grid_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + CL_CHECK(err); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq3_xxs_mv_nsg > 1); + backend_ctx->mul_mat.iq3_xxs_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq4_xs_q8_1_dp4a + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq4_xs_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq4_xs_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts + " -DTILESIZE_N=8"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a_narrow = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq4_xs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq4_xs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq4_xs_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_xs_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_xs_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq4_xs_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq4_xs_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq4_xs_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_IQ4_XS_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.iq4_xs_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DIQ4_XS_MV_NSG=" + std::to_string(backend_ctx->mul_mat.iq4_xs_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, (iq4_xs_grid_src + kernel_src).c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_iq4_xs_f32", &err); + CL_CHECK(err); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.iq4_xs_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_iq4_xs_f32 = kernel; + CL_CHECK(clReleaseProgram(prog)); + break; + } + CL_CHECK(clReleaseKernel(kernel)); + CL_CHECK(clReleaseProgram(prog)); + GGML_ASSERT(backend_ctx->mul_mat.iq4_xs_mv_nsg > 1); + backend_ctx->mul_mat.iq4_xs_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q3_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q3_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q3_k_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q3_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q3_k_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q3_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q3_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q3_k_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_Q3_K_MV_R")) { + const int rows = atoi(env); + if (rows == 1 || rows == 2 || rows == 4) { + backend_ctx->mul_mat.q3_k_mv_rows = rows; + } + } + if (const char * env = getenv("GGML_OPENCL_Q3_K_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.q3_k_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DQ3_K_MV_R=" + std::to_string(backend_ctx->mul_mat.q3_k_mv_rows) + + " -DQ3_K_MV_NSG=" + std::to_string(backend_ctx->mul_mat.q3_k_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_q3_k_f32", &err); + CL_CHECK(err); + CL_CHECK(clReleaseProgram(prog)); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.q3_k_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_q3_k_f32 = kernel; + break; + } + CL_CHECK(clReleaseKernel(kernel)); + GGML_ASSERT(backend_ctx->mul_mat.q3_k_mv_nsg > 1); + backend_ctx->mul_mat.q3_k_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q2_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q2_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q2_k_f32.cl"); +#endif + if (const char * env = getenv("GGML_OPENCL_Q2_K_MV_R")) { + const int rows = atoi(env); + if (rows == 1 || rows == 2 || rows == 4) { + backend_ctx->mul_mat.q2_k_mv_rows = rows; + } + } + if (const char * env = getenv("GGML_OPENCL_Q2_K_MV_NSG")) { + const int nsg = atoi(env); + if (nsg == 1 || nsg == 2 || nsg == 4 || nsg == 8) { + backend_ctx->mul_mat.q2_k_mv_nsg = nsg; + } + } + for (;;) { + const std::string opts = compile_opts + " -DQ2_K_MV_R=" + std::to_string(backend_ctx->mul_mat.q2_k_mv_rows) + + " -DQ2_K_MV_NSG=" + std::to_string(backend_ctx->mul_mat.q2_k_mv_nsg); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + cl_kernel kernel = clCreateKernel(prog, "kernel_gemv_noshuffle_q2_k_f32", &err); + CL_CHECK(err); + CL_CHECK(clReleaseProgram(prog)); + size_t max_workgroup; + CL_CHECK(clGetKernelWorkGroupInfo(kernel, backend_ctx->device, CL_KERNEL_WORK_GROUP_SIZE, sizeof(max_workgroup), &max_workgroup, nullptr)); + if (64*(size_t)backend_ctx->mul_mat.q2_k_mv_nsg <= max_workgroup) { + backend_ctx->mul_mat.kernel_gemv_noshuffle_q2_k_f32 = kernel; + break; + } + CL_CHECK(clReleaseKernel(kernel)); + GGML_ASSERT(backend_ctx->mul_mat.q2_k_mv_nsg > 1); + backend_ctx->mul_mat.q2_k_mv_nsg /= 2; + } + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_general + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X) { + CL_gemv_compile_opts += " -DGGML_CL_A6X_CONSTFOLD_FIX"; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src_CL_gemv_general { + #include "gemv_noshuffle_q4_0_f32.cl.h" + }; +#else + const std::string kernel_src_CL_gemv_general = read_file("gemv_noshuffle_q4_0_f32.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32_mc3", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle + { + // Gemv 2048, 16384 + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DLINE_STRIDE_A=2048 " + " -DBLOCK_STRIDE_A=16384 " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src_CL_gemv { + #include "gemv_noshuffle_q4_0_f32_spec.cl.h" + }; +#else + const std::string kernel_src_CL_gemv = read_file("gemv_noshuffle_q4_0_f32_spec.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_4096_1_4096 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + + // Gemv 2048, 16384 + CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DLINE_STRIDE_A=2048 " + " -DBLOCK_STRIDE_A=16384 " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + + prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_4096_1_11008 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + + // Gemv 5504, 44032 + CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DLINE_STRIDE_A=5504 " + " -DBLOCK_STRIDE_A=44032 " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + + prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_11008_1_4096 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + + // Gemv 16000, 128000 + CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DLINE_STRIDE_A=16000 " + " -DBLOCK_STRIDE_A=128000 " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); + + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + + prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv.c_str(), CL_gemv_compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_32000_1_4096 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mat_Ab_Bi_8x4 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src_CL_gemm { + #include "gemm_noshuffle_q4_0_f32.cl.h" + }; +#else + const std::string kernel_src_CL_gemm = read_file("gemm_noshuffle_q4_0_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemm.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_32b_trans = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin = nullptr; + { + { + std::string opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q4_0_f32_32b_trans.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q4_0_f32_32b_trans.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_32b_trans = + clCreateKernel(prog, "kernel_gemv_noshuffle_q4_0_f32_32b_trans", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + if (use_adreno_bin_kernels(backend_ctx)) { + size_t bin_size = 0; + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_0_f32_32b_trans_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_0_f32_32b_trans_ila_a7", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_noshuffle_q4_1_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_1_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_1_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_1_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_1_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q4_1_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q4_1_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q4_1_f32.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_1_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_1_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_1_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_1_f32_mc3", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q5_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_0_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q5_0_q8_1_dp4a (dp4a dense q5_0 prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_0_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_0_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_q8_1_dp4a", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q5_0_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q5_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q5_0_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q5_1_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_1_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_1_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_1_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_1_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q5_1_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q5_1_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q5_1_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_1_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_1_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq4_nl_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq4_nl_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq4_nl_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_nl_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_nl_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_iq4_nl_q8_1_dp4a (dp4a dense IQ4_NL prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_iq4_nl_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_iq4_nl_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q4_0_q8_1_dp4a (dp4a dense q4_0 prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_0_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_0_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_q8_1_dp4a", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_iq4_nl_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_iq4_nl_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_iq4_nl_f32.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_iq4_nl_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_iq4_nl_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_q8_0_f32_8x4 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q8_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q8_0_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q8_0_f32_bin + { + size_t bin_size = 0; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q8_0_f32_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_bin = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_f32_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q8_0_f32_32b_trans_ila_a7", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + } + } + + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemv_noshuffle_general_q8_0_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src_CL_gemv_general { + #include "gemv_noshuffle_q8_0_f32.cl.h" + }; +#else + const std::string kernel_src_CL_gemv_general = read_file("gemv_noshuffle_q8_0_f32.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src_CL_gemv_general.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q8_0_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q8_0_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q8_0_f32_splitk = clCreateKernel(prog, "kernel_gemv_noshuffle_q8_0_f32_splitk", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q8_0_f32_mc = clCreateKernel(prog, "kernel_gemv_noshuffle_q8_0_f32_mc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q4_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_k_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_r1 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_r1", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_kimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_kimg", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_cok = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_f32_cok", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q4_k_q8_1_dp4a (dp4a dense prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_k_q8_1_dp4a.cl"); +#endif + // X1 uses a smaller N tile to reduce local memory and register use. + int tile_n = (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E) ? 8 : 32; + if (const char * e = getenv("GGML_OPENCL_Q4K_DP4A_TS")) { tile_n = atoi(e); } + GGML_ASSERT(tile_n >= 4 && tile_n <= 64 && tile_n % 4 == 0); + backend_ctx->tile_n_dp4a_q4_k = tile_n; + std::string dp4a_opts = compile_opts + " -DTILESIZE_N=" + std::to_string(tile_n); + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), dp4a_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + + // Compile a smaller N tile to avoid unused columns in small batches. + int tile_n_narrow = MIN(tile_n, 16); + if (const char * e = getenv("GGML_OPENCL_Q4_K_DP4A_TS_NARROW")) { tile_n_narrow = atoi(e); } + GGML_ASSERT(tile_n_narrow >= 4 && tile_n_narrow <= 64 && tile_n_narrow % 4 == 0); + if (const char * e = getenv("GGML_OPENCL_Q4_K_DP4A_NARROW_MAX")) { + backend_ctx->max_n_dp4a_narrow_q4_k = atoi(e); + } + backend_ctx->tile_n_dp4a_narrow_q4_k = tile_n_narrow; + if (tile_n_narrow != tile_n) { + std::string narrow_opts = compile_opts + " -DTILESIZE_N=" + std::to_string(tile_n_narrow); + cl_program narrow_prog = build_program_from_source(backend_ctx, kernel_src.c_str(), narrow_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow = clCreateKernel(narrow_prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow_wimg = clCreateKernel(narrow_prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg", &err), err)); + CL_CHECK(clReleaseProgram(narrow_prog)); + } + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q8_0_q8_1_dp4a (dp4a dense q8_0 prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q8_0_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q8_0_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q5_k_q8_1_dp4a (dp4a dense prefill GEMM for q5_K) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_k_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_q8_1_dp4a", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q6_k_q8_1_dp4a (dp4a dense prefill GEMM for q6_K ffn_down/output) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q6_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q6_k_q8_1_dp4a.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_q8_1_dp4a", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4 = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // quant_a_q8_1 (plain activation q8_1 pre-pass for the dense dp4a GEMM) + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "quant_a_q8_1.cl.h" + }; +#else + const std::string kernel_src = read_file("quant_a_q8_1.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_quant_a_q8_1 = clCreateKernel(prog, "kernel_quant_a_q8_1", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q4_k_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + if (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A6X) { + CL_gemv_compile_opts += " -DGGML_CL_A6X_CONSTFOLD_FIX"; + } + // dequant-once-per-block mc3 verify GEMV + if (getenv("GGML_OPENCL_Q4_K_MC3_DQ")) { + CL_gemv_compile_opts += " -DQ4K_MC3_DEQUANT_ONCE "; + } + // LM-staged dequant mc3 verify GEMV, stages the dequantized + // q4_K weights in __local instead of regs + if (getenv("GGML_OPENCL_Q4_K_MC3_LDS")) { + CL_gemv_compile_opts += " -DQ4K_MC3_DEQUANT_LDS "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q4_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_mc3", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_splitk = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_splitk", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_splitk_reduce_f32 = clCreateKernel(prog, "kernel_gemv_splitk_reduce_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_glu = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_glu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q4_K_f32_tiled_dp4a + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q4_K_f32_tiled_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q4_K_f32_tiled_dp4a.cl"); +#endif + std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a = + clCreateKernel(prog, "kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_32b_trans = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin = nullptr; + { + if (backend_ctx->has_vector_subgroup_broadcast) { + std::string opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q4_k_f32_32b_trans.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32_32b_trans.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_32b_trans = + clCreateKernel(prog, "gemv_noshuffle_q4_k_f32_32b_trans", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + if (use_adreno_bin_kernels(backend_ctx)) { + size_t bin_size = 0; + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_k_f32_32b_trans_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_k_f32_32b_trans_ila_a7", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + } + } + + std::string CL_moe_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -cl-fast-relaxed-math"; + + // gemv_noshuffle_q4_k_f32_o4 - 4-output-per-WI variant for the long-vocab + // q4_K lm_head/embed GEMV (shares one activation read across 4 output rows). + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q4_k_f32_o4.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32_o4.cl"); +#endif + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + cl_program prog = build_program_from_source( + backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_o4 = clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_o4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q4_k_f32_tiled - tiled-wide canonical layout, default ON + // (opt out: GGML_OPENCL_Q4K_GEMV_TILED=0; separate convert + GEMV; weights via __global). + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q4_k_f32_tiled.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q4_k_f32_tiled.cl"); +#endif + std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_tiled = + clCreateKernel(prog, "kernel_gemv_noshuffle_q4_k_f32_tiled", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_moe_q4_1_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_q4_1_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_q4_1_f32_ns.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q4_1_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q4_1_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q4_1_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_1_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_1_f32_ns.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q4_1_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q4_1_f32_ns_bin + { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_1_f32_ns_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_1_f32_ns_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemv_moe_mxfp4_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_mxfp4_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_mxfp4_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_mxfp4_f32 = clCreateKernel(prog, "kernel_gemv_moe_mxfp4_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_mxfp4_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_mxfp4_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_mxfp4_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32 = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_moe_q4_0_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_q4_0_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_q4_0_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q4_0_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q4_0_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q4_0_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_0_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_0_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q4_0_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q4_0_f32_ns_bin + { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_f32_ns_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_f32_ns_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q8_0_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q8_0_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q8_0_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q8_0_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q8_0_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_moe_q5_0_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_q5_0_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_q5_0_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q5_0_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q5_0_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q5_0_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q5_0_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q5_0_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q5_0_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_moe_q5_1_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_q5_1_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_q5_1_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q5_1_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q5_1_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q5_1_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q5_1_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q5_1_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q5_1_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_moe_q4_k_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_q4_k_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_q4_k_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q4_k_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q4_k_f32_ns", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q4_k_f32_ns_wimg = clCreateKernel(prog, "kernel_gemv_moe_q4_k_f32_ns_wimg", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q4_k_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_k_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_k_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q4_k_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q4_k_f32_ns_bin + { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_f32_ns_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_f32_ns_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q4_k_q8_1_dp4a (dp4a prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_k_q8_1_dp4a.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q4_k_q8_1_dp4a_bin (dp4a prefill GEMM) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_q8_1_dp4a_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_mxfp4_q8_1_dp4a (dp4a prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_mxfp4_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_mxfp4_q8_1_dp4a.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *) backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_mxfp4_q8_1_dp4a_ldck_bin (dp4a prefill GEMM) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila_ldck", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila_ldck", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_mxfp4_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q4_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q4_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_1_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_1_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q5_0_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_0_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_0_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q5_1_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_1_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_1_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q4_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_k_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_k_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q5_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q5_k_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q5_k_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q6_k_q8_1_dp4a_malu_bin (malu int8 prefill GEMM, A850) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_q8_1_dp4a_ila_malu", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a_ila_malu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q4_0_q8_1_dp4a (dp4a prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q4_0_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q4_0_q8_1_dp4a.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *) backend_ctx->get_adreno_bin_kernel("gemm_moe_q4_0_q8_1_dp4a_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_q4_0_q8_1_dp4a_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q8_1_dp4a (generic dp4a MoE GEMM; MOE_QT=80 -> q8_0 expert variant) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q8_1_dp4a.cl"); +#endif + const std::string opts80 = CL_moe_compile_opts + " -DMOE_QT=80"; + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), opts80.c_str()); + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q80 = clCreateKernel(prog, "kernel_gemm_moe_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + + const std::string opts50 = CL_moe_compile_opts + " -DMOE_QT=50"; + cl_program prog50 = + build_program_from_source(backend_ctx, kernel_src.c_str(), opts50.c_str()); + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q50 = clCreateKernel(prog50, "kernel_gemm_moe_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog50)); + + const std::string opts5 = CL_moe_compile_opts + " -DMOE_QT=5"; + cl_program prog5 = + build_program_from_source(backend_ctx, kernel_src.c_str(), opts5.c_str()); + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q5k = clCreateKernel(prog5, "kernel_gemm_moe_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog5)); + GGML_LOG_CONT("."); + } + + // moe_reorder_quant_a_q8_1 (fused reorder + q8_1 quant) + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "moe_reorder_quant_a_q8_1.cl.h" + }; +#else + const std::string kernel_src = read_file("moe_reorder_quant_a_q8_1.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1 = clCreateKernel(prog, "kernel_moe_reorder_quant_a_q8_1", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // transpose_activation_q8 (per-tile transpose of q8_1 activations for the ldck dp4a GEMM) + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "transpose_activation_q8.cl.h" + }; +#else + const std::string kernel_src = read_file("transpose_activation_q8.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_transpose_activation_q8 = clCreateKernel(prog, "kernel_transpose_activation_q8", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_moe_q5_k_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_q5_k_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_q5_k_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q5_k_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q5_k_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q5_k_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q5_k_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q5_k_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q5_k_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_moe_q6_k_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_q6_k_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_q6_k_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_q6_k_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_q6_k_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q6_k_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q6_k_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q6_k_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_q6_k_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q6_k_f32_ns_bin + { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_f32_ns_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_f32_ns_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemm_moe_q6_k_q8_1_dp4a (dp4a q6_K MoE prefill GEMM) + if (backend_ctx->has_integer_dot) { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_q6_k_q8_1_dp4a.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_q6_k_q8_1_dp4a.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_q6_k_q8_1_dp4a_bin (dp4a prefill GEMM) + if (backend_ctx->has_integer_dot) { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_q6_k_q8_1_dp4a_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_bin = clCreateKernel(prog, "kernel_gemm_moe_q6_k_q8_1_dp4a_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemv_moe_mxfp4_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_moe_mxfp4_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_moe_mxfp4_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_mxfp4_f32_ns = clCreateKernel(prog, "kernel_gemv_moe_mxfp4_f32_ns", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemv_moe_mxfp4_f32_ns_wimg = clCreateKernel(prog, "kernel_gemv_moe_mxfp4_f32_ns_wimg", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_mxfp4_f32_ns + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_moe_mxfp4_f32_ns.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_moe_mxfp4_f32_ns.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_f32_ns", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_moe_mxfp4_f32_ns_bin + { + size_t bin_size = 0; + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_bin = nullptr; + + if (use_adreno_bin_kernels(backend_ctx)) { + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_moe_mxfp4_f32_ns_ila", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, CL_moe_compile_opts, bin_size); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_bin = clCreateKernel(prog, "kernel_gemm_moe_mxfp4_f32_ns_ila", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + } + } + + // moe_reorder_b + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "moe_reorder_b.cl.h" + }; +#else + const std::string kernel_src = read_file("moe_reorder_b.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_reorder_b = clCreateKernel(prog, "kernel_moe_reorder_b", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_reorder_b_f16 = clCreateKernel(prog, "kernel_moe_reorder_b_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_k_f32_32b_trans = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin = nullptr; + { + if (backend_ctx->has_vector_subgroup_broadcast) { + std::string opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q6_k_f32_32b_trans.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32_32b_trans.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_k_f32_32b_trans = + clCreateKernel(prog, "kernel_gemv_noshuffle_q6_k_f32_32b_trans", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + if (use_adreno_bin_kernels(backend_ctx)) { + size_t bin_size = 0; + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q6_k_f32_32b_trans_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q6_k_f32_32b_trans_ila_a7", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + } + } + + backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32_32b_trans = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin = nullptr; + backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin = nullptr; + { + if (backend_ctx->has_vector_subgroup_broadcast) { + std::string opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable " + " -DSIMDGROUP_WIDTH=" + + std::to_string(backend_ctx->adreno_wave_size); +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q5_k_f32_32b_trans.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q5_k_f32_32b_trans.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32_32b_trans = + clCreateKernel(prog, "gemv_noshuffle_q5_k_f32_32b_trans", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + if (use_adreno_bin_kernels(backend_ctx)) { + size_t bin_size = 0; + const char * kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q5_k_f32_32b_trans_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q5_k_f32_32b_trans_ila_a7", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + + kernel_bin = (const char *)backend_ctx->get_adreno_bin_kernel("gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8", &bin_size); + if (kernel_bin && bin_size > 0) { + cl_program bin_prog = + build_program_from_binary(backend_ctx->context, backend_ctx->device, kernel_bin, "", bin_size); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin = + clCreateKernel(bin_prog, "kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8", &err), err)); + CL_CHECK(clReleaseProgram(bin_prog)); + GGML_LOG_CONT("."); + } + } + } + + // gemv_noshuffle_q6_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q6_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32.cl"); +#endif + + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; + } + + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_mc3", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q6_k_f32_o4 - 4-output-per-WI variant, opt-in via + // GGML_OPENCL_Q6K_GEMV_O4=1 (~3x fewer dispatches on long-vocab lm_head). + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q6_k_f32_o4.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32_o4.cl"); +#endif + + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAT "; + } + + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_o4 = clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_o4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + + // Global-read variant: weights read from __global coalesced instead of + // image1d_buffer (the texture cache caps the streaming lm_head read + // bandwidth). Opt-in via GGML_OPENCL_Q6K_GEMV_O4_GLOBAL. + cl_program prog_g = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts + " -DQ6K_O4_GLOBAL"); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_o4_global = + clCreateKernel(prog_g, "kernel_gemv_noshuffle_q6_K_f32_o4_global", &err), err)); + CL_CHECK(clReleaseProgram(prog_g)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q6_k_f32_tiled - tiled-wide canonical layout, default ON + // (opt out: GGML_OPENCL_Q6K_GEMV_TILED=0; separate convert + GEMV; weights via __global). + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q6_k_f32_tiled.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q6_k_f32_tiled.cl"); +#endif + std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_tiled = + clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_tiled", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_tiled_mc3 = + clCreateKernel(prog, "kernel_gemv_noshuffle_q6_K_f32_tiled_mc3", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q6_k_f32_tiled - batched (N>1) GEMM over the same tiled-wide + // canonical layout, so batched lm_head/embed stays correct + on GPU. + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q6_k_f32_tiled.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32_tiled.cl"); +#endif + std::string compile_opts = std::string("-cl-std=") + opencl_c_std + " -cl-mad-enable "; + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_K_f32_tiled = + clCreateKernel(prog, "kernel_gemm_noshuffle_q6_K_f32_tiled", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q6_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q6_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q6_k_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), CL_moe_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_K_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_K_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_K_f32_cok = clCreateKernel(prog, "kernel_gemm_noshuffle_q6_K_f32_cok", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemv_noshuffle_q5_k_f32 + { + std::string CL_gemv_compile_opts = std::string("-cl-std=") + opencl_c_std + + " -cl-mad-enable "; + if (backend_ctx->has_vector_subgroup_broadcast) { + CL_gemv_compile_opts += " -DVECTOR_SUB_GROUP_BROADCAST "; + } + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemv_noshuffle_q5_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemv_noshuffle_q5_k_f32.cl"); +#endif + + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), CL_gemv_compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_k_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32_mc3 = clCreateKernel(prog, "kernel_gemv_noshuffle_q5_k_f32_mc3", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_noshuffle_q5_k_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_noshuffle_q5_k_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_noshuffle_q5_k_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32 = clCreateKernel(prog, "kernel_gemm_noshuffle_q5_k_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // gemm_xmem_f16_f32_os8 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "gemm_xmem_f16_f32_os8.cl.h" + }; +#else + const std::string kernel_src = read_file("gemm_xmem_f16_f32_os8.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_adreno_xmem_pack_src_f32 = + clCreateKernel(prog, "adreno_xmem_pack_src_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_adreno_xmem_prepack_weight_f16 = + clCreateKernel(prog, "adreno_xmem_prepack_weight_f16", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_gemm_xmem_f16_f32_os8 = + clCreateKernel(prog, "kernel_gemm_xmem_f16_f32_os8", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_adreno_xmem_store_dst_f32 = + clCreateKernel(prog, "adreno_xmem_store_dst_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_f16_f32_attn_adreno + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_f16_f32_attn_adreno.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_f16_f32_attn_adreno.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + cl_int err_x8gi = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4_img = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_x8_gqa4_img", &err_x8gi); + if (err_x8gi != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4_img = nullptr; } + + cl_int err_x8gi_r4 = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img", &err_x8gi_r4); + if (err_x8gi_r4 != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img = nullptr; } + + cl_int err_r2dk256 = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img", &err_r2dk256); + if (err_r2dk256 != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img = nullptr; } + + cl_int err_y8gi = CL_SUCCESS; + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa_img = + clCreateKernel(prog, "kernel_mul_mat_f16_f32_l4_y8_gqa_img", &err_y8gi); + if (err_y8gi != CL_SUCCESS) { backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa_img = nullptr; } + + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_f16_f32_kq_kqv + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_f16_f32_kq_kqv.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_f16_f32_kq_kqv.cl"); +#endif + cl_program prog_kqv = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts+" -DKQV "); + cl_program prog_kq = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_f16_f32_kqv = clCreateKernel(prog_kqv, "mul_mm_f16_f32_kqv", &err), err)); + CL_CHECK((backend_ctx->mul_mat.kernel_mul_mm_f16_f32_kq = clCreateKernel(prog_kq, "mul_mm_f16_f32_kq", &err), err)); + CL_CHECK(clReleaseProgram(prog_kqv)); + CL_CHECK(clReleaseProgram(prog_kq)); + GGML_LOG_CONT("."); + } + + load_cl_kernels_gemm_coopk(backend_ctx); + load_cl_kernels_coopmat(backend_ctx); +#else + GGML_UNUSED(backend_ctx); +#endif // GGML_OPENCL_USE_ADRENO_KERNELS +} + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +bool ggml_cl_can_use_adreno_xmem_gemm_f16_f32( + const ggml_backend_opencl_context * backend_ctx, + const ggml_tensor * src0, + const ggml_tensor * src1, + const ggml_tensor * dst) { + if (!backend_ctx->adreno_xmem_gemm_enabled) { + return false; + } + if (backend_ctx->gpu_family != GPU_FAMILY::ADRENO) { + return false; + } + if ((src0->type != GGML_TYPE_F16 && src0->type != GGML_TYPE_BF16) || + src1->type != GGML_TYPE_F32 || dst->type != GGML_TYPE_F32) { + return false; + } + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(src1) || !ggml_is_contiguous(dst)) { + return false; + } + if (src0->ne[2] != 1 || src0->ne[3] != 1 || + src1->ne[2] != 1 || src1->ne[3] != 1 || + dst->ne[2] != 1 || dst->ne[3] != 1) { + return false; + } + const int K = src0->ne[0]; + const int M = src0->ne[1]; + const int N = src1->ne[1]; + if (src1->ne[0] != K || dst->ne[0] != M || dst->ne[1] != N) { + return false; + } + if (N <= 1 || M < 64 || N < 16 || K < 64) { + return false; + } + if ((K % 8) != 0) { + return false; + } + const int kpack = K / 4; + const int npack = CEIL_DIV(M, 4); + if (static_cast(N) > backend_ctx->image2d_max_width || + static_cast(kpack) > backend_ctx->image2d_max_height) { + return false; + } + if (static_cast(N) > backend_ctx->image2d_max_width || + static_cast(npack) > backend_ctx->image2d_max_height) { + return false; + } + return true; +} + +void ggml_cl_mul_mat_f16_f32_adreno_xmem( + ggml_backend_t backend, + const ggml_tensor * src0, + const ggml_tensor * src1, + ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offset1 = extra1->offset + src1->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int K = src0->ne[0]; + const int M = src0->ne[1]; + const int N = src1->ne[1]; + const int kpack = K / 4; + const int npack = CEIL_DIV(M, 4); + const int os = 8; + // Pad weights to the 32-row tiles read by the xmem kernel. + const int npack_padded = CEIL_DIV(npack, os)*os; + + const size_t xmem_bytes = 6144; + const size_t weight_bytes = static_cast(kpack) * static_cast(npack_padded) * 4u * sizeof(cl_half4); + + backend_ctx->prealloc_adreno_xmem_const.allocate(backend_ctx->context, xmem_bytes); + + cl_int err = CL_SUCCESS; + cl_image_format fmt = {}; + fmt.image_channel_order = CL_RGBA; + fmt.image_channel_data_type = CL_HALF_FLOAT; + + cl_image_desc desc_src = {}; + desc_src.image_type = CL_MEM_OBJECT_IMAGE2D; + desc_src.image_width = static_cast(N); + desc_src.image_height = static_cast(kpack); + cl_mem src_img = clCreateImage(backend_ctx->context, CL_MEM_READ_WRITE, &fmt, &desc_src, nullptr, &err); + CL_CHECK(err); + + cl_image_desc desc_dst = {}; + desc_dst.image_type = CL_MEM_OBJECT_IMAGE2D; + desc_dst.image_width = static_cast(N); + desc_dst.image_height = static_cast(npack); + cl_mem dst_img = clCreateImage(backend_ctx->context, CL_MEM_READ_WRITE, &fmt, &desc_dst, nullptr, &err); + CL_CHECK(err); + + cl_mem weights = clCreateBuffer(backend_ctx->context, CL_MEM_READ_WRITE, weight_bytes, nullptr, &err); + CL_CHECK(err); + + cl_kernel prepack = backend_ctx->mul_mat.kernel_adreno_xmem_prepack_weight_f16; + CL_CHECK(clSetKernelArg(prepack, 0, sizeof(cl_mem), &weights)); + CL_CHECK(clSetKernelArg(prepack, 1, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(prepack, 2, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(prepack, 3, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(prepack, 4, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(prepack, 5, sizeof(int), &kpack)); + CL_CHECK(clSetKernelArg(prepack, 6, sizeof(int), &npack_padded)); + CL_CHECK(clSetKernelArg(prepack, 7, sizeof(int), &os)); + size_t lws = 256; + size_t max_wg = backend_ctx->get_kernel_workgroup_size(prepack); + if (lws > max_wg) { + lws = max_wg; + } + size_t gws = CEIL_DIV(static_cast(kpack) * static_cast(npack_padded), lws) * lws; + backend_ctx->enqueue_ndrange_kernel(prepack, 1, &gws, &lws, dst); + + cl_kernel pack_src = backend_ctx->mul_mat.kernel_adreno_xmem_pack_src_f32; + CL_CHECK(clSetKernelArg(pack_src, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(pack_src, 1, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(pack_src, 2, sizeof(cl_mem), &src_img)); + CL_CHECK(clSetKernelArg(pack_src, 3, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(pack_src, 4, sizeof(int), &N)); + size_t pack_src_lws[2] = { 16, 16 }; + size_t pack_src_gws[2] = { + CEIL_DIV(static_cast(N), pack_src_lws[0])*pack_src_lws[0], + CEIL_DIV(static_cast(kpack), pack_src_lws[1])*pack_src_lws[1] + }; + backend_ctx->enqueue_ndrange_kernel(pack_src, 2, pack_src_gws, pack_src_lws, dst); + + cl_kernel gemm = backend_ctx->mul_mat.kernel_gemm_xmem_f16_f32_os8; + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &weights)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &backend_ctx->prealloc_adreno_xmem_const.buffer)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &src_img)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &dst_img)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(int), &npack)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(int), &kpack)); + const size_t z_values = CEIL_DIV(static_cast(npack), static_cast(os)); + size_t gemm_lws[3] = { 64, 1, 1 }; + size_t gemm_gws[3] = { + z_values*gemm_lws[0], + CEIL_DIV(static_cast(N), gemm_lws[0]), + 1 + }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, gemm_gws, gemm_lws, dst); + + cl_kernel store_dst = backend_ctx->mul_mat.kernel_adreno_xmem_store_dst_f32; + CL_CHECK(clSetKernelArg(store_dst, 0, sizeof(cl_mem), &dst_img)); + CL_CHECK(clSetKernelArg(store_dst, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(store_dst, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(store_dst, 3, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(store_dst, 4, sizeof(int), &N)); + size_t store_lws[2] = { 16, 16 }; + size_t store_gws[2] = { + CEIL_DIV(static_cast(N), store_lws[0])*store_lws[0], + CEIL_DIV(static_cast(npack), store_lws[1])*store_lws[1] + }; + backend_ctx->enqueue_ndrange_kernel(store_dst, 2, store_gws, store_lws, dst); + + CL_CHECK(clReleaseMemObject(weights)); + CL_CHECK(clReleaseMemObject(dst_img)); + CL_CHECK(clReleaseMemObject(src_img)); +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +bool ggml_cl_mul_mat_f16_f32_attn_adreno( + ggml_backend_t backend, + const ggml_tensor * src0, + const ggml_tensor * src1, + ggml_tensor * dst +) { + const enum ggml_type src0t = (src0->type == GGML_TYPE_BF16) ? GGML_TYPE_F16 : src0->type; + const enum ggml_type src1t = src1->type; + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offset1 = extra1->offset + src1->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + + const int r2 = ne12 / ne02; + const int r3 = ne13 / ne03; + + if(src0t == GGML_TYPE_F16 && src1t == GGML_TYPE_F32){ + // Two tiling assumptions these kernels make but nothing enforced: + // + // ne00 % TILESIZE_K(16): the K loop has no tail, so a K that does not + // divide folds 1-15 rows of whatever follows the operands into every + // output. + // + // ne01 % TILESIZE_M(64): mm_store_c_N guards the n direction with its + // `mask` argument but nothing guards m -- the store walks all 64 rows + // of the tile at a stride of M. When M does not divide, the last tile + // does not run off the end of the buffer, it writes 64 - (M % 64) + // values ON TOP OF the next column, so the result is silently wrong. + // Reachable on the KQV side for any head size >= 64 that is not a + // multiple of it (80, 96, 112). + // + // Attention shapes in the graph satisfy both -- head sizes are multiples + // of 64 and n_kv is padded -- which is why this has stayed latent. + // Declining leaves the odd shapes on the generic GEMM, which handles them. + if (ne01 >= 64 && ne1 >= 32 && ne00 >= 16 && + (ne00 % 16) == 0 && (ne01 % 64) == 0 && (ne12 % ne02) == 0 && + // the KQ/KQV image kernels do not handle dim 3 (multi-stream batches) + ne03 == 1 && ne13 == 1 && + // dst is wrapped with image1d_buffer, the size limit applies, also src0 + (ne0 * ne1 * dst->ne[2] * dst->nb[0] / 4 <= backend_ctx->image_max_buffer_size)) { + // For KQ. + // + // Layout admission, mirroring the KQV arm below. The KQ kernel takes + // no stride arguments for A or B: it derives them as K*D_A*2 and + // K*D_B*4, i.e. it assumes both operands pack exactly D heads of K + // elements per row. Every real KV-cache view and permuted-Q view + // does, but a view spanning part of a wider allocation does not, and + // the kernel then walks the wrong rows with nothing to range-check + // it. Gate on the packed layout itself rather than on the stride + // ORDERING, which a wider parent satisfies just as well. + const bool kq_packed_a = (nb01 == (cl_ulong)ne00 * ne02 * ggml_type_size(src0t)) && + (nb02 == (cl_ulong)ne00 * ggml_type_size(src0t)); + const bool kq_packed_b = (nb11 == (cl_ulong)ne10 * ne12 * ggml_type_size(src1t)) && + (nb12 == (cl_ulong)ne10 * ggml_type_size(src1t)); + // + // ggml_is_permuted(src0) stands in for "K is head-major", but it is + // only a proxy and it COLLAPSES at n_head_kv == 1: with a single + // head there is no head stride to be out of order, so nb01 == nb02 + // and the view reports itself unpermuted. Such a KQ was declined + // here and fell through to the generic GEMM (gemma-4 E2B, and any + // other multi-query model). The packed check above is the contract + // the kernel actually needs -- it pins both strides exactly -- so + // require permutedness only where there is more than one head for + // it to mean anything. + // + // Default on; GGML_OPENCL_KQ_NHEAD_KV1=0 restores the old proxy so + // the two routings can be compared in one binary. + static const char * kq_nhkv1_env = getenv("GGML_OPENCL_KQ_NHEAD_KV1"); + static const bool kq_nhkv1_on = + (kq_nhkv1_env == nullptr || kq_nhkv1_env[0] != '0'); + if ((ggml_is_permuted(src0) || (ne02 == 1 && kq_nhkv1_on)) && ggml_is_permuted(src1) && + kq_packed_a && kq_packed_b && + ((nb01 * ne01 / 4)/4 <= backend_ctx->image_max_buffer_size) && + nb00 <= nb02 && + nb02 <= nb01 && + nb01 <= nb03 && + nb10 <= nb12 && + nb12 <= nb11 && + nb11 <= nb13) { + ggml_cl_mul_mat_kq_kqv_adreno(backend, src0, src1, dst, /*is_kq =*/ true); + return true; + } + // For KQV. Reaching this arm is what makes the op a KQV; the callee + // is told so explicitly rather than re-deriving it from the strides + // the arm above has already ruled on. + if (!ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && + ((nb02 * ne02 / 4)/4 <= backend_ctx->image_max_buffer_size)) { + ggml_cl_mul_mat_kq_kqv_adreno(backend, src0, src1, dst, /*is_kq =*/ false); + return true; + } + } + + static const char * mm_kq_gqa_img_env = getenv("GGML_OPENCL_MM_KQ_GQA_IMG"); + static const bool mm_kq_gqa_img_on = (mm_kq_gqa_img_env == nullptr || mm_kq_gqa_img_env[0] != '0'); + static const char * mm_kq_gqa_r4_img_env = getenv("GGML_OPENCL_MM_KQ_GQA_R4_IMG"); + static const bool mm_kq_gqa_r4_img_on = (mm_kq_gqa_r4_img_env == nullptr || mm_kq_gqa_r4_img_env[0] != '0'); + const bool img_r4_gate = + mm_kq_gqa_r4_img_on && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img != nullptr && + ne11 == 1 && ne01 >= 64 && (ne01 % 16) == 0 && ne00 == 128 && + (ne12 % ne02) == 0 && (ne12 / ne02) == 4 && (ne13 / ne03) == 1; + if (mm_kq_gqa_img_on && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4_img != nullptr && + ne11 == 1 && ne01 >= 64 && (ne01 % 16) == 0 && ne00 == 128 && + (ne12 % ne02) == 0 && (ne12 / ne02) == 8 && (ne13 / ne03) == 1) { + const size_t nb00_bytes = sizeof(uint16_t); + const size_t k_bytes_span = + (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + + (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + + (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + + (size_t)ne00 * nb00_bytes; + + const size_t k_bytes = (k_bytes_span + 15) & ~(size_t)15; + const size_t k_pixels = k_bytes >> 4; + if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa4_img; + cl_mem K_img = ggml_cl_img_pool_get_or_create( + backend_ctx, backend_ctx->kq_img_pool, + extra0->data_device, offset0, k_bytes, CL_FLOAT); + if (K_img != nullptr) { + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &K_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); + + const int nth0_d = 64; + const int64_t n_wg_x = ne01 / 16; + size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; + size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; + } + } + } + + // r2=4 specialization + if (img_r4_gate) { + const size_t nb00_bytes = sizeof(uint16_t); + const size_t k_bytes_span = + (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + + (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + + (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + + (size_t)ne00 * nb00_bytes; + const size_t k_bytes = (k_bytes_span + 15) & ~(size_t)15; + const size_t k_pixels = k_bytes >> 4; + if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r4_img; + cl_mem K_img = ggml_cl_img_pool_get_or_create( + backend_ctx, backend_ctx->kq_img_pool, + extra0->data_device, offset0, k_bytes, CL_FLOAT); + if (K_img != nullptr) { + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &K_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); + + const int nth0_d = 64; + const int64_t n_wg_x = ne01 / 16; + size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; + size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; + } + } + } + + // DK=256, r2=2 specialization + static const char * mm_kq_r2_dk256_env = getenv("GGML_OPENCL_MM_KQ_GQA_R2_DK256_IMG"); + static const bool mm_kq_r2_dk256_on = (mm_kq_r2_dk256_env != nullptr && mm_kq_r2_dk256_env[0] != '0'); + if (mm_kq_r2_dk256_on && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img != nullptr && + ne11 == 1 && ne01 >= 64 && (ne01 % 16) == 0 && ne00 == 256 && + (ne12 % ne02) == 0 && (ne12 / ne02) == 2 && (ne13 / ne03) == 1) { + const size_t nb00_bytes = sizeof(uint16_t); + const size_t k_bytes_span = + (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + + (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + + (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + + (size_t)ne00 * nb00_bytes; + const size_t k_bytes = (k_bytes_span + 15) & ~(size_t)15; + const size_t k_pixels = k_bytes >> 4; + if (k_pixels > 0 && k_pixels <= backend_ctx->image_max_buffer_size) { + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_x8_gqa_r2_dk256_img; + cl_mem K_img = ggml_cl_img_pool_get_or_create( + backend_ctx, backend_ctx->kq_img_pool, + extra0->data_device, offset0, k_bytes, CL_FLOAT); + if (K_img != nullptr) { + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &K_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); + + const int nth0_d = 64; + const int64_t n_wg_x = ne01 / 16; + size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; + size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; + } + } + } + + // GQA-coalesced KQV for decode using image1d_buffer_t + static const char * mm_kqv_gqa_img_env = getenv("GGML_OPENCL_MM_KQV_GQA_IMG"); + static const bool mm_kqv_gqa_img_on = (mm_kqv_gqa_img_env != nullptr && mm_kqv_gqa_img_env[0] != '0'); + if (mm_kqv_gqa_img_on && + backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa_img != nullptr && + ne11 == 1 && ne01 == 128 && + (ne12 % ne02) == 0 && (ne12 / ne02) == 8 && (ne13 / ne03) == 1) { + const size_t nb00_bytes = sizeof(uint16_t); + const size_t v_bytes_span = + (size_t)(ne01 > 0 ? ne01 - 1 : 0) * (size_t)nb01 + + (size_t)(ne02 > 0 ? ne02 - 1 : 0) * (size_t)nb02 + + (size_t)(ne03 > 0 ? ne03 - 1 : 0) * (size_t)nb03 + + (size_t)ne00 * nb00_bytes; + const size_t v_bytes = (v_bytes_span + 7) & ~(size_t)7; + const size_t v_pixels = v_bytes >> 3; + if (v_pixels > 0 && v_pixels <= backend_ctx->image_max_buffer_size) { + cl_kernel kernel = backend_ctx->mul_mat.kernel_mul_mat_f16_f32_l4_y8_gqa_img; + cl_mem V_img = ggml_cl_img_pool_get_or_create( + backend_ctx, backend_ctx->kqv_img_pool, + extra0->data_device, offset0, v_bytes, CL_HALF_FLOAT); + if (V_img != nullptr) { + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &V_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &r3)); + + const int nth0_d = 64; + const int64_t n_wg_x = ne01 / 8; + size_t global_work_size[] = {(size_t)n_wg_x * nth0_d, (size_t)1, (size_t)ne02 * ne13}; + size_t local_work_size[] = {(size_t)nth0_d, (size_t)1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return true; + } + } + } + } + + return false; +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +void ggml_cl_mul_mat_kq_kqv_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, bool is_kq) { + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + + const int ne10 = src1->ne[0]; + const int ne11 = src1->ne[1]; + const int ne12 = src1->ne[2]; + + const cl_ulong nb10 = src1->nb[0]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 == ne10); + + cl_kernel kernel; + cl_context context = backend_ctx->context; + + cl_int status; + cl_image_format img_fmt_1d; + cl_image_desc img_desc_1d; + cl_buffer_region region; + cl_mem A_image1d; + cl_mem A_sub_buffer; + cl_mem B_sub_buffer; + cl_mem D_image1d; + cl_mem D_sub_buffer; + + int M = ne01; + int N = ne1; + int K = ne00; + + kernel = is_kq ? backend_ctx->mul_mat.kernel_mul_mm_f16_f32_kq + : backend_ctx->mul_mat.kernel_mul_mm_f16_f32_kqv; + // create sub-buffer for A + // <--------------------------------------------> // + extra0 = src0->view_src ? (ggml_tensor_extra_cl *)src0->view_src->extra : (ggml_tensor_extra_cl *)src0->extra; + + region.origin = (extra0->offset + src0->view_offs); + if (is_kq) { + // KQ + region.size = nb01 * ne01; + } else { + // KQV + region.size = nb02 * ne02; + } + + A_sub_buffer = clCreateSubBuffer((extra0->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // <--------------------------------------------> // + + // create sub-buffer for B + // <--------------------------------------------> // + region.origin = (extra1->offset + src1->view_offs); + region.size = nb10 * ne10 * ne11 * ne12; + B_sub_buffer = clCreateSubBuffer((extra1->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + // <--------------------------------------------> // + + img_fmt_1d = {CL_RGBA, CL_FLOAT}; + memset(&img_desc_1d, 0, sizeof(img_desc_1d)); + img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + if (is_kq) { + img_desc_1d.image_width = (nb01 * ne01 / 4)/4; + } + else { + img_desc_1d.image_width = (nb02 * ne02 / 4)/4; + } + img_desc_1d.buffer = A_sub_buffer; + A_image1d = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &status); + CL_CHECK(status); + + // create sub-buffer for output C + // <--------------------------------------------> // + region.origin = (extrad->offset + dst->view_offs); + region.size = ne0 * ne1 * dst->ne[2] * dst->nb[0]; // size of C in bytes + D_sub_buffer = clCreateSubBuffer((extrad->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + // <--------------------------------------------> // + + // create image for C output + // <--------------------------------------------> // + img_fmt_1d = {CL_R, CL_FLOAT}; + memset(&img_desc_1d, 0, sizeof(img_desc_1d)); + img_desc_1d.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc_1d.image_width = ne0 * ne1 * dst->ne[2] * dst->nb[0] / 4; + img_desc_1d.buffer = D_sub_buffer; + D_image1d = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt_1d, &img_desc_1d, NULL, &status); + CL_CHECK(status); + // <--------------------------------------------> // + + int offset_src0 = 0; + int offset_src1 = 0; + + // set kernel args + // <--------------------------------------------> // + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &A_image1d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset_src0)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &B_sub_buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset_src1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &D_image1d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &extrad->offset)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &nb01)); + + size_t global_work_size[3] = {64, static_cast(((M+63)/64)), static_cast(((N+31)/32)*ne12)}; + size_t local_work_size[3] = {64, 1, 2}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + // deallocate sub buffers and images + // <--------------------------------------------> // + CL_CHECK(clReleaseMemObject(A_image1d)); + CL_CHECK(clReleaseMemObject(D_image1d)); + CL_CHECK(clReleaseMemObject(A_sub_buffer)); + CL_CHECK(clReleaseMemObject(B_sub_buffer)); + CL_CHECK(clReleaseMemObject(D_sub_buffer)); +} + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_q1_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT(src0->type == GGML_TYPE_Q1_0); + GGML_ASSERT(src1->type == GGML_TYPE_F32); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q1_0 * extra0_q1_0 = (ggml_tensor_extra_cl_q1_0 *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_ASSERT(src1->view_offs == 0); + GGML_ASSERT(dst->view_offs == 0); + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + + const int ne10 = src1->ne[0]; + const int ne12 = src1->ne[2]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 == ne10); + GGML_ASSERT((ne00 % 128) == 0); + GGML_ASSERT(ne0 == ne01); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + if (ne1 == 1) { + cl_mem q_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for q (uint32: each texel packs 32 sign bits) + img_fmt = { CL_R, CL_UNSIGNED_INT32}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 32; + img_desc.buffer = extra0_q1_0->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // create a sub_buffer for B + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer((extra1->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // Tall M has enough row parallelism to skip the K split and its reduction. + const bool use_nsg1 = backend_ctx->min_m_gemv_nsg1_q1_0 > 0 && M >= backend_ctx->min_m_gemv_nsg1_q1_0; + kernel = use_nsg1 ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q1_0_f32_nsg1 : backend_ctx->mul_mat.kernel_gemv_noshuffle_q1_0_f32; + + int r2 = 1; + int r3 = 1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q1_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &extra1->offset)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &extrad->offset)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); + + size_t wavesize = backend_ctx->adreno_wave_size; + const size_t nsg = use_nsg1 ? 1 : 4; + size_t local_work_size[] = { wavesize, nsg, 1 }; + size_t global_work_size[] = { CEIL_DIV(M, wavesize)*wavesize, nsg, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } else { + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q1_0_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q1_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q1_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(N, 8), (size_t)CEIL_DIV(M, 4), 1 }; + size_t local_work_size[] = { 2, 128, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } +} +#endif + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static bool ggml_cl_mul_mat_q2_0_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_q2_0 * extra0 = (ggml_tensor_extra_cl_q2_0 *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_0_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_0_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_Q2_0_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +void ggml_cl_mul_mat_q2_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_q2_0 * extra0 = (ggml_tensor_extra_cl_q2_0 *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + const bool wide = m >= 16384 && m % 8 == 0; + cl_kernel gemv = wide ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q2_0_f32_wide : backend_ctx->mul_mat.kernel_gemv_noshuffle_q2_0_f32; + const size_t workgroup = wide ? backend_ctx->mul_mat.q2_0_mv_workgroup_size_wide : backend_ctx->mul_mat.q2_0_mv_workgroup_size; + const size_t rows = wide ? 8 : 4; + size_t nsg = std::min((size_t)backend_ctx->mul_mat.q2_0_mv_nsg, wide ? size_t(8) : m >= 4096 ? size_t(16) : size_t(32)); + while (nsg > (size_t)k/64 || nsg*16 > workgroup) { + nsg /= 2; + } + const size_t lanes = workgroup/nsg; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &stride_d)); + size_t global[] = { (size_t)CEIL_DIV(m, rows*lanes)*lanes, (size_t)n*nsg, 1 }; + size_t local[] = { lanes, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_q2_0_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_0_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + + +static bool ggml_cl_mul_mat_coopmat(ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, + std::initializer_list weights, + const ggml_tensor * src1, ggml_tensor * dst, int K, int M, int N) { + if (kernel == nullptr || M % 64 != 0 || N < 2) { + return false; + } + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int n_tiles = CEIL_DIV(N, 64); + + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, (size_t)n_tiles * 64 * K * sizeof(cl_half)); + + cl_kernel pk = backend_ctx->mul_mat.kernel_pack_b_f16_coopmat; + CL_CHECK(clSetKernelArg(pk, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(pk, 1, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(pk, 2, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); + CL_CHECK(clSetKernelArg(pk, 3, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(pk, 4, sizeof(int), &N)); + size_t p_local[2] = { 64, 4 }; + size_t p_global[2] = { (size_t)n_tiles * 64, (size_t)CEIL_DIV(K, 64) * 4 }; + backend_ctx->enqueue_ndrange_kernel(pk, 2, p_global, p_local, dst); + + cl_uint ka = 0; + for (cl_mem w : weights) { + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &w)); + } + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &backend_ctx->prealloc_act_trans.buffer)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, ka++, sizeof(int), &N)); + + size_t c_local[3] = { 64, 1, 4 }; + size_t c_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(n_tiles, 4) * 4 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, c_global, c_local, dst); + return true; +} + +static void ggml_cl_mul_mat_q4_0_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + if (ne1 == 1) { + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_RGBA, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_32b_trans; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &K)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &M)); + + size_t wavesize = backend_ctx->adreno_wave_size; + size_t local_work_size[3] = { wavesize, 4, 1 }; + size_t global_work_size[3] = { (size_t)CEIL_DIV(M, 64) * 64, 4, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + const bool have_a8 = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin != nullptr; + const int gemm_tile_n = have_a8 ? 64 : 32; + int N_pad = (N + gemm_tile_n - 1) & ~(gemm_tile_n - 1); + + cl_mem a_img = extra0_q4_0->q_img; + cl_mem s_img = extra0_q4_0->d_img; + GGML_ASSERT(a_img && s_img && "ILA Q4_0 weight images missing; set_tensor should have built them"); + + static const char * q4_0_bin_dp4a_env = getenv("GGML_OPENCL_Q4_0_BIN_DP4A"); + bool q4_0_bin_dp4a_on = q4_0_bin_dp4a_env + ? (atoi(q4_0_bin_dp4a_env) != 0) + : true; + // dot prod has to be available + q4_0_bin_dp4a_on = backend_ctx->has_integer_dot && q4_0_bin_dp4a_on; + + if (q4_0_bin_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin) { + const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; + const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); + + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_mem b_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_int tb = (cl_int)((size_t)N * (K / 32)); + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_mem d_sub = nullptr; + cl_mem d_img = nullptr; + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a_ila_a8_bin; + + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 1, 1 }; + size_t global_work_size[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub)); + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub)); + return; + } + + // Pad B through a zero-filled scratch buffer when N needs + // padding, since the GEMM kernel always reads a full N-tile. + const bool need_pad = N_pad > N; + cl_mem b_sub_buf = nullptr; + cl_mem b_padded = nullptr; + if (need_pad) { + CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, + (size_t)K * N_pad * sizeof(float), NULL, &err), err)); + const float zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), + 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, + offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + } else { + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = need_pad ? (size_t)K * N_pad : (size_t)K * N; + img_desc.buffer = need_pad ? b_padded : b_sub_buf; + cl_mem b_img; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + int line_stride_matrix_A_in_bytes = M * 4; + int line_stride_matrix_S_in_bytes = M * 2; + int line_stride_matrix_B_in_bytes = K * 4; + int line_stride_matrix_C_in_bytes = M * 4; + + const int b_offset_for_kernel = 0; + + if (!have_a8) { + const int c_offset_for_kernel = (int)offsetd; + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a7_bin; + + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &b_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_A_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_S_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_B_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_C_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + if ((m_tiles % 2) != 0) { + // keep the work-group count in y even so every work-group is full + m_tiles += 1; + } + + size_t local_work_size[3] = { 64, 2, 4 }; + size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img)); + if (b_sub_buf) { + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } + if (b_padded) { + CL_CHECK(clReleaseMemObject(b_padded)); + } + return; + } + + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + cl_mem d_sub_buf; + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub_buf; + cl_mem d_img; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + const int c_offset_for_kernel = 0; + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_32b_trans_ila_a8_bin; + + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &s_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &b_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_A_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_S_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_B_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_matrix_C_in_bytes)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 2 }; + size_t global_work_size[3] = { 64, (size_t)CEIL_DIV(M, 64), (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + + if (b_sub_buf) { + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } + if (b_padded) { + CL_CHECK(clReleaseMemObject(b_padded)); + } + } +} + +void ggml_cl_mul_mat_q4_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + + const int ne10 = src1->ne[0]; + const int ne12 = src1->ne[2]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + // Multi-column (N=3) verify GEMV for q4_0 + static const bool q40_mc3 = (getenv("GGML_OPENCL_Q4_0_MC3") != nullptr); + const bool use_q40_mc3 = q40_mc3 && (ne1 >= 2 && ne1 <= 4) && (ne01 < 32768); + + const bool use_bin = use_q4_0_bin_kernels(backend_ctx, src0); + + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32_coopmat, + { extra0_q4_0->q, extra0_q4_0->d }, src1, dst, K, M, N)) { + return; + } + + if (use_bin) { + if (use_q40_mc3) { + static bool warned = false; + if (!warned) { + GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q4_0_MC3 is bypassed by Q4_0 binary kernels\n"); + warned = true; + } + } + // This bin layout is not supported by CoopK. + ggml_cl_mul_mat_q4_0_f32_adreno_ila(backend, src0, src1, dst); + return; + } + + if (ne1 == 1 || use_q40_mc3) { + cl_mem q_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for q + img_fmt = { CL_R, CL_UNSIGNED_INT32}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_q4_0->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + if (use_q40_mc3) { + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_mc3; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne1)); + } else { + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32; + if (M == 4096 && K == 4096) { + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_4096_1_4096; + } else if (M == 4096 && K == 11008) { + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_4096_1_11008; + } else if (M == 11008 && K == 4096) { + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_11008_1_4096; + } else if (M == 32000 && K == 4096) { + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_0_f32_32000_1_4096; + } + + int r2 = 1; + int r3 = 1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); + } + + // Small-M mc3 verify is occupancy/latency-bound (too few WGs at small M, so + // its bandwidth falls well short of the FFN matmuls'). Use 8 subgroups (512-WI WGs, half the + // per-lane K-walk) for small M. Layout stride is fixed (4 uints/block), so only + // the K-split count changes; the mc3 kernel reads it via get_local_size(1). The + // ne1==1 base kernel hardcodes N_SIMDGROUP=4, so it always stays at 4. + int mc3_nsg = (use_q40_mc3 && ne01 < 4096) ? 8 : 4; + if (use_q40_mc3) { + // Register pressure can lower the kernel limit below the device limit. + const size_t max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + while (mc3_nsg > 1 && (size_t)(64 * mc3_nsg) > max_workgroup_size) { + mc3_nsg /= 2; + } + } + size_t local_work_size[3] = {64, (size_t)mc3_nsg, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, (size_t)mc3_nsg, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + // CoopK uses the same untiled weight layout as gemm_noshuffle_q4_0_f32, with K-major Q8_1 activations (K contiguous). + if (ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->mul_mat.rows_coopk_dp4a_q4_0) + && backend_ctx->mul_mat.kernel_gemm_coopk_q4_0_q8_1_dp4a_c4 != nullptr + && ((N <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q4_0_q8_1_dp4a_c4) != nullptr) { + cl_mem b_sub_buf = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const int cols = (N <= 2) ? 2 : 4; + const size_t n_blocks_padded = (size_t)cols * (K / 32); + const size_t size_qa = (size_t)cols * K * sizeof(cl_char); + const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; + const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; + backend_ctx->prealloc_moe_qa.allocate(context, size_qa); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); + if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { + const cl_char z8 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, + &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); + } + if (backend_ctx->prealloc_moe_da.size != size_da_prev) { + const cl_half z16 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); + } + + cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); + cl_kernel kernel_quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); + size_t local_work_size_quant[1] = { 64 }; + size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); + + cl_kernel kernel_coopk = (N <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q4_0_q8_1_dp4a_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q4_0_q8_1_dp4a_c4; + const cl_int n_padded = cols; + CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q4_0->q)); + CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_int), &n_padded)); + CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_int), &K)); + CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &N)); + + const size_t nsg = (size_t)backend_ctx->mul_mat.nsg_coopk_dp4a_q4_0; + size_t local_work_size[3] = { 64, nsg, 1 }; + size_t global_work_size[3] = { (size_t)(M / backend_ctx->mul_mat.rows_coopk_dp4a_q4_0), nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + static const char * q4_0_act_vload4_env = getenv("GGML_OPENCL_Q4_0_DP4A_ACT_VLOAD4"); + const bool q4_0_act_vload4_on = q4_0_act_vload4_env == nullptr || atoi(q4_0_act_vload4_env) != 0; + // Enable dense prefill by default on X2E when the uint4 activation tile is enabled. + static const char * q4_0_dense_dp4a_env = getenv("GGML_OPENCL_Q4_0_DENSE_DP4A"); + bool q4_0_dense_dp4a_on = q4_0_dense_dp4a_env + ? (atoi(q4_0_dense_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && q4_0_act_vload4_on); + // dot prod has to be available + q4_0_dense_dp4a_on = backend_ctx->has_integer_dot && q4_0_dense_dp4a_on; + + if (q4_0_dense_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a + && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { + cl_mem a_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const size_t n_blocks = (size_t)N * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_kernel dk = q4_0_act_vload4_on + ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a_act_vload4 + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_q8_1_dp4a; + int ai = 0; + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_0->q)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + CL_CHECK(clReleaseMemObject(a_sub)); + return; + } + + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + cl_mem d_sub_buf = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for output + region.origin = extrad->offset; // Specify the starting offset (in bytes) + region.size = M * N * sizeof(float); // Specify the size of the sub-buffer + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, CL_MEM_WRITE_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + if (ne0 == 4096 && ne1 == 128 && ne10 == 4096) { + local_work_size_t[0]=4; + local_work_size_t[1]=8; + } else if (ne0 == 11008 && ne1 == 128 && ne10 == 4096) { + local_work_size_t[0]=2; + local_work_size_t[1]=8; + } else if(ne0 == 4096 && ne1 == 128 && ne10 == 11008) { + local_work_size_t[0]=1; + local_work_size_t[1]=8; + } else if(ne0 == 32000 && ne1 == 128 && ne10 == 4096) { + local_work_size_t[0]=2; + local_work_size_t[1]=8; + } + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_0_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &d_sub_buf)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne1)); + + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; + size_t local_work_size[3] = {1, 128, 1}; + if (ne0 == 4096 && ne1 == 128 && ne10 == 4096) { + local_work_size[0] = 1; + local_work_size[1] = 128; + } else if (ne0 == 11008 && ne1 == 128 && ne10 == 4096) { + local_work_size[0] = 2; + local_work_size[1] = 64; + } else if (ne0 == 4096 && ne1 == 128 && ne10 == 11008) { + local_work_size[0] = 2; + local_work_size[1] = 64; + } else if (ne0 == 32000 && ne1 == 128 && ne10 == 4096) { + local_work_size[0] = 2; + local_work_size[1] = 64; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_q4_1_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q4_1 * extra0_q4_1 = (ggml_tensor_extra_cl_q4_1 *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + // Multi-column (N=3) verify GEMV for q4_1 + static const bool q41_mc3 = (getenv("GGML_OPENCL_Q4_1_MC3") != nullptr); + const bool use_q41_mc3 = q41_mc3 && (ne1 >= 2 && ne1 <= 4) && (ne01 < 32768); + + if (ne1 == 1 || use_q41_mc3) { + cl_mem q_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for q + img_fmt = { CL_R, CL_UNSIGNED_INT32}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_q4_1->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = use_q41_mc3 ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_1_f32_mc3 + : backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_1_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_1->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_1->m)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); + if (use_q41_mc3) { + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne1)); // n_cols + } + + size_t local_work_size[3] = {64, 4, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_1_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_1->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_1->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_1->m)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne1)); + + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; + size_t local_work_size[3] = {1, 128, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_q5_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q5_0 * extra0_q5_0 = (ggml_tensor_extra_cl_q5_0 *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_f32_coopmat, + { extra0_q5_0->qs, extra0_q5_0->qh, extra0_q5_0->d }, src1, dst, K, M, N)) { + return; + } + + if (ne1 == 1) { + cl_mem qs_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for qs + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_q5_0->qs; + CL_CHECK((qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_0_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); + + size_t local_work_size[3] = {64, 4, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(qs_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + // dp4a (int8) dense q5_0 prefill GEMM, default off + static const char * q5_dense_dp4a_env = getenv("GGML_OPENCL_Q5_DENSE_DP4A"); + static const char * q5_dense_wimg_env = getenv("GGML_OPENCL_Q5_DENSE_DP4A_WIMG"); + const bool q5_dense_wimg_on = q5_dense_wimg_env && (atoi(q5_dense_wimg_env) != 0); + bool q5_dense_dp4a_on = q5_dense_wimg_on + ? true + : (q5_dense_dp4a_env && (atoi(q5_dense_dp4a_env) != 0)); + // dot prod has to be available + q5_dense_dp4a_on = backend_ctx->has_integer_dot && q5_dense_dp4a_on; + + if (q5_dense_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_q8_1_dp4a + && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { + cl_mem a_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const size_t n_blocks = (size_t)N * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + // optional qs texture (image1d_buffer over the nibble plane; the same + // CL_R/UINT32 view, width M*K/8, the GEMV path builds). + cl_mem q5_qs_img = nullptr; + bool use_wimg = q5_dense_wimg_on; + if (use_wimg) { + const size_t tex = (size_t)M * (size_t)K / 8; // uint32 texels (2 ushorts/texel) + if (tex == 0 || tex > backend_ctx->image_max_buffer_size) { + use_wimg = false; + } else { + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = tex; + img_desc.buffer = extra0_q5_0->qs; + q5_qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err); + if (err != CL_SUCCESS || q5_qs_img == nullptr) { use_wimg = false; q5_qs_img = nullptr; } + } + } + + cl_kernel dk = use_wimg ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_q8_1_dp4a_wimg + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_q8_1_dp4a; + int ai = 0; + if (use_wimg) { + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &q5_qs_img)); + } else { + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_0->qs)); + } + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_0->qh)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_0->d)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + if (q5_qs_img != nullptr) { + CL_CHECK(clReleaseMemObject(q5_qs_img)); + } + CL_CHECK(clReleaseMemObject(a_sub)); + return; + } + + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + cl_mem d_sub_buf = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for output + region.origin = extrad->offset; + region.size = M * N * sizeof(float); + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, CL_MEM_WRITE_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_0_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d_sub_buf)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne1)); + + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; + size_t local_work_size[3] = {1, 128, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_q5_1_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q5_1 * extra0_q5_1 = (ggml_tensor_extra_cl_q5_1 *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + if (ne1 == 1) { + cl_mem qs_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for qs + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_q5_1->qs; + CL_CHECK((qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_1_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_1->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_1->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_1->m)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); + + size_t local_work_size[3] = {64, 4, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(qs_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + cl_mem d_sub_buf = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for output + region.origin = extrad->offset; + region.size = M * N * sizeof(float); + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, CL_MEM_WRITE_ONLY, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_1_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_1->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_1->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_1->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_1->m)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &d_sub_buf)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne1)); + + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; + size_t local_work_size[3] = {1, 128, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_iq4_nl_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_iq4_nl * extra0_iq4_nl = (ggml_tensor_extra_cl_iq4_nl *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % 32 == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + if (ne1 == 1) { + cl_mem q_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for q + img_fmt = { CL_R, CL_UNSIGNED_INT32}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_iq4_nl->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq4_nl_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_nl->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); + + size_t local_work_size[3] = {64, 4, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + // dp4a (int8) dense IQ4_NL prefill GEMM. Quantizes the [N,K] activations to + // q8_1 and runs the int8 dot instead of the f16 half-dot. Large-batch + // (ne1>8) only + static const char * iq4nl_dense_dp4a_env = getenv("GGML_OPENCL_IQ4NL_DENSE_DP4A"); + bool iq4nl_dense_dp4a_on = iq4nl_dense_dp4a_env + ? (atoi(iq4nl_dense_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + // dot prod has to be available + iq4nl_dense_dp4a_on = backend_ctx->has_integer_dot && iq4nl_dense_dp4a_on; + + if (iq4nl_dense_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a + && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { + cl_mem a_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const size_t n_blocks = (size_t)N * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_kernel dk = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_nl_q8_1_dp4a; + int ai = 0; + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_iq4_nl->q)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_iq4_nl->d)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + CL_CHECK(clReleaseMemObject(a_sub)); + return; + } + + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_nl_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_iq4_nl->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_iq4_nl->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne1)); + + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; + size_t local_work_size[3] = {1, 128, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_q8_0_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT(src0->type == GGML_TYPE_Q8_0); + GGML_ASSERT(src1->type == GGML_TYPE_F32); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + // SoA extra lives on view_src (view->extra is pre-SoA). + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q8_0 * extra0_q8_0 = (ggml_tensor_extra_cl_q8_0 *)soa0_src->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + + const int ne10 = src1->ne[0]; + const int ne12 = src1->ne[2]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 == ne10); + GGML_ASSERT((ne00 % 32) == 0); + GGML_ASSERT(ne0 == ne01); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + if (ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_coopmat, + { extra0_q8_0->q, extra0_q8_0->d }, src1, dst, K, M, N)) { + return; + } + + // Multi-column verify GEMV for ne1 2..4, reuses the ne1 == 1 image setup. + // Default on for X2E, GGML_OPENCL_Q8_0_MC=0/1 forces it. + static const char * q8_mc_env = getenv("GGML_OPENCL_Q8_0_MC"); + const bool q8_mc = q8_mc_env ? atoi(q8_mc_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; + const bool use_q8_mc = q8_mc && ne1 >= 2 && ne1 <= 4; + + if (ne1 == 1 || use_q8_mc) { + cl_mem q_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for q + img_fmt = { CL_R, CL_UNSIGNED_INT32}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 4; + img_desc.buffer = extra0_q8_0->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // create a sub_buffer for B + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer((extra1->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + if (use_q8_mc) { + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q8_0_f32_mc; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne1)); + + size_t wavesize = backend_ctx->adreno_wave_size; + size_t local_work_size[] = { wavesize, 4, 1 }; + size_t global_work_size[] = { CEIL_DIV(M, wavesize)*wavesize, 4, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + // Split-K for small-M decode GEMVs. The base kernel puts one output row + // per lane and splits K only inside one workgroup, so M is the sole source + // of workgroup parallelism: gpt-oss's K and V projections are M=512 = 8 + // workgroups on a 16-CU X2, and the kernel measures 48 GB/s where the + // M=2880/4096 projections in the same decode graph reach 122-123. Mirrors + // the q4_0/q4_K split-K above and reuses their reduce kernel. + // + // Enabled where it is measured to win, like the q4_K gate: X2-90 +2.8% + // tg32 @d4096 on gpt-oss; Adreno 840 (12 CU) NEUTRAL on Llama-3.2-3B-Q8_0 + // (0.0% @d4096 -- its K/V proj is M=1024 = 16 workgroups, which already + // fills 12 CUs). Unmeasured on X1E/A7X/A6X and the q4_K split-K measured + // -0.7% on X1E, so the default is not widened on absence of evidence. + static const bool q8_splitk_env_set = []{ + const char * e = std::getenv("GGML_OPENCL_Q8_GEMV_SPLITK"); + return e && e[0] != '\0'; + }(); + static const bool q8_splitk_env_on = []{ + const char * e = std::getenv("GGML_OPENCL_Q8_GEMV_SPLITK"); + return !(e && e[0] == '0'); + }(); + const bool q8_splitk_on = q8_splitk_env_set + ? q8_splitk_env_on + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + if (q8_splitk_on && backend_ctx->mul_mat.kernel_gemv_noshuffle_q8_0_f32_splitk && + ne01 <= 1024 && ne01 % 64 == 0) { + const int nsg = 8; + const int ksplit = 8; // -> 8 * M/64 workgroups + const size_t gx = (size_t) CEIL_DIV(ne01, 64) * 64; + + backend_ctx->prealloc_splitk_partial.allocate( + backend_ctx->context, (size_t) ksplit * ne01 * sizeof(float)); + cl_mem partial = backend_ctx->prealloc_splitk_partial.buffer; + + cl_kernel ks = backend_ctx->mul_mat.kernel_gemv_noshuffle_q8_0_f32_splitk; + CL_CHECK(clSetKernelArg(ks, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(ks, 1, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(ks, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(ks, 3, sizeof(cl_mem), &partial)); + CL_CHECK(clSetKernelArg(ks, 4, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(ks, 5, sizeof(cl_int), &ne01)); + size_t lsk[3] = { 64, (size_t) nsg, 1 }; + size_t gsk[3] = { gx, (size_t) (nsg * ksplit), 1 }; + backend_ctx->enqueue_ndrange_kernel(ks, 3, gsk, lsk, dst); + + cl_kernel kr = backend_ctx->mul_mat.kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(kr, 0, sizeof(cl_mem), &partial)); + CL_CHECK(clSetKernelArg(kr, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kr, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kr, 3, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kr, 4, sizeof(cl_int), &ksplit)); + size_t lr[3] = { 64, 1, 1 }; + size_t gr[3] = { (size_t) CEIL_DIV(ne01, 64) * 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kr, 3, gr, lr, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q8_0_f32; + + int r2 = 1; + int r3 = 1; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &r3)); + + size_t wavesize = backend_ctx->adreno_wave_size; + size_t local_work_size[] = { wavesize, 4, 1 }; + size_t global_work_size[] = { CEIL_DIV(M, wavesize)*wavesize, 4, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } else { + static const char * q8_bin_dp4a_env = getenv("GGML_OPENCL_Q8_0_BIN_DP4A"); + const bool q8_bin_dp4a_on = backend_ctx->has_integer_dot && + (q8_bin_dp4a_env ? (atoi(q8_bin_dp4a_env) != 0) : true); + + if (q8_bin_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin + && M % 64 == 0) { + cl_mem a_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const size_t n_blocks = (size_t)N * (K / 32); + + const size_t N_pad = ((size_t)N + 31) / 32 * 32; + const size_t n_blocks_pad = N_pad * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N_pad * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks_pad * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_pad * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_mem q_img = nullptr; + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * (size_t)K / 4; + img_desc.buffer = extra0_q8_0->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + cl_mem d_sub_buf = nullptr; + cl_mem d_img = nullptr; + region.origin = extrad->offset; + region.size = (size_t)M * N * sizeof(float); + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub_buf; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + cl_kernel dk = backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_ila_a8_bin; + cl_uint ne00_u = (cl_uint)K; + cl_uint ne01_u = (cl_uint)M; + CL_CHECK(clSetKernelArg(dk, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(dk, 1, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(dk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, 4, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(dk, 5, sizeof(cl_uint), &ne00_u)); + CL_CHECK(clSetKernelArg(dk, 6, sizeof(cl_uint), &ne01_u)); + CL_CHECK(clSetKernelArg(dk, 7, sizeof(int), &N)); + + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + CL_CHECK(clReleaseMemObject(a_sub)); + return; + } + + // dp4a dense q8_0 prefill GEMM. Quantizes the [N,K] activations to + // q8_1 and runs the int8 dot instead of the f16 half-dot. Large-batch + // (ne1>8) only; q8_0 weights are already int8 (no requant) and symmetric + // (no min term) + static const char * q8_dense_dp4a_env = getenv("GGML_OPENCL_Q8_DENSE_DP4A"); + static const char * q8_dense_wimg_env = getenv("GGML_OPENCL_Q8_DENSE_DP4A_WIMG"); + const bool q8_dense_wimg_on = q8_dense_wimg_env && (atoi(q8_dense_wimg_env) != 0); + + const bool q8_bin_loaded = (backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_bin != nullptr); + // bin kernel takes precedence + bool q8_dense_dp4a_on = q8_dense_wimg_on + ? true + : q8_dense_dp4a_env + ? (atoi(q8_dense_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && !q8_bin_loaded); + // dot prod has to be available + q8_dense_dp4a_on = backend_ctx->has_integer_dot && q8_dense_dp4a_on; + + if (q8_dense_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a + && N > 8 && (K % 32 == 0) && (M % 64 == 0)) { + cl_mem a_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((a_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const size_t n_blocks = (size_t)N * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &a_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + // optional weight texture, the same CL_R/UINT32 view, width M*K/4 + cl_mem q8_q_img = nullptr; + bool use_wimg = q8_dense_wimg_on; + if (use_wimg) { + const size_t tex = (size_t)M * (size_t)K / 4; // uint32 texels + if (tex == 0 || tex > backend_ctx->image_max_buffer_size) { + use_wimg = false; + } else { + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = tex; + img_desc.buffer = extra0_q8_0->q; + q8_q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err); + if (err != CL_SUCCESS || q8_q_img == nullptr) { use_wimg = false; q8_q_img = nullptr; } + } + } + + static const char * q8_0_act_vload4_env = getenv("GGML_OPENCL_Q8_0_DP4A_ACT_VLOAD4"); + const bool q8_0_act_vload4_on = q8_0_act_vload4_env == nullptr || atoi(q8_0_act_vload4_env) != 0; + cl_kernel dk = use_wimg + ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_wimg + : q8_0_act_vload4_on + ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a_act_vload4 + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_q8_1_dp4a; + int ai = 0; + if (use_wimg) { + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &q8_q_img)); + } else { + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q8_0->q)); + } + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + if (q8_q_img != nullptr) { + CL_CHECK(clReleaseMemObject(q8_q_img)); + } + CL_CHECK(clReleaseMemObject(a_sub)); + return; + } + + const bool have_a8 = (backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_bin != nullptr); + + if (!have_a8 && backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin && M >= 64) { + const int gemm_tile_n = 32; + int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; + + cl_mem a_img_a7 = nullptr; + cl_mem b_src_sub = nullptr; + cl_mem b_pad_sub = nullptr; + cl_mem b_buf = nullptr; + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * K / 4; + img_desc.buffer = extra0_q8_0->q; + CL_CHECK((a_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + if (N_pad == N) { + b_buf = b_src_sub; + } else { + size_t padded_bytes = (size_t)K * N_pad * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); + region.origin = 0; + region.size = padded_bytes; + CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const float b_pad_zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), + 0, padded_bytes, 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + b_buf = b_pad_sub; + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N_pad; + img_desc.buffer = b_buf; + cl_mem b_img_a7; + CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + const int c_offset_for_kernel = (int)offsetd; + + int line_stride_B = K * (int)sizeof(float); + int line_stride_C = M * (int)sizeof(float); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_32b_trans_ila_a7_bin; + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &a_img_a7)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 4 }; + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + size_t global_y = ((m_tiles + 1) / 2) * 2; + size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(a_img_a7)); + CL_CHECK(clReleaseMemObject(b_img_a7)); + if (b_src_sub) { + CL_CHECK(clReleaseMemObject(b_src_sub)); + } + if (b_pad_sub) { + CL_CHECK(clReleaseMemObject(b_pad_sub)); + } + return; + } + + // use bin kernel if available + if (backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_bin) { + int K_pad = K; + + cl_mem b_sub_buf = nullptr; + cl_mem d_sub_buf = nullptr; + + cl_mem a_img = nullptr; + cl_mem s_img = nullptr; + cl_mem b_img = nullptr; + cl_mem d_img = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K_pad * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // Create subbuffer and image1d_buffer for dst + region.origin = (extrad->offset); // + dst->view_offs; + region.size = M * N * sizeof(float); + CL_CHECK((d_sub_buf = clCreateSubBuffer((extrad->data_device), 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // create an image for A + img_fmt = { CL_R, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 4; // Divide by 4 for char -> float + img_desc.buffer = extra0_q8_0->q; + CL_CHECK((a_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // create an image for Scale + img_fmt = { CL_R, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 32; // Block size is 32 + img_desc.buffer = extra0_q8_0->d; + CL_CHECK((s_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // create an image for B from sub_buffer + img_fmt = {CL_R, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K_pad * N; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // img for d + img_fmt = {CL_R, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * N; + img_desc.buffer = d_sub_buf; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32_bin; + + bool layoutA_Mfirst = true; + bool layoutS_Mfirst = true; + bool layoutB_Nfirst = false; + bool layoutC_Mfirst = true; + + cl_uint lineStrideMatrixAinBytes = layoutA_Mfirst ? M * 4 : K; // int8 + cl_uint lineStrideMatrixSinBytes = layoutS_Mfirst ? M * 2 : (K / 32) * 2; // fp16 + cl_uint lineStrideMatrixBinBytes = layoutB_Nfirst ? N * 4 : K_pad * 4; // fp32 + cl_uint lineStrideMatrixCinBytes = layoutC_Mfirst ? M * 4 : N * 4; // fp32 + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &a_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &s_img)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &extra1->offset)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &extrad->offset)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &lineStrideMatrixAinBytes)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &lineStrideMatrixSinBytes)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &lineStrideMatrixBinBytes)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &lineStrideMatrixCinBytes)); + + size_t global_work_size[] = { 64, (size_t)CEIL_DIV(M, 64), (size_t)CEIL_DIV(N, 64)}; + size_t local_work_size[] = { 64, 2, 2 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + CL_CHECK(clReleaseMemObject(a_img)); + CL_CHECK(clReleaseMemObject(s_img)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(d_img)); + return; + } + + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q8_0_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q8_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(N, 8), (size_t)CEIL_DIV(M, 4), 1 }; + size_t local_work_size[] = { 2, 128, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static bool ggml_cl_coopk_c8_image( + ggml_backend_opencl_context * backend_ctx, + ggml_cl_buffer & buffer, + size_t bytes, + cl_mem & image, + cl_mem & image_buffer, + size_t & image_bytes +) { + if (bytes / 16 > backend_ctx->image_max_buffer_size) { + return false; + } + if (image != nullptr && image_buffer == buffer.buffer && image_bytes >= bytes) { + return true; + } + if (image != nullptr) { + CL_CHECK(clReleaseMemObject(image)); + image = nullptr; + } + + image_buffer = nullptr; + image_bytes = 0; + + cl_image_format format = {CL_RGBA, CL_UNSIGNED_INT32}; + cl_image_desc desc = {}; + desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + desc.image_width = bytes / 16; + desc.buffer = buffer.buffer; + + cl_int err; + image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &format, &desc, nullptr, &err); + if (err != CL_SUCCESS) { + image = nullptr; + return false; + } + + image_buffer = buffer.buffer; + image_bytes = bytes; + return true; +} + +static int ggml_cl_coopk_ksplit(const ggml_backend_opencl_context * backend_ctx, int base_wg, int n_blocks) { + const int cu = MAX(1, (int) backend_ctx->fa.compute_units); + int ksplit = 1; + float best_eff = 0.0f; + for (int k = 1; k <= MIN(8, n_blocks); ++k) { + const int wg = base_wg * k; + const int waves = CEIL_DIV(wg, cu); + const float eff = (float) wg / (waves * cu); + if (eff > best_eff + 0.06f) { + best_eff = eff; + ksplit = k; + } + } + return ksplit; +} + +static void ggml_cl_mul_mat_q4_k_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q4_K * extra0_q4_k = (ggml_tensor_extra_cl_q4_K *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + const int coopk_c8_min_n = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 2 : 5; + if (backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8 != nullptr && + N >= coopk_c8_min_n && N <= 8 && M > 0 && K > 0 && M % 256 == 0 && K % 256 == 0 && + src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && + K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && + src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && + src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && + ggml_is_contiguous(src1) && ggml_is_contiguous(dst) + ) { + const int kb = K / 32; + const size_t qa_bytes = (size_t) 8 * K; + const size_t ds_bytes = (size_t) 16 * kb * sizeof(cl_half); + + backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); + backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); + + if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, + backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && + ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, + backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) + ) { + const int n_blocks = N * kb; + + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1_k4; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); + CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); + + size_t quant_local[] = {64}; + size_t quant_global[] = {(size_t) 8 * kb}; + backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); + + int ksplit = ggml_cl_coopk_ksplit(backend_ctx, M / 256, kb); + if (backend_ctx->mul_mat.kernel_gemv_splitk_reduce_f32 == nullptr) { + ksplit = 1; + } + + cl_mem out = extrad->data_device; + cl_ulong out_offset = offsetd; + + if (ksplit > 1) { + backend_ctx->prealloc_splitk_partial.allocate(context, (size_t) ksplit * M * N * sizeof(float)); + out = backend_ctx->prealloc_splitk_partial.buffer; + out_offset = 0; + } + + const cl_uchar mask_d6 = 0x3F; + const cl_uchar mask_d4 = 0x0F; + const cl_uchar mask_hi2 = 0xC0; + + const size_t nsg = backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k_bin_c8; + cl_kernel gemm = backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c8; + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q4_k->q)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(gemm, 12, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(gemm, 13, sizeof(cl_uchar), &mask_hi2)); + CL_CHECK(clSetKernelArg(gemm, 14, sizeof(int), &ksplit)); + + size_t local[] = {64, nsg, 1}; + size_t global[] = {(size_t) M / 4, nsg * ksplit, 1}; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + + if (ksplit > 1) { + const int rows = M * N; + cl_kernel reduce = backend_ctx->mul_mat.kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); + CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); + size_t reduce_local[] = {64}; + size_t reduce_global[] = {(size_t) CEIL_DIV(rows, 64) * 64}; + backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); + } + return; + } + } + + // CoopK handles with _bin use the bin weight layout (uint-transposed q), with K-major Q8_1 activations (K contiguous). + if (ne1 >= 2 && ne1 <= 4 && + ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->mul_mat.rows_coopk_dp4a_q4_k) && + backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4 != nullptr && + ((ne1 <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4) != nullptr) { + cl_mem b_sub_buf = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // Allocate all kernel columns; padded columns have independent accumulators and are not stored. + const int cols = (ne1 <= 2) ? 2 : 4; + const size_t size_qa = (size_t)cols * K * sizeof(cl_char); + const size_t n_blocks_padded = (size_t)cols * (K / 32); + const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; + const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; + backend_ctx->prealloc_moe_qa.allocate(context, size_qa); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); + if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { + const cl_char z8 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, + &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); + } + if (backend_ctx->prealloc_moe_da.size != size_da_prev) { + const cl_half z16 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); + } + + cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); + cl_kernel kernel_quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); + size_t local_work_size_quant[1] = { 64 }; + size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); + + cl_kernel kernel_coopk = (ne1 <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_bin_c4; + const int nsg_selected = (ne1 <= 2) ? backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k_bin_c2 + : backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k_bin_c4; + const cl_uchar mask_d6 = 0x3F, mask_d4 = 0x0F, mask_hi2 = 0xC0; + const cl_int n_padded = cols; + CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q4_k->q)); + CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel_coopk, 10, sizeof(cl_int), &n_padded)); + CL_CHECK(clSetKernelArg(kernel_coopk, 11, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel_coopk, 12, sizeof(cl_int), &ne1)); + CL_CHECK(clSetKernelArg(kernel_coopk, 13, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(kernel_coopk, 14, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(kernel_coopk, 15, sizeof(cl_uchar), &mask_hi2)); + + // Each width can compile with a different subgroup count. + const size_t nsg = (size_t)nsg_selected; + size_t local_work_size[3] = { 64, nsg, 1 }; + size_t global_work_size[3] = { (size_t)(ne01 / backend_ctx->mul_mat.rows_coopk_dp4a_q4_k), nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + if (ne1 == 1) { + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_RGBA, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_32b_trans; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); + + size_t local_work_size[3] = { 64, 8, 1 }; + size_t global_work_size[3] = { (size_t)ne01, 8, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + const int gemm_tile_n = 64; + int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; + + const bool have_a8 = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin != nullptr; + + static const char * q4_k_bin_dp4a_env = getenv("GGML_OPENCL_Q4_K_BIN_DP4A"); + bool q4_k_bin_dp4a_on = q4_k_bin_dp4a_env + ? (atoi(q4_k_bin_dp4a_env) != 0) + : true; + // dot prod has to be available + q4_k_bin_dp4a_on = backend_ctx->has_integer_dot && q4_k_bin_dp4a_on; + + if (q4_k_bin_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin) { + const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; + const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); + + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_mem b_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_int tb = (cl_int)((size_t)N * (K / 32)); + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_mem d_sub = nullptr; + cl_mem d_img = nullptr; + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_ila_a8_bin; + + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_int), &N)); + + size_t local_work_size[3] = { 64, 1, 1 }; + size_t global_work_size[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub)); + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub)); + return; + } + + if (!have_a8) { + cl_mem b_src_sub = nullptr; + cl_mem b_pad_sub = nullptr; + cl_mem b_buf = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + if (N_pad == N) { + b_buf = b_src_sub; + } else { + size_t padded_bytes = (size_t)K * N_pad * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); + region.origin = 0; + region.size = padded_bytes; + CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const float b_pad_zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), + 0, padded_bytes, 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + b_buf = b_pad_sub; + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N_pad; + img_desc.buffer = b_buf; + cl_mem b_img_a7; + CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + const int c_offset_for_kernel = (int)offsetd; + + int line_stride_B = K * (int)sizeof(float); + int line_stride_C = M * (int)sizeof(float); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a7_bin; + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 4 }; + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + size_t global_y = ((m_tiles + 1) / 2) * 2; + size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img_a7)); + if (b_src_sub) { + CL_CHECK(clReleaseMemObject(b_src_sub)); + } + if (b_pad_sub) { + CL_CHECK(clReleaseMemObject(b_pad_sub)); + } + return; + } + + cl_mem b_sub_buf = nullptr; + cl_mem b_padded = nullptr; + cl_mem b_buf = nullptr; + if (N_pad == N) { + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + b_buf = b_sub_buf; + } else { + CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, (size_t)K * N_pad * sizeof(float), NULL, &err), err)); + const float zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + b_buf = b_padded; + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N_pad; + img_desc.buffer = b_buf; + cl_mem b_img; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + cl_mem d_sub_buf; + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub_buf; + cl_mem d_img; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_32b_trans_ila_a8_bin; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 2 }; + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img)); + if (b_sub_buf) { + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } + if (b_padded) { + CL_CHECK(clReleaseMemObject(b_padded)); + } + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_q4_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q4_K * extra0_q4_k = (ggml_tensor_extra_cl_q4_K *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + cl_uchar mask_d6 = 0x3F; + cl_uchar mask_d4 = 0x0F; + cl_uchar mask_hi2 = 0xC0; + + // Multi-column verify GEMV + static const bool q4k_mc3 = (getenv("GGML_OPENCL_Q4_K_MC3") != nullptr); + const bool use_mc3 = q4k_mc3 && (ne1 == 3) && (ne01 < 32768); + + const bool use_bin = use_q4_k_bin_kernels(backend_ctx, src0); + + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_coopmat, + { extra0_q4_k->q, extra0_q4_k->s, extra0_q4_k->d, extra0_q4_k->dm }, src1, dst, K, M, N)) { + return; + } + + if (use_bin) { + if (use_mc3) { + static bool warned = false; + if (!warned) { + GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q4_K_MC3 is bypassed by Q4_K binary kernels\n"); + warned = true; + } + } + ggml_cl_mul_mat_q4_k_f32_adreno_ila(backend, src0, src1, dst); + return; + } + + if (ne1 == 1 || use_mc3) { + cl_mem q_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + const bool use_tiled = !use_mc3 && use_q4k_tiled(backend_ctx, src0); + + // image for q (not needed for the tiled path, which reads __global) + if (!use_tiled) { + img_fmt = { CL_R, CL_UNSIGNED_INT32}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_q4_k->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + } + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // 4-output-per-WI o4 variant for the long-vocab lm_head/embed GEMV + // (ne01 = vocab ~256K on Gemma): shares one activation read across 4 + // output rows. Gated to large ne01 (lm_head/embed). Default on; opt-out + // GGML_OPENCL_Q4K_GEMV_O4=0. (Skipped when mc3 handles the ne1==3 verify.) + static const bool q4k_o4_env = []{ + const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_O4"); + return !e || e[0] == '\0' || e[0] != '0'; + }(); + const bool use_q4k_o4 = !use_tiled && !use_mc3 && q4k_o4_env && (ne01 % 4 == 0) && (ne01 >= 32768); + // Split-K across workgroups for small-M decode GEMVs. A single-token GEMV + // makes only CEIL_DIV(M/2,64) workgroups; even with the wide intra-WG split + // (16 subgroups) those all land on ONE CU, so small-M matmuls under-fill the + // 16 CUs and their bandwidth falls well short of what the large-M FFN matmuls + // reach. Adding a `ksplit` second grid dim that spreads K across WGs (+ a + // reduce pass) fills the CUs. Gate is M<=2560: the tiny M<=1024 ones only + // break even (the reduce dispatch eats the kernel win), but the big-K M=2560 + // cases (ffn_down, attn_output) make the per-call win dwarf the reduce, and + // are byte-identical. ffn_gate/up (large M) fill the CUs already and are excluded. + // + // DEVICE-GATED. Split-K buys GPU time by spending an extra kernel LAUNCH (the + // reduce), so it only pays where launches are cheap. That is a per-device + // property and it does not travel from the X2-90 this was tuned on. Measured + // with one binary, env A/B (tg32, GGML_OPENCL_Q4K_GEMV_SPLITK=0/1): + // + // X2-90 +3.36% gemma-4 E4B (the number this gate was built on) + // 840 -1.3% Qwen3.5-4B-Q4_K_M 14.00 -> 13.85 + // 850 -20.0% Qwen3-1.7B-Q4_K_M 6.97 -> 5.58 (6 interleaved reps) + // + // The kernel is not the problem. On the 850 split-K makes the GPU strictly + // faster -- total busy 537 -> 485 ms, this GEMV 43.7 -> 34.0 us/call (-22%) -- + // and still costs a fifth of decode, because the +3696 reduce dispatches cost + // ~550 us of HOST round-trip each against 2.7 us of GPU work (~200x; that part + // is ~95% host-bound at decode). The 840 pays the same tax at ~42 us/dispatch. + // Break-even needs launch cost below the ~9.7 us/call the split actually saves, + // so this is not a "the 850 is slow" adjustment that a faster part would fix -- + // the 840 is 13x cheaper per launch and still loses. + // + // Enabled where it is measured to win, i.e. X2E only. The X1-85 was measured + // afterwards and is NOT a win either: Qwen3.5-4B-Q4_K_M tg32, split-K off + // 17.98/18.10/18.19 vs on 18.03/17.91/17.97 = -0.7%, so X1E stays excluded on + // evidence rather than on absence of it. Do not widen this without a NEW + // measurement. The env still forces either way so every device stays measurable. + static const bool splitk_env_set = []{ + const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_SPLITK"); + return e && e[0] != '\0'; + }(); + static const bool splitk_env_on = []{ + const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_SPLITK"); + return !(e && e[0] == '0'); + }(); + const bool splitk_wg_env = splitk_env_set + ? splitk_env_on + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + // Gate: small-M decode GEMVs that under-fill the 16 CUs even with the wide + // intra-WG split (all 16 subgroups land on one CU). M<=2560 covers Kcur/Vcur + // (M=1024), Qcur (2048), attn_output + ffn_down (2560). The tiny ones + // (M<=1024) only break even (reduce dispatch eats the kernel win), but the + // big-K M=2560 cases (ffn_down K=10240 @182us, attn_output @42us) have a + // large per-call win that dwarfs the ~5us reduce, so extending to 2560 nets + // positive end-to-end. ffn_gate/up (M=10240) already fill the CUs -> excluded. + const bool use_splitk = splitk_wg_env && !use_tiled && !use_q4k_o4 && !use_mc3 && ne01 <= 2560; + + if (use_splitk) { + const int nsg = 8; + const int ksplit = (ne01 <= 512) ? 8 : 4; // -> ~32 total WGs + const size_t gx = (size_t)CEIL_DIV(ne01/2, 64) * 64; + + backend_ctx->prealloc_splitk_partial.allocate( + backend_ctx->context, (size_t)ksplit * ne01 * sizeof(float)); + cl_mem partial = backend_ctx->prealloc_splitk_partial.buffer; + + cl_kernel ks = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_splitk; + CL_CHECK(clSetKernelArg(ks, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(ks, 1, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(ks, 2, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(ks, 3, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(ks, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(ks, 5, sizeof(cl_mem), &partial)); + CL_CHECK(clSetKernelArg(ks, 6, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(ks, 7, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(ks, 8, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(ks, 9, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(ks, 10, sizeof(cl_uchar), &mask_hi2)); + size_t lsk[3] = {64, (size_t)nsg, 1}; + size_t gsk[3] = {gx, (size_t)(nsg * ksplit), 1}; + backend_ctx->enqueue_ndrange_kernel(ks, 3, gsk, lsk, dst); + + cl_kernel kr = backend_ctx->mul_mat.kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(kr, 0, sizeof(cl_mem), &partial)); + CL_CHECK(clSetKernelArg(kr, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kr, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kr, 3, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kr, 4, sizeof(cl_int), &ksplit)); + size_t lr[3] = {64, 1, 1}; + size_t gr[3] = {(size_t)CEIL_DIV(ne01, 64) * 64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kr, 3, gr, lr, dst); + + if (q_img) CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + return; + } + + kernel = use_mc3 ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_mc3 + : use_tiled ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_tiled + : use_q4k_o4 ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_o4 + : backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32; + + if (use_tiled) { + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); + } else { + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_uchar), &mask_hi2)); + } + + // Wide K-split for the decode GEMV: the default 4-subgroup K-split leaves + // each Adreno SP with only ~4 waves, too few to hide LPDDR weight-load + // latency, so even the large FFN matmuls run well below the achievable + // bandwidth. Widen to 16 subgroups/WG (= the 1024-lane Adreno WG max) so + // each SP holds enough in-flight memory requests. Prefill is unaffected (the + // GEMM path is separate) and coherence-identical (greedy output unchanged). + // Applies to the plain base + // GEMV only; tiled/o4/mc3 keep 4 (their reductions are hard-coded to 4). + // Layout-safe: the base kernel derives its K-split from get_local_size(1) + // and the packed block stride is a physical constant (independent of it). + // Opt-out: GGML_OPENCL_Q4K_GEMV_WIDE=0. + static const bool splitk_wide_env = []{ + const char * e = std::getenv("GGML_OPENCL_Q4K_GEMV_WIDE"); + return !e || e[0] == '\0' || e[0] != '0'; + }(); + const bool splitk_wide = splitk_wide_env && !use_tiled && !use_q4k_o4 && !use_mc3; + size_t nsg_y = splitk_wide ? 16 : 4; + // Cap the wide K-split by the kernel's real max WG. X1-class drivers cap + // this GEMV at 768 (< 64*16 = 1024), so an uncapped lws aborts the + // dispatch with CL_INVALID_WORK_GROUP_SIZE (-54) and breaks ALL q4_K + // decode for M>2560. nsg_y is a pure K-split (the base kernel reads it + // from get_local_size(1); the packed block stride is a physical constant), + // so halving it stays coherent - just a narrower split. X2 keeps 16 + // (maxwg 1024); X1 falls to 8. + if (splitk_wide) { + const size_t maxwg = backend_ctx->get_kernel_workgroup_size(kernel); + while (nsg_y > 4 && 64 * nsg_y > maxwg) { nsg_y >>= 1; } + } + size_t local_work_size[3] = {64, nsg_y, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(use_tiled ? ne01 : (use_q4k_o4 ? ne01/4 : ne01/2), 64)*64, nsg_y, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + if (q_img) CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // Only the tiled kernels can read the tiled layout (use_q4k_tiled). + if (use_q4k_tiled(backend_ctx, src0)) { + const size_t n_blocks = (size_t)N * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tbq = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tbq)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_kernel dk = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_K_f32_tiled_dp4a; + CL_CHECK(clSetKernelArg(dk, 0, sizeof(cl_mem), &extra0_q4_k->q)); + CL_CHECK(clSetKernelArg(dk, 1, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(dk, 2, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(dk, 3, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(dk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, 9, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(dk, 10, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(dk, 11, sizeof(cl_int), &ne1)); + + const int WROWS_D = 4 * 64; + const int BN_DP = 8; + size_t dlocal[3] = {64, 4, 1}; + size_t dglobal[3] = {(size_t)CEIL_DIV(ne01, WROWS_D) * 64, 4, (size_t)CEIL_DIV(ne1, BN_DP)}; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dglobal, dlocal, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + // CoopK handles without _bin use the same untiled weight layout as gemm_noshuffle_q4_k_f32. + // Activations use K-major Q8_1 SoA (K contiguous). + if (ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->mul_mat.rows_coopk_dp4a_q4_k) + && backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_c4 != nullptr + && ((N <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_c4) != nullptr) { + const int cols = (N <= 2) ? 2 : 4; + const size_t size_qa = (size_t)cols * K * sizeof(cl_char); + const size_t n_blocks_padded = (size_t)cols * (K / 32); + const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; + const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; + backend_ctx->prealloc_moe_qa.allocate(context, size_qa); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); + if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { + const cl_char z8 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, + &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); + } + if (backend_ctx->prealloc_moe_da.size != size_da_prev) { + const cl_half z16 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); + } + + cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); + cl_kernel kernel_quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); + size_t local_work_size_quant[1] = { 64 }; + size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); + + cl_kernel kernel_coopk = (N <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q4_k_q8_1_dp4a_c4; + const cl_uchar mask_d6 = 0x3F, mask_d4 = 0x0F, mask_hi2 = 0xC0; + const cl_int n_padded = cols; + CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q4_k->q)); + CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(kernel_coopk, 10, sizeof(cl_int), &n_padded)); + CL_CHECK(clSetKernelArg(kernel_coopk, 11, sizeof(cl_int), &K)); + CL_CHECK(clSetKernelArg(kernel_coopk, 12, sizeof(cl_int), &N)); + CL_CHECK(clSetKernelArg(kernel_coopk, 13, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(kernel_coopk, 14, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(kernel_coopk, 15, sizeof(cl_uchar), &mask_hi2)); + + const size_t nsg = (size_t)backend_ctx->mul_mat.nsg_coopk_dp4a_q4_k; + size_t local_work_size[3] = { 64, nsg, 1 }; + size_t global_work_size[3] = { (size_t)(M / backend_ctx->mul_mat.rows_coopk_dp4a_q4_k), nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // transpose activations + int height_B = N/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = K/4; + int padded_height_B = (N + padding)/4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = { 1, 16 }; + size_t global_work_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // dp4a (int8) dense prefill GEMM and weight via texture + static const char * q4k_dense_dp4a_env = getenv("GGML_OPENCL_Q4K_DENSE_DP4A"); + static const char * q4k_dense_wimg_env = getenv("GGML_OPENCL_Q4K_DENSE_DP4A_WIMG"); + + const bool q4k_dense_wimg_on = q4k_dense_wimg_env && (atoi(q4k_dense_wimg_env) != 0); + bool q4k_dense_dp4a_on = q4k_dense_wimg_on + ? true + : q4k_dense_dp4a_env + ? (atoi(q4k_dense_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + + // dp4 has to be available + q4k_dense_dp4a_on = backend_ctx->has_integer_dot && q4k_dense_dp4a_on; + + // Min N for the dp4a prefill GEMM, default 9, i.e., ne1 > 8 + static const char * q4k_dp4a_minn_env = getenv("GGML_OPENCL_Q4K_DP4A_MINN"); + const int q4k_dp4a_minn = q4k_dp4a_minn_env ? atoi(q4k_dp4a_minn_env) : 9; + + if (q4k_dense_dp4a_on && N >= q4k_dp4a_minn && (K % 32 == 0) && (M % 64 == 0)) { + const size_t n_blocks = (size_t)N * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + // check if weights go through texture + cl_mem q4k_q_img = nullptr; + bool use_wimg = q4k_dense_wimg_on; + if (use_wimg) { + const size_t tex = (size_t)M * (size_t)K / 8; // uint32 texels = bytes/4 + if (tex == 0 || tex > backend_ctx->image_max_buffer_size) { + use_wimg = false; + } else { + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = tex; + img_desc.buffer = extra0_q4_k->q; + q4k_q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err); + if (err != CL_SUCCESS || q4k_q_img == nullptr) { + use_wimg = false; + q4k_q_img = nullptr; + } + } + } + + const bool use_narrow = backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow != nullptr + && N <= backend_ctx->max_n_dp4a_narrow_q4_k; + static const char * q4_k_act_vload4_env = getenv("GGML_OPENCL_Q4_K_DP4A_ACT_VLOAD4"); + const bool q4_k_act_vload4_on = q4_k_act_vload4_env == nullptr || atoi(q4_k_act_vload4_env) != 0; + cl_kernel dk = use_narrow + ? (use_wimg ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow_wimg + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_narrow) + : use_wimg + ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_wimg + : q4_k_act_vload4_on + ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a_act_vload4 + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_q8_1_dp4a; + int ai = 0; + if (use_wimg) { + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &q4k_q_img)); + } else { + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->q)); + } + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_hi2)); + const int tile_n = use_narrow ? backend_ctx->tile_n_dp4a_narrow_q4_k : backend_ctx->tile_n_dp4a_q4_k; + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, tile_n) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + if (q4k_q_img != nullptr) { + CL_CHECK(clReleaseMemObject(q4k_q_img)); + } + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + return; + } + + // gemm + // Small-batch (medium n_q) occupancy fix: at ne1<=8 the 2x8 grid is + // (1, ceil(M/2)) -> ~M/256 workgroups, which under-occupies the SP and + // makes the GEMM much slower than the ne1==1 GEMV at the same weight + // traffic. The _r1 (1-row) kernel doubles the M-axis workgroup count + // and removes the accumulator spill. Opt-in via env while validating. + static const bool q4k_gemm_r1 = (getenv("GGML_OPENCL_Q4K_GEMM_R1") != nullptr); + static const bool q4k_gemm_kimg = (getenv("GGML_OPENCL_Q4K_GEMM_KIMG") != nullptr); + // Cooperative-K (intra-WG K-split + reduction) for the small-batch + // (n_q in [2..8]) path: DEFAULT ON, opt out with GGML_OPENCL_Q4K_GEMM_COK=0. + // Byte-identical greedy output; large-batch (ne1>8) untouched. + static const char * q4k_cok_env = getenv("GGML_OPENCL_Q4K_GEMM_COK"); + static const bool q4k_gemm_cok = (q4k_cok_env == nullptr) || (atoi(q4k_cok_env) != 0); + const bool use_cok = q4k_gemm_cok && (ne1 <= 8); + const bool use_r1 = !use_cok && q4k_gemm_r1 && (ne1 <= 8); + // Weights-as-image (L1/TPL1) for the small-batch weight-read-bound path. + const bool use_kimg = !use_cok && !use_r1 && q4k_gemm_kimg && (ne1 <= 8); + + cl_mem q_img = nullptr; + if (use_kimg) { + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_q4_k->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + } + + kernel = use_cok ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_cok + : use_r1 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_r1 + : use_kimg ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32_kimg + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q4_k_f32; + int padded_N = N + padding; + + if (use_kimg) { + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + } else { + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_k->q)); + } + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_k->s)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q4_k->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q4_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_uchar), &mask_hi2)); + + size_t global_work_size[3]; + size_t local_work_size[3]; + if (use_cok) { + // (COK_SG lanes x COK_NSG subgroups): one row per lane, K split + // across the COK_NSG subgroups. ne01 is a multiple of 64. + global_work_size[0] = (size_t)ne01; // rows + global_work_size[1] = 8; // COK_NSG + global_work_size[2] = 1; + local_work_size[0] = 64; // COK_SG + local_work_size[1] = 8; // COK_NSG + local_work_size[2] = 1; + } else if (use_r1) { + // 1 row per WI (opt-in occupancy experiment). + global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); + global_work_size[1] = (size_t)ne01; + global_work_size[2] = 1; + local_work_size[0] = 1; + local_work_size[1] = 128; + local_work_size[2] = 1; + } else if (use_kimg) { + // kimg is a 2-row tile (opt-in weights-as-image experiment). + global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); + global_work_size[1] = (size_t)CEIL_DIV(ne01, 2); + global_work_size[2] = 1; + local_work_size[0] = 1; + local_work_size[1] = 128; + local_work_size[2] = 1; + } else { + // Default: x2-unified base kernel is the 4-row (gx<<2) tile. + global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); + global_work_size[1] = (size_t)CEIL_DIV(ne01, 4); + global_work_size[2] = 1; + local_work_size[0] = 1; + local_work_size[1] = 128; + local_work_size[2] = 1; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + if (q_img) CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_mul_mat_q5_K_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl_q5_K * extra0_q5_k = (ggml_tensor_extra_cl_q5_K *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_buffer_region region; + cl_image_format img_fmt; + cl_image_desc img_desc; + + const int M = ne01; + const int N = ne1; + const int K = ne00; + + if (ne1 == 1) { + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_RGBA, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32_32b_trans; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_k->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne01)); + + size_t local_work_size[3] = { 64, 8, 1 }; + size_t global_work_size[3] = { (size_t)ne01, 8, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } else { + static const char * q5_k_bin_dp4a_env = getenv("GGML_OPENCL_Q5_K_BIN_DP4A"); + bool q5_k_bin_dp4a_on = q5_k_bin_dp4a_env + ? (atoi(q5_k_bin_dp4a_env) != 0) + : true; + // dot prod has to be available + q5_k_bin_dp4a_on = backend_ctx->has_integer_dot && q5_k_bin_dp4a_on; + + if (q5_k_bin_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin) { + const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; + const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); + + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_mem b_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_int tb = (cl_int)((size_t)N * (K / 32)); + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_mem d_sub = nullptr; + cl_mem d_img = nullptr; + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a_ila_a8_bin; + + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->qh)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->dm)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->s)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_int), &N)); + + size_t local_work_size_dp4a[3] = { 64, 1, 1 }; + size_t global_work_size_dp4a[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size_dp4a, local_work_size_dp4a, dst); + + CL_CHECK(clReleaseMemObject(b_sub)); + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub)); + return; + } + + const int gemm_tile_n = 64; + int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; + + const bool have_a8 = backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin != nullptr; + + if (!have_a8) { + cl_mem b_src_sub = nullptr; + cl_mem b_pad_sub = nullptr; + cl_mem b_buf = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + if (N_pad == N) { + b_buf = b_src_sub; + } else { + size_t padded_bytes = (size_t)K * N_pad * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); + region.origin = 0; + region.size = padded_bytes; + CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + const float b_pad_zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), + 0, padded_bytes, 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + b_buf = b_pad_sub; + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N_pad; + img_desc.buffer = b_buf; + cl_mem b_img_a7; + CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + const int c_offset_for_kernel = (int)offsetd; + + int line_stride_B = K * (int)sizeof(float); + int line_stride_C = M * (int)sizeof(float); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a7_bin; + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->qh)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->dm)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q5_k->s)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 4 }; + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + size_t global_y = ((m_tiles + 1) / 2) * 2; + size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img_a7)); + if (b_src_sub) { + CL_CHECK(clReleaseMemObject(b_src_sub)); + } + if (b_pad_sub) { + CL_CHECK(clReleaseMemObject(b_pad_sub)); + } + return; + } + + cl_mem b_sub_buf = nullptr; + cl_mem b_padded = nullptr; + cl_mem b_buf = nullptr; + if (N_pad == N) { + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + b_buf = b_sub_buf; + } else { + CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, (size_t)K * N_pad * sizeof(float), NULL, &err), err)); + const float zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + b_buf = b_padded; + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N_pad; + img_desc.buffer = b_buf; + cl_mem b_img; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + cl_mem d_sub_buf; + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub_buf; + cl_mem d_img; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_32b_trans_ila_a8_bin; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_k->q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_k->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 2 }; + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img)); + if (b_sub_buf) { + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } + if (b_padded) { + CL_CHECK(clReleaseMemObject(b_padded)); + } + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + } +} + +void ggml_cl_mul_mat_q5_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q5_K * extra0_q5_k = (ggml_tensor_extra_cl_q5_K *)src0->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + int M = ne01; + int N = ne1; + int K = ne00; + + cl_uchar mask_d6 = 0x3F; + cl_uchar mask_d4 = 0x0F; + cl_uchar mask_hi2 = 0xC0; + + // Multi-column (N=3) verify GEMV for q5_K: route the spec/MTP verify batch + // (ne1==3) onto the efficient GEMV path instead of the transposed-GEMM dead- + // zone (gemm_noshuffle_q5_k, the #2 chunk of MTP decode on a Q4_0-mix model + // after q4_0 mc3). Reuses the ne1==1 GEMV image setup (q + qh + activations). + // Default on for X2E, GGML_OPENCL_Q5_K_MC3=0/1 forces it. Per-layer only (ne01 < 32768). + static const char * q5k_mc3_env = getenv("GGML_OPENCL_Q5_K_MC3"); + const bool q5k_mc3 = q5k_mc3_env ? atoi(q5k_mc3_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E; + const bool use_q5k_mc3 = q5k_mc3 && (ne1 >= 2 && ne1 <= 4) && (ne01 < 32768); + + const bool use_bin = use_q5_k_bin_kernels(backend_ctx, src0); + + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32_coopmat, + { extra0_q5_k->q, extra0_q5_k->qh, extra0_q5_k->s, extra0_q5_k->d, extra0_q5_k->dm }, src1, dst, K, M, N)) { + return; + } + + if (use_bin) { + if (use_q5k_mc3) { + static bool warned = false; + if (!warned) { + GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q5_K_MC3 is bypassed by Q5_K binary kernels\n"); + warned = true; + } + } + ggml_cl_mul_mat_q5_K_f32_adreno_ila(backend, src0, src1, dst); + return; + } + + if (ne1 == 1 || use_q5k_mc3) { + cl_mem q_img = nullptr; + cl_mem qh_img = nullptr; + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + // image for q (CL_R, CL_UNSIGNED_INT32): width = M*K/2/4 + img_fmt = {CL_R, CL_UNSIGNED_INT32}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 2 / 4; + img_desc.buffer = extra0_q5_k->q; + CL_CHECK((q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // image for qh (CL_R, CL_HALF_FLOAT): width = M*K/16 + img_fmt = {CL_R, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = M * K / 16; + img_desc.buffer = extra0_q5_k->qh; + CL_CHECK((qh_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations (CL_RGBA, CL_FLOAT): width = K*N/4 + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = use_q5k_mc3 ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32_mc3 + : backend_ctx->mul_mat.kernel_gemv_noshuffle_q5_k_f32; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh_img)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_hi2)); + if (use_q5k_mc3) { + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_int), &ne1)); // n_cols + } + + size_t local_work_size[3] = {64, 4, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01/2, 64)*64, 4, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(q_img)); + CL_CHECK(clReleaseMemObject(qh_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + cl_mem b_sub_buf = nullptr; + cl_mem b_sub_buf_trans = nullptr; + cl_mem b_img = nullptr; + cl_mem b_img_trans = nullptr; + + // subbuffer for activations + region.origin = offset1; + region.size = K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for activations + img_fmt = {CL_RGBA, CL_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = N % 8; + int padding = 0; + if (extra_elements > 0) { + padding = 8 - extra_elements; + } + + // subbuffer for transposed activations + region.origin = 0; + region.size = K * (N + padding) * sizeof(float) / 2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activations + img_fmt = {CL_RGBA, CL_HALF_FLOAT}; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = K * (N + padding) / 4; + img_desc.buffer = b_sub_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // transpose activations + int height_B = N / 4; + if (height_B == 0) height_B = 1; + int width_B = K / 4; + int padded_height_B = (N + padding) / 4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_work_size_t[2] = {1, 16}; + size_t global_work_size_t[2] = {(size_t)width_B, (size_t)padded_height_B}; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size_t, local_work_size_t, dst); + + // dp4a (int8) dense q5_K prefill GEMM + static const char * q5k_dense_dp4a_env = getenv("GGML_OPENCL_Q5K_DENSE_DP4A"); + bool q5k_dense_dp4a_on = q5k_dense_dp4a_env + ? (atoi(q5k_dense_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + // dot prod has to be available + q5k_dense_dp4a_on = backend_ctx->has_integer_dot && q5k_dense_dp4a_on; + + if (q5k_dense_dp4a_on && ne1 > 8 && (ne00 % 32 == 0) && (ne01 % 64 == 0)) { + const int Mm = ne01, Nn = ne1, Kk = ne00; + const size_t n_blocks = (size_t)Nn * (Kk / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)Nn * Kk * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + static const char * q5_k_act_vload4_env = getenv("GGML_OPENCL_Q5_K_DP4A_ACT_VLOAD4"); + const bool q5_k_act_vload4_on = q5_k_act_vload4_env == nullptr || atoi(q5_k_act_vload4_env) != 0; + cl_kernel dk = q5_k_act_vload4_on + ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a_act_vload4 + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_q8_1_dp4a; + int ai = 0; + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->q)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->qh)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->s)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->d)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q5_k->dm)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &Mm)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &Nn)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &Kk)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_uchar), &mask_hi2)); + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(Mm / 64), (size_t)CEIL_DIV(Nn, 32) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + return; + } + + // gemm + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q5_k_f32; + int padded_N = N + padding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q5_k->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q5_k->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q5_k->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q5_k->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0_q5_k->dm)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_uchar), &mask_hi2)); + + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne1, 8), (size_t)CEIL_DIV(ne01, 4), 1}; + size_t local_work_size[3] = {1, 128, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_mul_mat_q6_K_f32_adreno_ila(ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_buffer_region region; + cl_image_format img_fmt; + cl_image_desc img_desc; + + const int M = ne01; + const int N = ne1; + const int K = ne00; + + if (backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8 != nullptr && + N >= 2 && N <= 8 && M > 0 && K > 0 && M % 4 == 0 && K % 256 == 0 && + src0->ne[0] == K && src0->ne[1] == M && dst->ne[1] == N && + K <= INT_MAX / 8 && (int64_t) M * K / 8 <= INT_MAX && + src0->ne[2] == 1 && src0->ne[3] == 1 && src0->view_src == nullptr && + src1->ne[2] == 1 && src1->ne[3] == 1 && dst->ne[2] == 1 && dst->ne[3] == 1 && + ggml_is_contiguous(src1) && ggml_is_contiguous(dst) + ) { + const int kb = K / 32; + const size_t qa_bytes = (size_t)8 * K; + const size_t ds_bytes = (size_t)24 * kb * sizeof(cl_half); + + backend_ctx->prealloc_moe_qa.allocate(context, qa_bytes); + backend_ctx->prealloc_moe_da.allocate(context, ds_bytes); + + if (ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_qa, qa_bytes, + backend_ctx->coopk_c8_qa_image, backend_ctx->coopk_c8_qa_buffer, backend_ctx->coopk_c8_qa_image_bytes) && + ggml_cl_coopk_c8_image(backend_ctx, backend_ctx->prealloc_moe_da, ds_bytes, + backend_ctx->coopk_c8_ds_image, backend_ctx->coopk_c8_ds_buffer, backend_ctx->coopk_c8_ds_image_bytes) + ) { + const int n_blocks = N * kb; + + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1_k4h; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(int), &n_blocks)); + CL_CHECK(clSetKernelArg(quant, 5, sizeof(int), &kb)); + + size_t quant_local[] = {64}; + size_t quant_global[] = {(size_t)8 * kb}; + backend_ctx->enqueue_ndrange_kernel(quant, 1, quant_global, quant_local, dst); + + int ksplit = ggml_cl_coopk_ksplit(backend_ctx, CEIL_DIV(M / 4, 64), kb); + if (backend_ctx->mul_mat.kernel_gemv_splitk_reduce_f32 == nullptr) { + ksplit = 1; + } + + cl_mem out = extrad->data_device; + cl_ulong out_offset = offsetd; + + if (ksplit > 1) { + backend_ctx->prealloc_splitk_partial.allocate(context, (size_t)ksplit * M * N * sizeof(float)); + out = backend_ctx->prealloc_splitk_partial.buffer; + out_offset = 0; + } + + const cl_uchar mask_c0 = 0xC0; + + const size_t nsg = backend_ctx->mul_mat.nsg_coopk_dp4a_q6_k_bin_c8; + cl_kernel gemm = backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_bin_c8; + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->coopk_c8_qa_image)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->coopk_c8_ds_image)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &out_offset)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &N)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(cl_uchar), &mask_c0)); + CL_CHECK(clSetKernelArg(gemm, 12, sizeof(int), &ksplit)); + + size_t local[] = {64, nsg, 1}; + size_t global[] = {(size_t)CEIL_DIV(M / 4, 64) * 64, nsg * ksplit, 1}; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + + if (ksplit > 1) { + const int rows = M * N; + cl_kernel reduce = backend_ctx->mul_mat.kernel_gemv_splitk_reduce_f32; + CL_CHECK(clSetKernelArg(reduce, 0, sizeof(cl_mem), &out)); + CL_CHECK(clSetKernelArg(reduce, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(reduce, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(reduce, 3, sizeof(int), &rows)); + CL_CHECK(clSetKernelArg(reduce, 4, sizeof(int), &ksplit)); + size_t reduce_local[] = {64}; + size_t reduce_global[] = {(size_t)CEIL_DIV(rows, 64) * 64}; + backend_ctx->enqueue_ndrange_kernel(reduce, 1, reduce_global, reduce_local, dst); + } + return; + } + } + + if (ne1 == 1) { + cl_mem b_sub_buf = nullptr; + cl_mem b_img = nullptr; + + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_RGBA, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_k_f32_32b_trans; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh_img)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); + + size_t local_work_size[3] = { 64, 8, 1 }; + size_t global_work_size[3] = { (size_t)ne01, 8, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } else { + const int gemm_tile_n = 64; + int N_pad = CEIL_DIV(N, gemm_tile_n) * gemm_tile_n; + + const bool have_a8 = backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin != nullptr; + + static const char * q6_k_bin_dp4a_env = getenv("GGML_OPENCL_Q6_K_BIN_DP4A"); + bool q6_k_bin_dp4a_on = q6_k_bin_dp4a_env + ? (atoi(q6_k_bin_dp4a_env) != 0) + : true; + // dot prod has to be available + q6_k_bin_dp4a_on = backend_ctx->has_integer_dot && q6_k_bin_dp4a_on; + + if (q6_k_bin_dp4a_on && backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin) { + const int dp4a_N_pad = CEIL_DIV(N, 32) * 32; + const size_t n_blocks = (size_t)dp4a_N_pad * (K / 32); + + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)dp4a_N_pad * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_mem b_sub = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_int tb = (cl_int)((size_t)N * (K / 32)); + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)CEIL_DIV(tb, 64) * 64 }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + cl_mem d_sub = nullptr; + cl_mem d_img = nullptr; + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + CL_CHECK((d_sub = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a_ila_a8_bin; + + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->ql_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &K)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &M)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 1, 1 }; + size_t global_work_size[3] = { 64, (size_t)(M / 64), (size_t)(dp4a_N_pad / 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub)); + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub)); + return; + } + + if (!have_a8) { + cl_mem b_src_sub = nullptr; + cl_mem b_pad_sub = nullptr; + cl_mem b_buf = nullptr; + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_src_sub = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + if (N_pad == N) { + b_buf = b_src_sub; + } else { + size_t padded_bytes = (size_t)K * N_pad * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(context, padded_bytes); + region.origin = 0; + region.size = padded_bytes; + CL_CHECK((b_pad_sub = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + const float b_pad_zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_pad_sub, &b_pad_zero, sizeof(float), + 0, padded_bytes, 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, b_src_sub, b_pad_sub, 0, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + b_buf = b_pad_sub; + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N_pad; + img_desc.buffer = b_buf; + cl_mem b_img_a7; + CL_CHECK((b_img_a7 = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + const int c_offset_for_kernel = (int)offsetd; + + int line_stride_B = K * (int)sizeof(float); + int line_stride_C = M * (int)sizeof(float); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a7_bin; + cl_uint k_arg = 0; + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->ql_img)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &b_img_a7)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &offset1)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &c_offset_for_kernel)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_B)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &line_stride_C)); + CL_CHECK(clSetKernelArg(kernel, k_arg++, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 4 }; + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + size_t global_y = ((m_tiles + 1) / 2) * 2; + size_t global_work_size[3] = { 64, global_y, (size_t)CEIL_DIV(N_pad, 32) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img_a7)); + if (b_src_sub) { + CL_CHECK(clReleaseMemObject(b_src_sub)); + } + if (b_pad_sub) { + CL_CHECK(clReleaseMemObject(b_pad_sub)); + } + return; + } + + cl_mem b_sub_buf = nullptr; + cl_mem b_padded = nullptr; + cl_mem b_buf = nullptr; + if (N_pad == N) { + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + b_buf = b_sub_buf; + } else { + CL_CHECK((b_padded = clCreateBuffer(context, CL_MEM_READ_WRITE, (size_t)K * N_pad * sizeof(float), NULL, &err), err)); + const float zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, b_padded, &zero, sizeof(zero), 0, (size_t)K * N_pad * sizeof(float), 0, NULL, NULL)); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, extra1->data_device, b_padded, offset1, 0, (size_t)K * N * sizeof(float), 0, NULL, NULL)); + b_buf = b_padded; + } + + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N_pad; + img_desc.buffer = b_buf; + cl_mem b_img; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + region.origin = offsetd; + region.size = (size_t)M * N * sizeof(float); + cl_mem d_sub_buf; + CL_CHECK((d_sub_buf = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + img_fmt = { CL_R, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * N; + img_desc.buffer = d_sub_buf; + cl_mem d_img; + CL_CHECK((d_img = clCreateImage(context, CL_MEM_WRITE_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_32b_trans_ila_a8_bin; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &d_img)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uint), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &N)); + + size_t local_work_size[3] = { 64, 2, 2 }; + size_t m_tiles = (size_t)CEIL_DIV(M, 64); + size_t global_work_size[3] = { 64, m_tiles, (size_t)CEIL_DIV(N_pad, gemm_tile_n) }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img)); + if (b_sub_buf) { + CL_CHECK(clReleaseMemObject(b_sub_buf)); + } + if (b_padded) { + CL_CHECK(clReleaseMemObject(b_padded)); + } + CL_CHECK(clReleaseMemObject(d_img)); + CL_CHECK(clReleaseMemObject(d_sub_buf)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +void ggml_cl_mul_mat_q6_K_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + + const int ne1 = dst->ne[1]; + + GGML_ASSERT(ne00 % ggml_blck_size(src0->type) == 0); + + cl_context context = backend_ctx->context; + cl_kernel kernel; + + cl_int err; + cl_buffer_region region; + cl_image_format img_fmt; + cl_image_desc img_desc; + + // Multi-column verify GEMV + static const bool q6k_mc3 = (getenv("GGML_OPENCL_Q6_K_MC3") != nullptr); + const bool use_q6k_mc3 = q6k_mc3 && (ne1 == 3) && (ne01 < 32768); + // Multi-column tiled vocab GEMV for verify + // streams the large lm_head weight once across the verify columns + static const char * q6k_tiled_mc_env = getenv("GGML_OPENCL_Q6_K_TILED_MC"); + const bool q6k_tiled_mc = q6k_tiled_mc_env ? atoi(q6k_tiled_mc_env) != 0 + : (q6k_mc3 || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + const bool use_q6k_tiled_mc = q6k_tiled_mc && (ne1 >= 2 && ne1 <= 4) && (ne01 >= 32768) && use_q6k_tiled(backend_ctx, src0); + + const bool use_bin = use_q6_k_bin_kernels(backend_ctx, src0); + + if (use_bin && ggml_cl_mul_mat_coopmat(backend_ctx, backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_f32_coopmat, + { extra0_q6_K->ql, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, src1, dst, ne00, ne01, ne1)) { + return; + } + + if (use_bin) { + if (use_q6k_mc3 || use_q6k_tiled_mc) { + static bool warned = false; + if (!warned) { + GGML_LOG_WARN("ggml_opencl: GGML_OPENCL_Q6_K_MC3 is bypassed by Q6_K binary kernels\n"); + warned = true; + } + } + // This bin layout is not supported by CoopK. + ggml_cl_mul_mat_q6_K_f32_adreno_ila(backend, src0, src1, dst); + return; + } + + if (ne1 == 1 || use_q6k_mc3 || use_q6k_tiled_mc) { + cl_mem ql_img = nullptr; + cl_mem qh_img = nullptr; + cl_mem b_sub_buffer = nullptr; + cl_mem b_img = nullptr; + + // o4 = 4-output-per-WI variant for long-vocab lm_head/embed; gated to + // ne01 >= 32768 so per-layer q6_K (ne01=hidden 2-8K) keeps the 2-output + // kernel (o4 regresses there). o4_global reads the weights from __global + // coalesced instead of image1d_buffer -- the texture cache caps the + // read-once-per-token lm_head bandwidth, while __global reaches the higher + // rate the rest of the model gets. Both default ON; opt out via + // GGML_OPENCL_Q6K_GEMV_O4 / GGML_OPENCL_Q6K_GEMV_O4_GLOBAL = 0. + static const bool gemv_o4_env = []{ + const char * e = std::getenv("GGML_OPENCL_Q6K_GEMV_O4"); + return !e || e[0] == '\0' || e[0] != '0'; + }(); + static const bool o4_global_env = []{ + const char * e = std::getenv("GGML_OPENCL_Q6K_GEMV_O4_GLOBAL"); + return !e || e[0] == '\0' || e[0] != '0'; + }(); + const bool use_tiled = !use_q6k_mc3 && use_q6k_tiled(backend_ctx, src0); + const bool use_o4 = !use_tiled && !use_q6k_mc3 && gemv_o4_env && (ne01 % 4 == 0) && (ne01 >= 32768); + const bool use_o4_global = use_o4 && o4_global_env; + + // ql/qh image views are only needed when NOT reading weights from global. + if (!use_o4_global && !use_tiled) { + // image for ql + img_fmt.image_channel_order = CL_R; + img_fmt.image_channel_data_type = CL_FLOAT; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = ne01 * ne00 / 8; + img_desc.buffer = extra0_q6_K->ql; + CL_CHECK((ql_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // image for qh + img_fmt.image_channel_order = CL_R; + img_fmt.image_channel_data_type = CL_HALF_FLOAT; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = ne01 * ne00 / 8; + img_desc.buffer = extra0_q6_K->qh; + CL_CHECK((qh_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + } + + region.origin = offset1; + region.size = ne00 * ne1 * sizeof(float); + CL_CHECK((b_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt.image_channel_order = CL_RGBA; + img_fmt.image_channel_data_type = CL_FLOAT; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = ne00 * ne1 / 4; + img_desc.buffer = b_sub_buffer; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + kernel = use_q6k_mc3 ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_mc3 + : use_q6k_tiled_mc ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_tiled_mc3 + : use_tiled ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_tiled + : use_o4_global ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_o4_global + : use_o4 ? backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32_o4 + : backend_ctx->mul_mat.kernel_gemv_noshuffle_q6_K_f32; + + if (use_o4_global || use_tiled) { + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + } else { + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &ql_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh_img)); + } + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_int), &ne01)); + if (use_q6k_tiled_mc) { + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_int), &ne1)); + } + + const size_t gws_x = use_tiled + ? (size_t) CEIL_DIV(ne01, 64) * 64 + : use_o4 + ? (size_t) CEIL_DIV(ne01/4, 64) * 64 + : (size_t) CEIL_DIV(ne01/2, 64) * 64; + size_t local_work_size[3] = {64, 4, 1}; + size_t global_work_size[3] = {gws_x, 4, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + if (ql_img) CL_CHECK(clReleaseMemObject(ql_img)); + if (qh_img) CL_CHECK(clReleaseMemObject(qh_img)); + CL_CHECK(clReleaseMemObject(b_sub_buffer)); + CL_CHECK(clReleaseMemObject(b_img)); + } else { + // Tiled-layout batched GEMM. When the weight was converted to the 64-row + // tiled canonical layout (use_q6k_tiled - the default for lm_head/embed), + // the plain noshuffle GEMM below reads it as plain-transposed and produces + // garbage. Use the batched GEMM that matches the decode tiled GEMV's + // layout; it reads the f32 activation directly (column-major, no transpose). + if (use_q6k_tiled(backend_ctx, src0)) { + cl_mem b_sub_buf_t = nullptr; + cl_mem b_img_t = nullptr; + + region.origin = offset1; + region.size = ne00 * ne1 * sizeof(float); + CL_CHECK((b_sub_buf_t = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + img_fmt.image_channel_order = CL_RGBA; + img_fmt.image_channel_data_type = CL_FLOAT; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = ne00 * ne1 / 4; + img_desc.buffer = b_sub_buf_t; + CL_CHECK((b_img_t = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + cl_kernel kt = backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_K_f32_tiled; + CL_CHECK(clSetKernelArg(kt, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(kt, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kt, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kt, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kt, 4, sizeof(cl_mem), &b_img_t)); + CL_CHECK(clSetKernelArg(kt, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kt, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kt, 7, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kt, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kt, 9, sizeof(int), &ne1)); + + // Must match the kernel: NTILES=4 64-row tiles per work-group (256 rows), + // BN=8 output columns per work-group. + const int BN_T = 16; + const int WROWS = 4 * 64; // NTILES * TILE_ROWS + size_t local_work_size[3] = {64, 4, 1}; + size_t global_work_size[3] = {(size_t)CEIL_DIV(ne01, WROWS) * 64, 4, (size_t)CEIL_DIV(ne1, BN_T)}; + backend_ctx->enqueue_ndrange_kernel(kt, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_img_t)); + CL_CHECK(clReleaseMemObject(b_sub_buf_t)); + return; + } + + cl_mem b_sub_buf; + cl_mem b_buf_trans; + cl_mem b_img; + cl_mem b_img_trans; + + // subbuffer for activation + region.origin = offset1; + region.size = ne00 * ne1 * sizeof(float); + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // CoopK uses the same untiled weight layout as gemm_noshuffle_q6_K_f32, with K-major Q8_1 activations (K contiguous). + // Keep output and embedding weights on the existing path for logit stability. + if (ggml_cl_coopk_dp4a_narrow_on(backend_ctx, dst, backend_ctx->mul_mat.rows_coopk_dp4a_q6_k) + && backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_c4 != nullptr + && strncmp(src0->name, "output", 6) != 0 + && strncmp(src0->name, "token_embd", 10) != 0 + && ((ne1 <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_c4) != nullptr) { + const int N = (int)ne1, K = (int)ne00; + const int cols = (N <= 2) ? 2 : 4; + const size_t n_blocks_padded = (size_t)cols * (K / 32); + const size_t size_qa = (size_t)cols * K * sizeof(cl_char); + const size_t size_qa_prev = backend_ctx->prealloc_moe_qa.size; + const size_t size_da_prev = backend_ctx->prealloc_moe_da.size; + backend_ctx->prealloc_moe_qa.allocate(context, size_qa); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks_padded * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks_padded * sizeof(cl_half)); + if (backend_ctx->prealloc_moe_qa.size != size_qa_prev) { + const cl_char z8 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_qa.buffer, + &z8, sizeof(z8), 0, backend_ctx->prealloc_moe_qa.size, 0, NULL, NULL)); + } + if (backend_ctx->prealloc_moe_da.size != size_da_prev) { + const cl_half z16 = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_da.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_da.size, 0, NULL, NULL)); + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_moe_sa.buffer, + &z16, sizeof(z16), 0, backend_ctx->prealloc_moe_sa.size, 0, NULL, NULL)); + } + + cl_int n_blocks = (cl_int)((size_t)N * (K / 32)); + cl_kernel kernel_quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(kernel_quant, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(kernel_quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(kernel_quant, 4, sizeof(cl_int), &n_blocks)); + size_t local_work_size_quant[1] = { 64 }; + size_t global_work_size_quant[1] = { (size_t)((((size_t)n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(kernel_quant, 1, global_work_size_quant, local_work_size_quant, dst); + + cl_kernel kernel_coopk = (N <= 2) ? backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_c2 + : backend_ctx->mul_mat.kernel_gemm_coopk_q6_k_q8_1_dp4a_c4; + const cl_ushort mask_f000 = 0xF000; + const cl_uchar mask_c0 = 0xC0; + const cl_int n_padded = cols; + const cl_int m = (cl_int)ne01, k = (cl_int)ne00, n = (cl_int)ne1; + CL_CHECK(clSetKernelArg(kernel_coopk, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(kernel_coopk, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel_coopk, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel_coopk, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel_coopk, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(kernel_coopk, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel_coopk, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel_coopk, 8, sizeof(cl_int), &m)); + CL_CHECK(clSetKernelArg(kernel_coopk, 9, sizeof(cl_int), &n_padded)); + CL_CHECK(clSetKernelArg(kernel_coopk, 10, sizeof(cl_int), &k)); + CL_CHECK(clSetKernelArg(kernel_coopk, 11, sizeof(cl_int), &n)); + CL_CHECK(clSetKernelArg(kernel_coopk, 12, sizeof(cl_ushort), &mask_f000)); + CL_CHECK(clSetKernelArg(kernel_coopk, 13, sizeof(cl_uchar), &mask_c0)); + + const size_t nsg = (size_t)backend_ctx->mul_mat.nsg_coopk_dp4a_q6_k; + size_t local_work_size[3] = { 64, nsg, 1 }; + size_t global_work_size[3] = { (size_t)(ne01 / backend_ctx->mul_mat.rows_coopk_dp4a_q6_k), nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel_coopk, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + // dp4a (int8) dense q6_K prefill GEMM + static const char * q6k_dense_dp4a_env = getenv("GGML_OPENCL_Q6K_DENSE_DP4A"); + bool q6k_dense_dp4a_on = (q6k_dense_dp4a_env != nullptr) + ? (atoi(q6k_dense_dp4a_env) != 0) + : (backend_ctx->adreno_gen != ADRENO_GPU_GEN::X1E); + // dot prod has to be available + q6k_dense_dp4a_on = backend_ctx->has_integer_dot && q6k_dense_dp4a_on; + + const bool is_output_w_dp4a = strncmp(src0->name, "output", 6) == 0 || + strncmp(src0->name, "token_embd", 10) == 0; + + if (q6k_dense_dp4a_on && !is_output_w_dp4a && ne1 > 8 && (ne00 % 32 == 0) && (ne01 % 64 == 0)) { + const int M = ne01, N = ne1, K = ne00; + const size_t n_blocks = (size_t)N * (K / 32); + backend_ctx->prealloc_moe_qa.allocate(context, (size_t)N * K * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(context, n_blocks * sizeof(cl_half)); + + cl_int tb = (cl_int)n_blocks; + cl_kernel qk = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(qk, 0, sizeof(cl_mem), &b_sub_buf)); + CL_CHECK(clSetKernelArg(qk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(qk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(qk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(qk, 4, sizeof(cl_int), &tb)); + size_t q_local[1] = { 64 }; + size_t q_global[1] = { (size_t)(((n_blocks + 63) / 64) * 64) }; + backend_ctx->enqueue_ndrange_kernel(qk, 1, q_global, q_local, dst); + + static const char * q6_k_act_vload4_env = getenv("GGML_OPENCL_Q6_K_DP4A_ACT_VLOAD4"); + const bool q6_k_act_vload4_on = q6_k_act_vload4_env == nullptr || atoi(q6_k_act_vload4_env) != 0; + cl_kernel dk = q6_k_act_vload4_on + ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a_act_vload4 + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_k_q8_1_dp4a; + int ai = 0; + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &N)); + CL_CHECK(clSetKernelArg(dk, ai++, sizeof(cl_int), &K)); + size_t d_local[3] = { 64, 1, 1 }; + size_t d_global[3] = { 64, (size_t)(M / 64), (size_t)CEIL_DIV(N, 32) }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, d_global, d_local, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + return; + } + + // image for activation + img_fmt.image_channel_order = CL_RGBA; + img_fmt.image_channel_data_type = CL_FLOAT; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = ne00 * ne1 / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // pad N to multiple of 8 + int extra_elements = ne1 % 8; + int padding = 0; + if (extra_elements > 0){ + padding = 8 - extra_elements; + } + + // subbuffer for transposed activation + region.origin = 0; + region.size = ne00 * (ne1 + padding) * sizeof(float)/2; + backend_ctx->prealloc_act_trans.allocate(context, region.size); + CL_CHECK((b_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + // image for transposed activation + img_fmt.image_channel_order = CL_RGBA; + img_fmt.image_channel_data_type = CL_HALF_FLOAT; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = ne00 * (ne1 + padding) / 4; + img_desc.buffer = b_buf_trans; + CL_CHECK((b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, NULL, &err), err)); + + // transpose activation + int height_B = ne1/4; + if (height_B == 0) { + height_B = 1; + } + int width_B = ne00/4; + int padded_height_B = (ne1 + padding) / 4; + + kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_B)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_B)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_B)); + + size_t local_size_t[2] = { 1, 16 }; + size_t global_size_t[2] = { (size_t)width_B, (size_t)padded_height_B }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_size_t, local_size_t, dst); + + // gemm + // Cooperative-K small-batch (n_q in [2..8]) path: intra-WG K-split, + // mirrors the q4_K _cok path (batched serving). OPT-IN + // (GGML_OPENCL_Q6K_GEMM_COK=1), DEFAULT OFF: q6_K is the tied lm_head/ + // output projection, so the K-reassociation perturbs final logits and + // greedy is NOT byte-identical (op-tests pass, output coherent, but not + // bit-exact). It is also NEUTRAL on end-to-end MTP (q4_K cok already + // captured that; the MTP bottleneck moved off the GEMMs). Keep opt-in + // for batched serving until PPL-validated on a non-GDN q6_K model. + static const char * q6k_cok_env = getenv("GGML_OPENCL_Q6K_GEMM_COK"); + static const bool q6k_gemm_cok = (q6k_cok_env != nullptr) && (atoi(q6k_cok_env) != 0); + const bool use_q6k_cok = q6k_gemm_cok && (ne1 <= 8); + kernel = use_q6k_cok ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_K_f32_cok + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q6_K_f32; + int padded_N = ne1 + padding; + + cl_ushort mask_f000 = 0xF000; + cl_uchar mask_c0 = 0xC0; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &padded_N)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ushort),&mask_f000)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_uchar), &mask_c0)); + + size_t global_work_size[3]; + size_t local_work_size[3]; + if (use_q6k_cok) { + global_work_size[0] = (size_t)ne01; // rows (1 per lane) + global_work_size[1] = 8; // COK_NSG + global_work_size[2] = 1; + local_work_size[0] = 64; // COK_SG + local_work_size[1] = 8; // COK_NSG + local_work_size[2] = 1; + } else { + global_work_size[0] = (size_t)CEIL_DIV(ne1, 8); + global_work_size[1] = (size_t)CEIL_DIV(ne01, 4); + global_work_size[2] = 1; + local_work_size[0] = 2; + local_work_size[1] = 128; + local_work_size[2] = 1; + } + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(b_sub_buf)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img_trans)); + } +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static bool ggml_cl_mul_mat_q2_K_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_q2_K * extra0 = (ggml_tensor_extra_cl_q2_K *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 16 ? 8 : 32; + cl_kernel gemm = n <= 16 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_k_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_k_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_Q2_K_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->dm)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +static bool ggml_cl_mul_mat_q3_K_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_q3_K * extra0 = (ggml_tensor_extra_cl_q3_K *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 16 ? 8 : 32; + cl_kernel gemm = n <= 16 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_q3_k_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_q3_k_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_Q3_K_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->hm)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +static bool ggml_cl_mul_mat_iq3_s_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq3_s * extra0 = (ggml_tensor_extra_cl_iq3_s *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_s_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_s_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ3_S_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sg)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +static bool ggml_cl_mul_mat_iq3_xxs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq3_xxs * extra0 = (ggml_tensor_extra_cl_iq3_xxs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_xxs_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ3_XXS_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sas)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +static bool ggml_cl_mul_mat_iq1_m_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq1_m * extra0 = (ggml_tensor_extra_cl_iq1_m *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_m_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_m_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ1_M_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +static bool ggml_cl_mul_mat_iq1_s_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq1_s * extra0 = (ggml_tensor_extra_cl_iq1_s *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_s_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_s_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ1_S_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + + +void ggml_cl_mul_mat_iq3_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq3_s * extra0 = (ggml_tensor_extra_cl_iq3_s *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq3_s_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq3_s_grid_image)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sg)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 12, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 13, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq3_s_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq3_s_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_s_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +void ggml_cl_mul_mat_iq3_xxs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq3_xxs * extra0 = (ggml_tensor_extra_cl_iq3_xxs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq3_xxs_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq3_xxs_grid_image)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sas)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq3_xxs_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq3_xxs_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq3_xxs_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +static bool ggml_cl_mul_mat_iq4_xs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq4_xs * extra0 = (ggml_tensor_extra_cl_iq4_xs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_xs_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ4_XS_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sl)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->sh)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +void ggml_cl_mul_mat_iq4_xs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq4_xs * extra0 = (ggml_tensor_extra_cl_iq4_xs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq4_xs_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->sl)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sh)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq4_xs_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq4_xs_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq4_xs_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sl)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->sh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +void ggml_cl_mul_mat_iq1_m_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq1_m * extra0 = (ggml_tensor_extra_cl_iq1_m *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq1_m_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq1_s_grid_image)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq1_m_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq1_m_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_m_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +void ggml_cl_mul_mat_iq1_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq1_s * extra0 = (ggml_tensor_extra_cl_iq1_s *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq1_s_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq1_s_grid_image)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq1_s_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq1_s_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq1_s_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +static bool ggml_cl_mul_mat_iq2_s_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq2_s * extra0 = (ggml_tensor_extra_cl_iq2_s *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_s_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_s_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ2_S_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sg)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 10, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 11, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +static bool ggml_cl_mul_mat_iq2_xs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq2_xs * extra0 = (ggml_tensor_extra_cl_iq2_xs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xs_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ2_XS_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + +static bool ggml_cl_mul_mat_iq2_xxs_dp4a(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq2_xxs * extra0 = (ggml_tensor_extra_cl_iq2_xxs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + const int tile_n = n <= 8 ? 8 : 32; + cl_kernel gemm = n <= 8 ? backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a_narrow + : backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xxs_q8_1_dp4a; + const char * env = getenv("GGML_OPENCL_IQ2_XXS_DENSE_DP4A"); + if (!gemm || !backend_ctx->has_integer_dot || (env && env[0] == '0') || + n <= 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + return false; + } + + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem activation = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + const size_t n_blocks = (size_t)n*(k/32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, (size_t)n*k); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks*sizeof(cl_half)); + + cl_int nb = n_blocks; + cl_kernel quant = backend_ctx->mul_mat.kernel_quant_a_q8_1; + CL_CHECK(clSetKernelArg(quant, 0, sizeof(cl_mem), &activation)); + CL_CHECK(clSetKernelArg(quant, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(quant, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(quant, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(quant, 4, sizeof(cl_int), &nb)); + size_t q_global[] = { CEIL_DIV(n_blocks, 64)*64 }; + size_t q_local[] = { 64 }; + backend_ctx->enqueue_ndrange_kernel(quant, 1, q_global, q_local, dst); + + CL_CHECK(clSetKernelArg(gemm, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemm, 1, sizeof(cl_mem), &extra0->sas)); + CL_CHECK(clSetKernelArg(gemm, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemm, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(gemm, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(gemm, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemm, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemm, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemm, 8, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(gemm, 9, sizeof(int), &k)); + size_t global[] = { 64, (size_t)CEIL_DIV(m, 64), (size_t)CEIL_DIV(n, tile_n) }; + size_t local[] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemm, 3, global, local, dst); + CL_CHECK(clReleaseMemObject(activation)); + return true; +} + + +void ggml_cl_mul_mat_iq2_s_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq2_s * extra0 = (ggml_tensor_extra_cl_iq2_s *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq2_s_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq2_s_grid_image)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sg)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 12, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 13, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq2_s_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq2_s_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_s_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +void ggml_cl_mul_mat_iq2_xs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq2_xs * extra0 = (ggml_tensor_extra_cl_iq2_xs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq2_xs_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq2_xs_grid_image)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq2_xs_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq2_xs_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xs_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +void ggml_cl_mul_mat_iq2_xxs_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_iq2_xxs * extra0 = (ggml_tensor_extra_cl_iq2_xxs *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_iq2_xxs_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &backend_ctx->iq2_xxs_grid_image)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sas)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); + const size_t nsg = backend_ctx->mul_mat.iq2_xxs_mv_nsg; + size_t global[] = { (size_t)CEIL_DIV(m, 128)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_iq2_xxs_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_iq2_xxs_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +void ggml_cl_mul_mat_q3_k_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_q3_K * extra0 = (ggml_tensor_extra_cl_q3_K *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_q3_k_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->hm)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 11, sizeof(int), &stride_d)); + const size_t rows = 64*(size_t)backend_ctx->mul_mat.q3_k_mv_rows; + const size_t nsg = backend_ctx->mul_mat.q3_k_mv_nsg; + size_t global[] = { CEIL_DIV((size_t)m, rows)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_q3_K_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q3_k_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->hm)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra0->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} + +void ggml_cl_mul_mat_q2_k_f32_adreno(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + ggml_tensor_extra_cl_q2_K * extra0 = (ggml_tensor_extra_cl_q2_K *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + const int m = src0->ne[1]; + const int n = src1->ne[1]; + const int k = src0->ne[0]; + + if (n == 1 || !ggml_is_contiguous(src1) || offset1 % backend_ctx->alignment != 0) { + cl_kernel gemv = backend_ctx->mul_mat.kernel_gemv_noshuffle_q2_k_f32; + const int stride_d = dst->ne[0]; + const int stride_b = src1->nb[1]/sizeof(float); + CL_CHECK(clSetKernelArg(gemv, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(gemv, 1, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(gemv, 2, sizeof(cl_mem), &extra0->dm)); + CL_CHECK(clSetKernelArg(gemv, 3, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(gemv, 4, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(gemv, 5, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(gemv, 6, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(gemv, 7, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(gemv, 8, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(gemv, 9, sizeof(int), &stride_b)); + CL_CHECK(clSetKernelArg(gemv, 10, sizeof(int), &stride_d)); + const size_t rows = 64*(size_t)backend_ctx->mul_mat.q2_k_mv_rows; + const size_t nsg = backend_ctx->mul_mat.q2_k_mv_nsg; + size_t global[] = { CEIL_DIV((size_t)m, rows)*64, (size_t)n*nsg, 1 }; + size_t local[] = { 64, nsg, 1 }; + backend_ctx->enqueue_ndrange_kernel(gemv, 3, global, local, dst); + return; + } + + if (ggml_cl_mul_mat_q2_K_dp4a(backend, src0, src1, dst)) { + return; + } + + cl_context context = backend_ctx->context; + cl_int err; + cl_buffer_region region = { (size_t)offset1, (size_t)k*n*sizeof(float) }; + cl_mem b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_image_format img_fmt = { CL_RGBA, CL_FLOAT }; + cl_image_desc img_desc = {}; + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)k*n/4; + img_desc.buffer = b_sub_buf; + cl_mem b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int padded_n = CEIL_DIV(n, 8)*8; + region.origin = 0; + region.size = (size_t)k*padded_n*sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(context, region.size); + cl_mem b_sub_buf_trans = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + img_fmt = { CL_RGBA, CL_HALF_FLOAT }; + img_desc.image_width = (size_t)k*padded_n/4; + img_desc.buffer = b_sub_buf_trans; + cl_mem b_img_trans = clCreateImage(context, 0, &img_fmt, &img_desc, nullptr, &err); + CL_CHECK(err); + + const int height_b = std::max(n/4, 1); + const int width_b = k/4; + const int padded_height_b = padded_n/4; + cl_kernel kernel = backend_ctx->mul_mat.kernel_transpose_32_16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &height_b)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &width_b)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &padded_height_b)); + size_t t_global[] = { (size_t)width_b, (size_t)padded_height_b }; + size_t t_local[] = { 1, 16 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, t_global, t_local, dst); + + kernel = backend_ctx->mul_mat.kernel_gemm_noshuffle_q2_k_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0->sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra0->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &b_img_trans)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &m)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &padded_n)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &n)); + size_t global[] = { (size_t)CEIL_DIV(n, 8), (size_t)CEIL_DIV(m, 512)*128, 1 }; + size_t local[] = { 1, 128, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); + + CL_CHECK(clReleaseMemObject(b_img_trans)); + CL_CHECK(clReleaseMemObject(b_sub_buf_trans)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} +void ggml_cl_mul_mat_q4_K_glu_fused(ggml_backend_t backend, ggml_tensor * gate_tensor, ggml_tensor * up_tensor, ggml_tensor * glu_tensor) { + GGML_ASSERT(gate_tensor && up_tensor && glu_tensor); + + const ggml_tensor * Wg = gate_tensor->src[0]; + const ggml_tensor * Wu = up_tensor->src[0]; + const ggml_tensor * src1 = gate_tensor->src[1]; // == up_tensor->src[1] + const ggml_tensor * dst = glu_tensor; + + GGML_ASSERT(Wg && Wg->extra); + GGML_ASSERT(Wu && Wu->extra); + GGML_ASSERT(src1 && src1->extra); + GGML_ASSERT(dst && dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + ggml_tensor_extra_cl_q4_K * extra_g = (ggml_tensor_extra_cl_q4_K *)Wg->extra; + ggml_tensor_extra_cl_q4_K * extra_u = (ggml_tensor_extra_cl_q4_K *)Wu->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int K = Wg->ne[0]; // ne00 + const int M = Wg->ne[1]; // ne01 (= ffn intermediate width) + const int N = 1; // decode GEMV + + const cl_uchar mask_d6 = 0x3F, mask_d4 = 0x0F, mask_hi2 = 0xC0; + const int glu_op = (int)ggml_get_glu_op(dst); + + cl_context context = backend_ctx->context; + cl_int err; + cl_image_format img_fmt; + cl_image_desc img_desc; + cl_buffer_region region; + + // q images for the two weight matrices (standard noshuffle layout) + img_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)M * K / 2 / 4; + img_desc.buffer = extra_g->q; + cl_mem qg_img = nullptr, qu_img = nullptr; + CL_CHECK((qg_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + img_desc.buffer = extra_u->q; + CL_CHECK((qu_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + // shared activation image (one column at decode) + region.origin = offset1; + region.size = (size_t)K * N * sizeof(float); + cl_mem b_sub_buf = nullptr, b_img = nullptr; + CL_CHECK((b_sub_buf = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + img_fmt = { CL_RGBA, CL_FLOAT }; + memset(&img_desc, 0, sizeof(img_desc)); + img_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + img_desc.image_width = (size_t)K * N / 4; + img_desc.buffer = b_sub_buf; + CL_CHECK((b_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_fmt, &img_desc, NULL, &err), err)); + + cl_kernel kernel = backend_ctx->mul_mat.kernel_gemv_noshuffle_q4_k_f32_glu; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qg_img)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra_g->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_g->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra_g->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &qu_img)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra_u->d)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra_u->dm)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extra_u->s)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &b_img)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_int), &K)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_int), &M)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_int), &glu_op)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_uchar), &mask_d6)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_uchar), &mask_d4)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_uchar), &mask_hi2)); + + // K-split = nsg_y subgroups. HARD-CAP at 8 (512 work-items): the fused + // kernel's cross-subgroup reduce uses a float4 reduceLM (gate+up packed) = + // 2x the LDS of the base GEMV's float2 reduce, so 16 co-resident subgroups + // exceed the per-CU LDS budget on X2 and the WG barrier DEADLOCKS -> GPU TDR + // (reproduced on upstream gemma-4 E4B decode, K=2560 M=10240). This used to + // be masked: get_kernel_workgroup_size reported 896 for this kernel (so the + // cap loop fell to 8), but it now returns 1024 and the Adreno per-kernel WG + // query is unreliable (over-reports), so cap explicitly instead of trusting + // it. nsg_y < 16 also means the cross-subgroup accumulation grouping differs + // from the standalone wide (nsg=16) GEMV, so the output is coherent but NOT + // byte-identical to the per-op path. Keep the maxwg query as a further floor + // for any driver that reports < 512. + size_t maxwg = backend_ctx->get_kernel_workgroup_size(kernel); + // X2E: 4 is faster than 8 on every q4_K FFN shape measured there + size_t nsg_y = backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E ? 4 : 8; + while (nsg_y > 1 && 64 * nsg_y > maxwg) { nsg_y >>= 1; } + size_t local_work_size[3] = { 64, nsg_y, 1 }; + size_t global_work_size[3] = { (size_t)CEIL_DIV(M / 2, 64) * 64, nsg_y, 1 }; + + if (getenv("GGML_OPENCL_FUSE_DEBUG")) { + static int dbg = 0; + if (dbg < 3) { fprintf(stderr, "[FUSE_MM_GLU] fired #%d K=%d M=%d glu_op=%d nsg=%zu maxwg=%zu\n", ++dbg, K, M, glu_op, nsg_y, maxwg); fflush(stderr); } + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + + CL_CHECK(clReleaseMemObject(qg_img)); + CL_CHECK(clReleaseMemObject(qu_img)); + CL_CHECK(clReleaseMemObject(b_img)); + CL_CHECK(clReleaseMemObject(b_sub_buf)); +} +#endif // GGML_OPENCL_USE_ADRENO_KERNELS diff --git a/ggml/src/ggml-opencl/ops/mul_mat_id.cpp b/ggml/src/ggml-opencl/ops/mul_mat_id.cpp new file mode 100644 index 000000000000..8d7755661ad5 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/mul_mat_id.cpp @@ -0,0 +1,3600 @@ +#include "../cl-common.h" +#include "../ops.h" + +#include + +void ggml_cl_moe_combine_fused(ggml_backend_t backend, const ggml_tensor * mul, const ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context; + const ggml_tensor * experts = mul->src[0]; + const ggml_tensor * weights = mul->src[1]; + + ggml_tensor_extra_cl * ee = (ggml_tensor_extra_cl *)experts->extra; + ggml_tensor_extra_cl * ew = (ggml_tensor_extra_cl *)weights->extra; + ggml_tensor_extra_cl * ed = (ggml_tensor_extra_cl *)dst->extra; + cl_ulong off_e = ee->offset + experts->view_offs; + cl_ulong off_w = ew->offset + weights->view_offs; + cl_ulong off_d = ed->offset + dst->view_offs; + + const int n_embd4 = (int)(experts->ne[0] / 4); + const int k = (int)experts->ne[1]; + const int nt = (int)experts->ne[2]; + const cl_uint e1 = (cl_uint)(experts->nb[1] / sizeof(float)); + const cl_uint e2 = (cl_uint)(experts->nb[2] / sizeof(float)); + const cl_uint w1 = (cl_uint)(weights->nb[1] / sizeof(float)); + const cl_uint w2 = (cl_uint)(weights->nb[2] / sizeof(float)); + const cl_uint d1 = (cl_uint)(dst->nb[1] / sizeof(float)); + + // The router weights are tiny ([1,k,nt]) and may share a pool buffer with the output; + // copy them into a private scratch so the fused kernel never reads aliased memory. + const size_t w_bytes = ggml_nbytes(weights); + backend_ctx->prealloc_moe_combine_w.allocate(backend_ctx->context, w_bytes); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, ew->data_device, backend_ctx->prealloc_moe_combine_w.buffer, + off_w, 0, w_bytes, 0, NULL, NULL)); + cl_mem w_dev = backend_ctx->prealloc_moe_combine_w.buffer; + cl_ulong w_off = 0; + + cl_kernel kernel = backend_ctx->mul_mat_id.kernel_moe_combine_f32; + int a = 0; + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &ee->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_e)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &w_dev)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &w_off)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_mem), &ed->data_device)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_ulong), &off_d)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &n_embd4)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(int), &nt)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &e1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &e2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &w1)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &w2)); + CL_CHECK(clSetKernelArg(kernel, a++, sizeof(cl_uint), &d1)); + + size_t lws[2] = { 64, 1 }; + size_t gws[2] = { (size_t)(((n_embd4 + 63) / 64) * 64), (size_t)nt }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, gws, lws, dst); +} + +void ggml_cl_moe_bias_glu_fused(ggml_backend_t backend, ggml_tensor * gate_mm, const ggml_tensor * gate_add, + ggml_tensor * up_mm, const ggml_tensor * up_add, const ggml_tensor * glu) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_cl_mul_mat_ext(backend, gate_mm->src[0], gate_mm->src[1], gate_mm); + ggml_cl_mul_mat_ext(backend, up_mm->src[0], up_mm->src[1], up_mm); + + const ggml_tensor * gbias = gate_add->src[1]; + const ggml_tensor * ubias = up_add->src[1]; + const ggml_tensor * ids = gate_add->src[2]; + + ggml_tensor_extra_cl * eg = (ggml_tensor_extra_cl *) gate_mm->extra; + ggml_tensor_extra_cl * egb = (ggml_tensor_extra_cl *) gbias->extra; + ggml_tensor_extra_cl * eu = (ggml_tensor_extra_cl *) up_mm->extra; + ggml_tensor_extra_cl * eub = (ggml_tensor_extra_cl *) ubias->extra; + ggml_tensor_extra_cl * ei = (ggml_tensor_extra_cl *) ids->extra; + ggml_tensor_extra_cl * ed = (ggml_tensor_extra_cl *) glu->extra; + + cl_ulong off_g = eg->offset + gate_mm->view_offs; + cl_ulong off_gb = egb->offset + gbias->view_offs; + cl_ulong off_u = eu->offset + up_mm->view_offs; + cl_ulong off_ub = eub->offset + ubias->view_offs; + cl_ulong off_i = ei->offset + ids->view_offs; + cl_ulong off_d = ed->offset + glu->view_offs; + + const cl_ulong nb01_g = gate_mm->nb[1]; + const cl_ulong nb02_g = gate_mm->nb[2]; + const cl_ulong nb01_u = up_mm->nb[1]; + const cl_ulong nb02_u = up_mm->nb[2]; + const cl_ulong nb11_g = gbias->nb[1]; + const cl_ulong nb11_u = ubias->nb[1]; + const cl_ulong nb21 = ids->nb[1]; + const cl_ulong nbd1 = glu->nb[1]; + const cl_ulong nbd2 = glu->nb[2]; + + const int ne0 = (int) glu->ne[0]; + const float alpha = ggml_get_op_params_f32(glu, 2); + const float limit = ggml_get_op_params_f32(glu, 3); + + cl_kernel kernel = backend_ctx->mul_mat_id.kernel_add_id_add_id_swiglu_oai; + + int i = 0; + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &eg->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_g)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &egb->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_gb)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &eu->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_u)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &eub->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_ub)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &ei->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_i)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &ed->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_d)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb01_g)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb02_g)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb01_u)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb02_u)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb11_g)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb11_u)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nbd1)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nbd2)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(float), &limit)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(float), &alpha)); + + const int nth = MIN(ne0, (int) backend_ctx->get_kernel_workgroup_size(kernel)); + size_t global_work_size[] = { (size_t) glu->ne[1] * nth, (size_t) glu->ne[2], 1 }; + size_t local_work_size[] = { (size_t) nth, 1, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, glu); +} + +void ggml_cl_moe_bias_combine_fused(ggml_backend_t backend, const ggml_tensor * add, + const ggml_tensor * mul, const ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + const ggml_tensor * experts = add->src[0]; + const ggml_tensor * bias = add->src[1]; + const ggml_tensor * ids = add->src[2]; + const ggml_tensor * weights = mul->src[1]; + + ggml_tensor_extra_cl * ee = (ggml_tensor_extra_cl *) experts->extra; + ggml_tensor_extra_cl * eb = (ggml_tensor_extra_cl *) bias->extra; + ggml_tensor_extra_cl * ei = (ggml_tensor_extra_cl *) ids->extra; + ggml_tensor_extra_cl * ew = (ggml_tensor_extra_cl *) weights->extra; + ggml_tensor_extra_cl * ed = (ggml_tensor_extra_cl *) dst->extra; + cl_ulong off_e = ee->offset + experts->view_offs; + cl_ulong off_b = eb->offset + bias->view_offs; + cl_ulong off_i = ei->offset + ids->view_offs; + cl_ulong off_w = ew->offset + weights->view_offs; + cl_ulong off_d = ed->offset + dst->view_offs; + + const int n_embd4 = (int) (experts->ne[0] / 4); + const int k = (int) experts->ne[1]; + const int nt = (int) experts->ne[2]; + const cl_uint e1 = (cl_uint) (experts->nb[1] / sizeof(float)); + const cl_uint e2 = (cl_uint) (experts->nb[2] / sizeof(float)); + const cl_uint w1 = (cl_uint) (weights->nb[1] / sizeof(float)); + const cl_uint w2 = (cl_uint) (weights->nb[2] / sizeof(float)); + const cl_uint d1 = (cl_uint) (dst->nb[1] / sizeof(float)); + const cl_ulong nb_b1 = bias->nb[1]; + const cl_ulong nb_i1 = ids->nb[1]; + + const size_t w_bytes = ggml_nbytes(weights); + backend_ctx->prealloc_moe_combine_w.allocate(backend_ctx->context, w_bytes); + CL_CHECK(clEnqueueCopyBuffer(backend_ctx->queue, ew->data_device, backend_ctx->prealloc_moe_combine_w.buffer, + off_w, 0, w_bytes, 0, NULL, NULL)); + cl_mem w_dev = backend_ctx->prealloc_moe_combine_w.buffer; + cl_ulong w_off = 0; + + cl_kernel kernel = backend_ctx->mul_mat_id.kernel_moe_combine_bias_f32; + int i = 0; + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &ee->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_e)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &w_dev)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &w_off)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &eb->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_b)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &ei->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_i)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_mem), &ed->data_device)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &off_d)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(int), &n_embd4)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(int), &nt)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_uint), &e1)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_uint), &e2)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_uint), &w1)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_uint), &w2)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_uint), &d1)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb_b1)); + CL_CHECK(clSetKernelArg(kernel, i++, sizeof(cl_ulong), &nb_i1)); + + size_t local_work_size[] = { 64, 1 }; + size_t global_work_size[] = { (size_t) (((n_embd4 + 63) / 64) * 64), (size_t) nt }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); +} + +void ggml_cl_load_kernels_mul_mat_id(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + + // mul_mat_id_utils + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mat_id_utils.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mat_id_utils.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_zero_dst = clCreateKernel(prog, "kernel_moe_zero_dst", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // moe_sort_by_expert + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "moe_sort_by_expert.cl.h" + }; +#else + const std::string kernel_src = read_file("moe_sort_by_expert.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_histogram = clCreateKernel(prog, "kernel_moe_histogram", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_scan = clCreateKernel(prog, "kernel_moe_scan", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_fill = clCreateKernel(prog, "kernel_moe_fill", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_scatter = clCreateKernel(prog, "kernel_moe_scatter", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_scatter_stable = clCreateKernel(prog, "kernel_moe_scatter_stable", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "moe_add_id_glu.cl.h" + }; +#else + const std::string kernel_src = read_file("moe_add_id_glu.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat_id.kernel_add_id_add_id_swiglu_oai = clCreateKernel( + prog, "kernel_add_id_add_id_swiglu_oai", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // moe_combine (fused router-weight mul + cross-expert sum) + { + #ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "moe_combine.cl.h" + }; + #else + const std::string kernel_src = read_file("moe_combine.cl"); + #endif + cl_program prog = build_program_from_source( + backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_combine_f32 = + clCreateKernel(prog, "kernel_moe_combine_f32", &err), err)); + CL_CHECK((backend_ctx->mul_mat_id.kernel_moe_combine_bias_f32 = + clCreateKernel(prog, "kernel_moe_combine_bias_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_id_f32_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_id_f32_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_id_f32_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat_id.kernel_mul_mv_id_f32_f32 = clCreateKernel(prog, "kernel_mul_mv_id_f32_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mm_id_f32_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mm_id_f32_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mm_id_f32_f32.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->mul_mat_id.kernel_mul_mm_id_f32_f32 = clCreateKernel(prog, "kernel_mul_mm_id_f32_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_id_q4_0_f32_8x_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_id_q4_0_f32_8x_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_id_q4_0_f32_8x_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_mul_mv_id_q4_0_f32_8x_flat = clCreateKernel(prog, "kernel_mul_mv_id_q4_0_f32_8x_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_id_q8_0_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_id_q8_0_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_id_q8_0_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_mul_mv_id_q8_0_f32 = clCreateKernel(prog, "kernel_mul_mv_id_q8_0_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_id_q8_0_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_id_q8_0_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_id_q8_0_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_mul_mv_id_q8_0_f32_flat = clCreateKernel(prog, "kernel_mul_mv_id_q8_0_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_id_mxfp4_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_id_mxfp4_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_id_mxfp4_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_mul_mv_id_mxfp4_f32 = clCreateKernel(prog, "kernel_mul_mv_id_mxfp4_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // mul_mv_id_mxfp4_f32_flat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "mul_mv_id_mxfp4_f32_flat.cl.h" + }; +#else + const std::string kernel_src = read_file("mul_mv_id_mxfp4_f32_flat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->mul_mat_id.kernel_mul_mv_id_mxfp4_f32_flat = clCreateKernel(prog, "kernel_mul_mv_id_mxfp4_f32_flat", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +static void moe_router_reoerder(ggml_backend_t backend, const ggml_tensor * src, int ne20) { + cl_int err; + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *)src->extra; + cl_ulong offset = extra->offset + src->view_offs; + + const int ne21 = src->ne[1]; + const int nb21 = src->nb[1]; + const int ne02 = nb21 / src->nb[0]; + const int n_tile_size = 32; + const int max_post_router_tile = (ne20 * ne21 / n_tile_size) + ne02; + + cl_buffer_region region; + + backend_ctx->prealloc_post_router.allocate(backend_ctx->context, sizeof(int) * max_post_router_tile * n_tile_size); + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + cl_mem post_router_buf = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + backend_ctx->prealloc_emap.allocate(backend_ctx->context, sizeof(short) * max_post_router_tile); + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + cl_mem emap_buf = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + if (sizeof(int) * ne02 > backend_ctx->prealloc_hist.size) { + backend_ctx->prealloc_hist.allocate(backend_ctx->context, sizeof(int) * ne02); + const int zero = 0; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, backend_ctx->prealloc_hist.buffer, &zero, sizeof(zero), 0, sizeof(int) * ne02, 0, nullptr, nullptr)); + } + region.origin = 0; + region.size = sizeof(int) * ne02; + cl_mem hist_buf = clCreateSubBuffer(backend_ctx->prealloc_hist.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + backend_ctx->prealloc_tile_offset.allocate(backend_ctx->context, sizeof(int) * ne02); + region.origin = 0; + region.size = sizeof(int) * ne02; + cl_mem tile_offset_buf = clCreateSubBuffer(backend_ctx->prealloc_tile_offset.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + backend_ctx->prealloc_slot_counter.allocate(backend_ctx->context, sizeof(int) * ne02); + region.origin = 0; + region.size = sizeof(int) * ne02; + cl_mem slot_counter_buf = clCreateSubBuffer(backend_ctx->prealloc_slot_counter.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + backend_ctx->prealloc_total_tiles.allocate(backend_ctx->context, sizeof(int)); + region.origin = 0; + region.size = sizeof(int); + cl_mem total_tiles_buf = clCreateSubBuffer(backend_ctx->prealloc_total_tiles.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + // Histogram + cl_kernel kernel = backend_ctx->mul_mat_id.kernel_moe_histogram; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &hist_buf)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset)); + + size_t histogram_global_size[] = {(size_t)(((ne21 + 63) / 64) * 64), static_cast(ne20), 1}; + size_t histogram_local_size[] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, histogram_global_size, histogram_local_size, src); + + // Scan + kernel = backend_ctx->mul_mat_id.kernel_moe_scan; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &hist_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &tile_offset_buf)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &total_tiles_buf)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &slot_counter_buf)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n_tile_size)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne02)); + + size_t scan_global_size[] = {1}; + size_t scan_local_size[] = {1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 1, scan_global_size, scan_local_size, src); + + // Fill + kernel = backend_ctx->mul_mat_id.kernel_moe_fill; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &post_router_buf)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &total_tiles_buf)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(int), &n_tile_size)); + + size_t fill_global_size[] = {(size_t)(((max_post_router_tile + 63) / 64) * 64), n_tile_size, 1}; + size_t fill_local_size[] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, fill_global_size, fill_local_size, src); + + static const bool stable_scatter = []{ + const char * env = getenv("GGML_OPENCL_MOE_STABLE_SCATTER"); + return !env || env[0] == '\0' || env[0] != '0'; + }(); + + if (stable_scatter) { + kernel = backend_ctx->mul_mat_id.kernel_moe_scatter_stable; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &post_router_buf)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &emap_buf)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &tile_offset_buf)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset)); + + size_t scatter_global_size[] = {64, (size_t) ne02}; + size_t scatter_local_size[] = {64, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, scatter_global_size, scatter_local_size, src); + } else { + kernel = backend_ctx->mul_mat_id.kernel_moe_scatter; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &post_router_buf)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &emap_buf)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &tile_offset_buf)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &slot_counter_buf)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offset)); + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, histogram_global_size, histogram_local_size, src); + } + + // [MOE_TILES] env-gated padding probe: read back total_tiles (= Sum_e + // ceil(k_e/n_tile_size)) and compare to the ideal tile count for the real + // routing count. Quantifies the per-expert tile-padding waste. Blocking + // readback perturbs timing -> diagnostic only. + if (getenv("GGML_OPENCL_MOE_TILES_DEBUG")) { + int h_total = 0; + clFinish(backend_ctx->queue); + CL_CHECK(clEnqueueReadBuffer(backend_ctx->queue, total_tiles_buf, CL_TRUE, 0, sizeof(int), &h_total, 0, NULL, NULL)); + const int routings = ne20 * ne21; + const int ideal = (routings + n_tile_size - 1) / n_tile_size; + const int slots = h_total * n_tile_size; + fprintf(stderr, "[MOE_TILES] routings=%d (ne20=%d ne21=%d nexp=%d) total_tiles=%d ideal=%d slots=%d pad=%.1f%%\n", + routings, ne20, ne21, ne02, h_total, ideal, slots, + routings > 0 ? 100.0 * (slots - routings) / routings : 0.0); + fflush(stderr); + } + + CL_CHECK(clReleaseMemObject(hist_buf)); + CL_CHECK(clReleaseMemObject(tile_offset_buf)); + CL_CHECK(clReleaseMemObject(total_tiles_buf)); + CL_CHECK(clReleaseMemObject(slot_counter_buf)); + CL_CHECK(clReleaseMemObject(post_router_buf)); + CL_CHECK(clReleaseMemObject(emap_buf)); +} + +// Use the per-token MoE GEMV instead of the tiled expert GEMM for small batches. +// The GEMV costs one weight pass per token, the GEMM pads every expert to a +// 32-token tile, so the GEMV wins while tokens rarely share an expert. +// Default on for X2E up to 4 tokens while 2 * tokens * used < experts. +// GGML_OPENCL_MOE_GEMV_MAX_TOK overrides with a plain token limit (1 = decode only). +static bool use_adreno_moe_gemv_small_batch(const ggml_backend_opencl_context * backend_ctx, int n_tokens, int n_used, int n_expert) { + if (n_tokens <= 1) { + return true; + } + static const char * env = getenv("GGML_OPENCL_MOE_GEMV_MAX_TOK"); + if (env) { + return n_tokens <= std::max(1, atoi(env)); + } + return backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && n_tokens <= 4 && + 2 * (int64_t) n_tokens * n_used < (int64_t) n_expert; +} + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS +static void ggml_cl_moe_gemm_malu_bin( + ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, std::initializer_list weights, bool use_sa, + cl_mem sub_buf_src1_pre, cl_mem buf_src2, cl_mem buf_src2_emap, + cl_mem dst_data, cl_ulong offsetd, size_t n_dst, const ggml_tensor * dst, + int ne00, int ne01, unsigned short map_ratio, int max_post_router_tile, int n_tile_size) { + cl_int status; + + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + cl_uint ne00_u = ne00; + cl_uint tile_u = n_tile_size; + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00_u)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &tile_u)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + // dst as an image + cl_buffer_region region; + region.origin = offsetd; + region.size = n_dst * sizeof(float); + cl_mem sub_buf_dst = clCreateSubBuffer(dst_data, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, n_dst, 0,0,0,0,0,0,0, {sub_buf_dst}}; + cl_mem buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + int aidx = 0; + for (cl_mem w : weights) { + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &w)); + } + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + if (use_sa) { + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + } + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); +} + +// Run a cl_qcom_kernel_cooperative_matrix MoE GEMM: f16 reorder of the activations, then the GEMM. +// The weight buffers come first in the kernel args, in the order of the ns kernel of the same type. +static void ggml_cl_moe_gemm_coopmat( + ggml_backend_opencl_context * backend_ctx, cl_kernel kernel, std::initializer_list weights, + cl_mem sub_buf_src1_pre, cl_mem buf_src2, cl_mem buf_src2_emap, + cl_mem dst_data, cl_ulong offsetd, size_t n_dst, const ggml_tensor * dst, + int ne00, int ne01, unsigned short map_ratio, int max_post_router_tile, int n_tile_size) { + cl_int status; + + // f16 reordered activations, read by the coopmat kernel as a buffer + cl_buffer_region region; + region.origin = 0; + region.size = (size_t)ne00 * max_post_router_tile * n_tile_size * sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + cl_mem buf_src1_reordered = clCreateSubBuffer(backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + cl_kernel rk = backend_ctx->mul_mat_id.kernel_moe_reorder_b_f16; + unsigned int ne00_u = ne00; + unsigned int tile_u = n_tile_size; + CL_CHECK(clSetKernelArg(rk, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rk, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rk, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(rk, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rk, 4, sizeof(unsigned int), &ne00_u)); + CL_CHECK(clSetKernelArg(rk, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(rk, 6, sizeof(unsigned int), &tile_u)); + + size_t rk_local_size[3] = {256, 1, 1}; + size_t rk_global_size[3] = {(size_t)(((ne00 / 8) + 255) / 256 * 256), (size_t)max_post_router_tile * n_tile_size, 1}; + backend_ctx->enqueue_ndrange_kernel(rk, 3, rk_global_size, rk_local_size, dst); + + // dst as an image + region.origin = offsetd; + region.size = n_dst * sizeof(float); + cl_mem sub_buf_dst = clCreateSubBuffer(dst_data, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, n_dst, 0,0,0,0,0,0,0, {sub_buf_dst}}; + cl_mem buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + int arg_idx = 0; + for (cl_mem w : weights) { + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &w)); + } + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // coopmat kernels need a uniform NDRange + size_t global_size[3] = {64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile}; + size_t local_size[3] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); +} +#endif + +static void ggml_cl_mul_mat_id_float(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + cl_kernel kernel = backend_ctx->mul_mat_id.kernel_mul_mv_id_f32_f32; + const ggml_tensor * src2 = dst->src[2]; + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) src1->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *) src2->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offset1 = extra1->offset + src1->view_offs; + const cl_ulong offset2 = extra2->offset + src2->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ncols = src0->ne[0]; + const int ne11 = src1->ne[1]; + const int nrows = dst->ne[0]; + // BF16 tensors are stored as F16 on the device. Activations remain F32. + const int src0_f16 = src0->type == GGML_TYPE_F32 ? 0 : 1; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb20 = src2->nb[0]; + const cl_ulong nb21 = src2->nb[1]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + + // The router uses the IDs row stride as its expert count. + const size_t router_experts = src2->nb[1]/sizeof(int32_t); + if (src1->ne[2] >= 16 && ncols >= 64 && nrows >= 32 && ggml_is_contiguous(dst) && + src2->nb[0] == sizeof(int32_t) && src2->nb[1] % sizeof(int32_t) == 0 && + router_experts >= (size_t) src0->ne[2] && router_experts <= 1024 && + dst->ne[1]*dst->ne[2] >= (int64_t) router_experts*4 && + dst->ne[1]*dst->ne[2] >= 16384/nrows && + dst->ne[1]*dst->ne[2] <= INT_MAX - 32*(int64_t) router_experts) { + const int nused = dst->ne[1]; + const size_t max_tiles = (size_t) nused*dst->ne[2]/32 + router_experts; + moe_router_reoerder(backend, src2, nused); + backend_ctx->toggle_reorder = true; + const float zero = 0.0f; + CL_CHECK(clEnqueueFillBuffer(backend_ctx->queue, extrad->data_device, &zero, sizeof(zero), offsetd, ggml_nbytes(dst), 0, nullptr, nullptr)); + kernel = backend_ctx->mul_mat_id.kernel_mul_mm_id_f32_f32; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &backend_ctx->prealloc_post_router.buffer)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &backend_ctx->prealloc_emap.buffer)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &backend_ctx->prealloc_total_tiles.buffer)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ncols)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &nrows)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &nused)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &src0_f16)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb2)); + size_t global_work_size[] = {(size_t) ((nrows + 63)/64)*128, max_tiles}; + size_t local_work_size[] = {128, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); + return; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ncols)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &src0_f16)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb20)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &nrows)); + + size_t global_work_size[] = {(size_t) ((dst->ne[0] + 3)/4)*64, (size_t) dst->ne[1], (size_t) dst->ne[2]}; + size_t local_work_size[] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + if (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16) { + ggml_cl_mul_mat_id_float(backend, src0, src1, dst); + return; + } + + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + const ggml_tensor * src2 = dst->src[2]; + GGML_ASSERT(src2); + GGML_ASSERT(src2->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offset2 = extra2->offset + src2->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_UNUSED(offset0); + +#ifdef GGML_OPENCL_SOA_Q + // SoA extra lives on view_src (view->extra is pre-SoA). + const ggml_tensor * soa0_src = src0->view_src != nullptr ? src0->view_src : src0; + ggml_tensor_extra_cl_q4_0 * extra0_q4_0 = (ggml_tensor_extra_cl_q4_0 *)soa0_src->extra; + ggml_tensor_extra_cl_q4_1 * extra0_q4_1 = (ggml_tensor_extra_cl_q4_1 *)soa0_src->extra; + ggml_tensor_extra_cl_q5_0 * extra0_q5_0 = (ggml_tensor_extra_cl_q5_0 *)soa0_src->extra; + ggml_tensor_extra_cl_q5_1 * extra0_q5_1 = (ggml_tensor_extra_cl_q5_1 *)soa0_src->extra; + ggml_tensor_extra_cl_q4_K * extra0_q4_K = (ggml_tensor_extra_cl_q4_K *)soa0_src->extra; + ggml_tensor_extra_cl_q5_K * extra0_q5_K = (ggml_tensor_extra_cl_q5_K *)soa0_src->extra; + ggml_tensor_extra_cl_q6_K * extra0_q6_K = (ggml_tensor_extra_cl_q6_K *)soa0_src->extra; + ggml_tensor_extra_cl_mxfp4 * extra0_mxfp4 = (ggml_tensor_extra_cl_mxfp4 *)soa0_src->extra; + ggml_tensor_extra_cl_q8_0 * extra0_q8_0 = (ggml_tensor_extra_cl_q8_0 *)soa0_src->extra; + +#endif + + // TODO: general MoE for the following types + (void)extra0_q4_1; + (void)extra0_q5_0; + (void)extra0_q5_1; + (void)extra0_q4_K; + (void)extra0_q5_K; + (void)extra0_q6_K; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne10 = src1->ne[0]; + const int ne11 = src1->ne[1]; + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; + + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const int ne20 = src2->ne[0]; + const int ne21 = src2->ne[1]; + + const cl_ulong nb21 = src2->nb[1]; + const cl_ulong nb20 = src2->nb[0]; + + UNUSED(nb20); + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + const int ne2 = dst->ne[2]; + + GGML_UNUSED(ne2); + + const int r2 = ne12/ne02; + const int r3 = ne13/ne03; + const int dst_rows = ne20*ne21; // ne20 = n_used_experts, ne21 = n_rows + + GGML_ASSERT(ne00 == ne10); + + // The matmul kernels only write the rows an expert owns, so zero the skipped rows here. + { + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + cl_kernel kernel_zero = backend_ctx->mul_mat_id.kernel_moe_zero_dst; + CL_CHECK(clSetKernelArg(kernel_zero, 0, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel_zero, 1, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel_zero, 2, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel_zero, 3, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel_zero, 4, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel_zero, 5, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel_zero, 6, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel_zero, 7, sizeof(int), &ne0)); + + size_t zero_local[3] = {1, 1, 64}; + size_t zero_global[3] = {(size_t) ne20, (size_t) ne21, 64}; + backend_ctx->enqueue_ndrange_kernel(kernel_zero, 3, zero_global, zero_local, dst); + } + + int sgs = 32; // subgroup size + int nsg = 1; // number of subgroups + int nrows = 1; // number of row in src1 + int ndst = 4; // number of values produced by each subgroup + + const int n_tile_size = 32; + const int max_post_router_tile = (ne20 * ne21 / n_tile_size) + ne02; + + GGML_UNUSED(max_post_router_tile); + + cl_kernel kernel; + + // subgroup mat vec + switch (src0->type) { + case GGML_TYPE_Q4_0: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q4_0_f32_ns; + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20 * ne12); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + const int ids_stride = (int) (nb21 / sizeof(int)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->q)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + + } else { // for gemm + // dp4a (int8) prefill GEMM variant + static const char * q4_0_moe_dp4a_env = getenv("GGML_OPENCL_Q4_0_MOE_DP4A"); + + // It turns out that the prebuilt kernel only outperforms the dp4a variant (on X2-90) + // at very large routing counts, so we gate its use accordingly using moe_bin_min, + // which can be overridden via the GGML_OPENCL_MOE_BIN_MIN_ROUTINGS environment variable. + // The routing count is ne20 * ne21 (n_expert_used * n_tokens). + static const char * moe_bin_min_env = getenv("GGML_OPENCL_MOE_BIN_MIN_ROUTINGS"); + const int moe_bin_min = moe_bin_min_env ? atoi(moe_bin_min_env) : 4096; + + // whether bin kernels are available + const bool bin_available = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_bin != nullptr; + const bool dp4a_bin_available = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_bin != nullptr; + + bool use_moe_dp4a = q4_0_moe_dp4a_env + ? (atoi(q4_0_moe_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E + && (dp4a_bin_available || !bin_available + || (int)(ne20 * ne21) < moe_bin_min)); + // dot prod has to be available + use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; + + const bool use_bin_kernel = bin_available && !use_moe_dp4a; + + kernel = use_bin_kernel + ? backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_bin + : backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns; + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; + cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; + cl_mem buf_src2, buf_src2_emap; + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * q4_0_moe_malu_env = getenv("GGML_OPENCL_Q4_0_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!q4_0_moe_malu_env || atoi(q4_0_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_malu_bin, + { extra0_q4_0->q_img, extra0_q4_0->d }, true, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels + { + static const char * q4_0_moe_coopmat_env = getenv("GGML_OPENCL_Q4_0_MOE_COOPMAT"); + if (!use_moe_dp4a && (q4_0_moe_coopmat_env ? (atoi(q4_0_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_coopmat != nullptr) { + unsigned short cp_map_ratio = ne20 / ne11; + GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_f32_ns_coopmat, + { extra0_q4_0->q_img, extra0_q4_0->d }, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + if (!use_moe_dp4a) { + // Create image for reordered src1 + // Use pre-allocated placeholder + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1; + cl_image_desc image_desc_buf_src1; + image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + if (use_bin_kernel) { + // bin kernel uses slightly different image format + image_format_buf_src1 = {CL_R, CL_FLOAT}; + image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); + } + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + } + + // MoE kernel prepare + // Create sub buffer for dst + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + if (use_moe_dp4a) { + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + + // fused reorder + q8_1 quant straight from the original activations + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + // dp4a GEMM + cl_kernel dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_bin) { + dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_0_q8_1_dp4a_bin; + } + int aidx = 0; + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_0->q_img)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + return; + } + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->q_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } // fallback to generic Q4_0 MoE kernel + +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + kernel = backend_ctx->mul_mat_id.kernel_mul_mv_id_q4_0_f32_8x_flat; + + if (backend_ctx->gpu_family == INTEL) { + sgs = 16; + nsg = 1; + ndst = 8; + } else if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + nsg = 1; + ndst = 8; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q4_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q4_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &r3)); + + break; + } + case GGML_TYPE_Q4_1: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q4_1_f32_ns; + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20 * ne12); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + const int ids_stride = (int) (nb21 / sizeof(int)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->q)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->m)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + + } else { // for gemm + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_bin) { + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_bin; + } + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; + cl_mem buf_src2, buf_src2_emap; + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * q4_1_moe_malu_env = getenv("GGML_OPENCL_Q4_1_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!q4_1_moe_malu_env || atoi(q4_1_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_q8_1_dp4a_malu_bin, + { extra0_q4_1->q_img, extra0_q4_1->d, extra0_q4_1->m }, true, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels + { + static const char * q4_1_moe_coopmat_env = getenv("GGML_OPENCL_Q4_1_MOE_COOPMAT"); + if ((q4_1_moe_coopmat_env ? (atoi(q4_1_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_coopmat != nullptr) { + unsigned short cp_map_ratio = ne20 / ne11; + GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_coopmat, + { extra0_q4_1->q_img, extra0_q4_1->d, extra0_q4_1->m }, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // Create image for reordered src1 + // Use pre-allocated placeholder + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1; + cl_image_desc image_desc_buf_src1; + image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q4_1_f32_ns_bin) { + // bin kernel uses slightly different image format + image_format_buf_src1 = {CL_R, CL_FLOAT}; + image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); + } + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + + // MoE kernel prepare + // Create sub buffer for dst + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->q_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_1->m)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } +#endif //GGML_OPENCL_USE_ADRENO_KERNELS + } + case GGML_TYPE_Q5_0: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q5_0_f32_ns; + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20 * ne12); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + const int ids_stride = (int) (nb21 / sizeof(int)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qs)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + + } else { // for gemm + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_f32_ns; + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; + cl_mem buf_src2, buf_src2_emap; + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Generic dp4a MoE GEMM + { + static const char * q5mdp4a_env = getenv("GGML_OPENCL_Q5_MOE_DP4A"); + const bool q5mdp4a_on = q5mdp4a_env ? (atoi(q5mdp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + const bool use_q5_moe_dp4a = q5mdp4a_on + && backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q50 != nullptr + && extra0_q5_0->scale != nullptr; + + if (use_q5_moe_dp4a) { + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + unsigned short map_ratio_q5 = ne20 / ne11; + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio_q5)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + cl_mem dp_sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + cl_image_format dp_ifd = {CL_R, CL_FLOAT}; + cl_image_desc dp_idd = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {dp_sub_buf_dst}}; + cl_mem dp_buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &dp_ifd, &dp_idd, NULL, &status); + CL_CHECK(status); + + int ne00i = (int)ne00, ne01i = (int)ne01; + cl_kernel dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q50; + int has_min_q5 = 1; + int aidx = 0; + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->qs_img)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->qh)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->scale)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_0->min)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &dp_buf_dst_image)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00i)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01i)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &has_min_q5)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(dp_sub_buf_dst); + clReleaseMemObject(dp_buf_dst_image); + return; + } + } + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * q5_0_moe_malu_env = getenv("GGML_OPENCL_Q5_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!q5_0_moe_malu_env || atoi(q5_0_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_q8_1_dp4a_malu_bin, + { extra0_q5_0->qs_img, extra0_q5_0->qh, extra0_q5_0->d }, false, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels + { + static const char * q5_0_moe_coopmat_env = getenv("GGML_OPENCL_Q5_0_MOE_COOPMAT"); + if ((q5_0_moe_coopmat_env ? (atoi(q5_0_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_f32_ns_coopmat != nullptr) { + unsigned short cp_map_ratio = ne20 / ne11; + GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q5_0_f32_ns_coopmat, + { extra0_q5_0->qs_img, extra0_q5_0->qh, extra0_q5_0->d }, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // Create image for reordered src1 + // Use pre-allocated placeholder + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1; + cl_image_desc image_desc_buf_src1; + image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + + // MoE kernel prepare + // Create sub buffer for dst + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qs_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_0->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } +#endif //GGML_OPENCL_USE_ADRENO_KERNELS + } + case GGML_TYPE_Q5_1: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q5_1_f32_ns; + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20 * ne12); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + const int ids_stride = (int) (nb21 / sizeof(int)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qs)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->m)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + } else { // for gemm + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_f32_ns; + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; + cl_mem buf_src2, buf_src2_emap; + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * q5_1_moe_malu_env = getenv("GGML_OPENCL_Q5_1_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!q5_1_moe_malu_env || atoi(q5_1_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_q8_1_dp4a_malu_bin, + { extra0_q5_1->qs_img, extra0_q5_1->qh, extra0_q5_1->d, extra0_q5_1->m }, true, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels + { + static const char * q5_1_moe_coopmat_env = getenv("GGML_OPENCL_Q5_1_MOE_COOPMAT"); + if ((q5_1_moe_coopmat_env ? (atoi(q5_1_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_f32_ns_coopmat != nullptr) { + unsigned short cp_map_ratio = ne20 / ne11; + GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q5_1_f32_ns_coopmat, + { extra0_q5_1->qs_img, extra0_q5_1->qh, extra0_q5_1->d, extra0_q5_1->m }, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // Create image for reordered src1 + // Use pre-allocated placeholder + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1; + cl_image_desc image_desc_buf_src1; + image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + + // MoE kernel prepare + // Create sub buffer for dst + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qs_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_1->m)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } +#endif //GGML_OPENCL_USE_ADRENO_KERNELS + } + case GGML_TYPE_Q8_0: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // MoE GEMM for q8_0 at prefill (ne12>1) + // There is no corresponding gemv_moe, so the code path is different here + static const char * moe_gemm_q8_env = getenv("GGML_OPENCL_MOE_GEMM_Q8"); + const bool moe_gemm_q8 = moe_gemm_q8_env + ? (atoi(moe_gemm_q8_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + if (moe_gemm_q8 && use_adreno_moe_kernels(backend_ctx, src0) && ne12 > 1) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q8_0_f32_ns; + + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; + cl_mem buf_src2, buf_src2_emap; + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations (group tokens by expert into tiles of 32) + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Generic dp4a MoE GEMM + { + static const char * q8mdp4a_env = getenv("GGML_OPENCL_Q8_MOE_DP4A"); + const bool q8mdp4a_on = q8mdp4a_env ? (atoi(q8mdp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + const bool use_q8_moe_dp4a = q8mdp4a_on + && backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q80 != nullptr + && extra0_q8_0->scale != nullptr; + if (use_q8_moe_dp4a) { + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + unsigned short map_ratio_q8 = ne20 / ne11; + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio_q8)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + // dst image + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + cl_mem dp_sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + cl_image_format dp_ifd = {CL_R, CL_FLOAT}; + cl_image_desc dp_idd = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {dp_sub_buf_dst}}; + cl_mem dp_buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &dp_ifd, &dp_idd, NULL, &status); + CL_CHECK(status); + + int ne00i = (int)ne00, ne01i = (int)ne01; + cl_kernel dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q80; + int has_min_q8 = 0; + int aidx = 0; + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q8_0->q)); // flat int8 codes [expert][row][K] + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q8_0->scale)); // uniform scale[16] + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q8_0->scale)); // dummy min (has_min=0, unread) + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &dp_buf_dst_image)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00i)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01i)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &has_min_q8)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(dp_sub_buf_dst); + clReleaseMemObject(dp_buf_dst_image); + return; + } + } + + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + + // dst image + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q8_0->q)); // flat q8_0 quants + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q8_0->d)); // flat q8_0 scales + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat_id.kernel_mul_mv_id_q8_0_f32_flat; + + if (backend_ctx->gpu_family == INTEL) { + sgs = 16; + nsg = 2; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + nsg = 2; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0_q8_0->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_q8_0->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); +#else + kernel = backend_ctx->mul_mat_id.kernel_mul_mv_id_q8_0_f32; + + if (backend_ctx->gpu_family == INTEL) { + sgs = 16; + nsg = 2; + ndst = 4; + } else if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + nsg = 2; + ndst = 4; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne1)); +#endif // GGML_OPENCL_SOA_Q + break; + } + case GGML_TYPE_Q4_K: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q4_k_f32_ns; + + // Weight-as-texture MoE decode GEMV + static const char * moe_decode_wimg_env = getenv("GGML_OPENCL_MOE_DECODE_WIMG"); + const bool moe_decode_wimg_on = moe_decode_wimg_env + ? (atoi(moe_decode_wimg_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + const bool use_moe_decode_wimg = moe_decode_wimg_on + && backend_ctx->mul_mat_id.kernel_gemv_moe_q4_k_f32_ns_wimg != nullptr + && extra0_q4_K->q_img != nullptr; + if (use_moe_decode_wimg) { + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q4_k_f32_ns_wimg; + } + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20 * ne12); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + const int ids_stride = (int) (nb21 / sizeof(int)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), use_moe_decode_wimg ? &extra0_q4_K->q_img : &extra0_q4_K->q)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->dm)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->s)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + + } else { // for gemm + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_bin) { + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_bin; + } + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; + cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; + cl_mem buf_src2, buf_src2_emap; + + // dp4a (int8) prefill GEMM variant + static const char * q4k_moe_dp4a_env = getenv("GGML_OPENCL_Q4K_MOE_DP4A"); + bool use_moe_dp4a = (q4k_moe_dp4a_env != nullptr) + ? (atoi(q4k_moe_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E); + // dot prod has to be available + use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; + // bin kernel takes precedence, dp4a bin kernel has higher priority than normal bin kernel + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_bin == nullptr) { + use_moe_dp4a = use_moe_dp4a && backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_bin == nullptr; + } + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * q4_k_moe_malu_env = getenv("GGML_OPENCL_Q4K_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!q4_k_moe_malu_env || atoi(q4_k_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_malu_bin, + { extra0_q4_K->q_img, extra0_q4_K->d, extra0_q4_K->dm, extra0_q4_K->s }, true, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels + { + static const char * q4_k_moe_coopmat_env = getenv("GGML_OPENCL_Q4K_MOE_COOPMAT"); + if (!use_moe_dp4a && (q4_k_moe_coopmat_env ? (atoi(q4_k_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_coopmat != nullptr) { + unsigned short cp_map_ratio = ne20 / ne11; + GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_coopmat, + { extra0_q4_K->q_img, extra0_q4_K->d, extra0_q4_K->dm, extra0_q4_K->s }, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + if (!use_moe_dp4a) { + // Create image for reordered src1 + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_f32_ns_bin) { + // bin kernel uses slightly different image format + image_format_buf_src1 = {CL_R, CL_FLOAT}; + image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); + } + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + } + + // MoE kernel prepare + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + if (use_moe_dp4a) { + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + + // fused reorder + q8_1 quant straight from the original + // activations (no intermediate f32 reorder buffer) + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + // dp4a GEMM + cl_kernel dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_bin) { + dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q4_k_q8_1_dp4a_bin; + } + + int aidx = 0; + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->q_img)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->d)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->dm)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q4_K->s)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + return; + } + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->q_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->dm)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q4_K->s)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } +#endif //GGML_OPENCL_USE_ADRENO_KERNELS + } + case GGML_TYPE_Q5_K: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q5_k_f32_ns; + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20 * ne12); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + const int ids_stride = (int) (nb21 / sizeof(int)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->q)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->dm)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->s)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + + } else { // for gemm + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_f32_ns; + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, buf_src1_reordered, image_src1_reordered, sub_buf_dst, buf_dst_image; + cl_mem buf_src2, buf_src2_emap; + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Generic dp4a MoE GEMM + { + static const char * q5kmdp4a_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A"); + const bool q5kmdp4a_on = q5kmdp4a_env ? (atoi(q5kmdp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + bool use_moe_dp4a = q5kmdp4a_on + && backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q5k != nullptr + && extra0_q5_K->scale != nullptr; + // dot prod has to be available + use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; + + if (use_moe_dp4a) { + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + unsigned short map_ratio_q5k = ne20 / ne11; + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio_q5k)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + cl_mem dp_sub_buf_dst = clCreateSubBuffer(extrad->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + cl_image_format dp_ifd = {CL_R, CL_FLOAT}; + cl_image_desc dp_idd = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {dp_sub_buf_dst}}; + cl_mem dp_buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &dp_ifd, &dp_idd, NULL, &status); + CL_CHECK(status); + + int ne00i = (int)ne00, ne01i = (int)ne01; + cl_kernel dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q8_1_dp4a_q5k; + int has_min_q5k = 1; + int aidx = 0; + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->q_img)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->qh)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->scale)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_q5_K->min)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &dp_buf_dst_image)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00i)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01i)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &has_min_q5k)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(dp_sub_buf_dst); + clReleaseMemObject(dp_buf_dst_image); + return; + } + } + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * q5_k_moe_malu_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!q5_k_moe_malu_env || atoi(q5_k_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_q8_1_dp4a_malu_bin, + { extra0_q5_K->q_img, extra0_q5_K->qh, extra0_q5_K->s, extra0_q5_K->d, extra0_q5_K->dm }, true, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels + { + static const char * q5_k_moe_coopmat_env = getenv("GGML_OPENCL_Q5K_MOE_COOPMAT"); + if ((q5_k_moe_coopmat_env ? (atoi(q5_k_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_f32_ns_coopmat != nullptr) { + unsigned short cp_map_ratio = ne20 / ne11; + GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q5_k_f32_ns_coopmat, + { extra0_q5_K->q_img, extra0_q5_K->qh, extra0_q5_K->s, extra0_q5_K->d, extra0_q5_K->dm }, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // Create image for reordered src1 + // Use pre-allocated placeholder + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + + // MoE kernel prepare + // Create sub buffer for dst + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->q_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->s)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q5_K->dm)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } +#endif //GGML_OPENCL_USE_ADRENO_KERNELS + } + case GGML_TYPE_Q6_K: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (use_adreno_moe_gemv_small_batch(backend_ctx, ne12, ne20, ne02)) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_q6_k_f32_ns; + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = (size_t) nb21 * (ne21 - 1) + ne20 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20 * ne12); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + const int ids_stride = (int) (nb21 / sizeof(int)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->ql)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ids_stride)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + + } else { // for gemm + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_bin) { + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_bin; + } + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; + cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; + cl_mem buf_src2, buf_src2_emap; + + // dp4a (int8) q6_K MoE prefill GEMM + static const char * q6k_moe_dp4a_env = getenv("GGML_OPENCL_Q6K_MOE_DP4A"); + bool use_moe_dp4a = (q6k_moe_dp4a_env != nullptr) + ? (atoi(q6k_moe_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E + || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E); + // dot prod has to be available + use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; + // bin kernel takes precedence, dp4a bin kernel has higher priority than normal bin kernel + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_bin == nullptr) { + use_moe_dp4a = use_moe_dp4a && backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_bin == nullptr; + } + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * q6_k_moe_malu_env = getenv("GGML_OPENCL_Q6K_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!q6_k_moe_malu_env || atoi(q6_k_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_malu_bin, + { extra0_q6_K->ql_img, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, false, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + // cl_qcom_kernel_cooperative_matrix GEMM (A850 only) takes precedence over the bin and Adreno clc kernels + { + static const char * q6_k_moe_coopmat_env = getenv("GGML_OPENCL_Q6K_MOE_COOPMAT"); + if (!use_moe_dp4a && (q6_k_moe_coopmat_env ? (atoi(q6_k_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_coopmat != nullptr) { + unsigned short cp_map_ratio = ne20 / ne11; + GGML_ASSERT(((cp_map_ratio == 1) || (cp_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_coopmat(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_coopmat, + { extra0_q6_K->ql_img, extra0_q6_K->qh, extra0_q6_K->s, extra0_q6_K->d }, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, cp_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + if (!use_moe_dp4a) { + // Create image for reordered src1 + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_f32_ns_bin) { + // bin kernel uses slightly different image format + image_format_buf_src1 = {CL_R, CL_FLOAT}; + image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); + } + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + } + + // MoE kernel prepare + // Create sub buffer for dst + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + if (use_moe_dp4a) { + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + + // fused reorder + q8_1 quant from the original activations + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + cl_kernel dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_bin) { + dk = backend_ctx->mul_mat_id.kernel_gemm_moe_q6_k_q8_1_dp4a_bin; + } + + int qi = 0; + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->ql_img)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(dk, qi++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + return; + } + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->ql_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->qh)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->s)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_q6_K->d)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + clReleaseMemObject(image_src1_reordered); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } +#endif //GGML_OPENCL_USE_ADRENO_KERNELS + } + case GGML_TYPE_MXFP4: { +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, src0)) { + cl_int status; + + size_t local_size[3] = {64, 2, 1}; + size_t global_size[3] = {64, 2, 1}; + + if (ne12 == 1) { // for gemv + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_mxfp4_f32_ns; + + // Weight-as-texture MoE decode GEMV (see q4_K _wimg) + static const char * moe_decode_wimg_env = getenv("GGML_OPENCL_MOE_DECODE_WIMG"); + const bool use_moe_decode_wimg = (moe_decode_wimg_env && (atoi(moe_decode_wimg_env) != 0)) + && backend_ctx->mul_mat_id.kernel_gemv_moe_mxfp4_f32_ns_wimg != nullptr + && extra0_mxfp4->q_img != nullptr; + if (use_moe_decode_wimg) { + kernel = backend_ctx->mul_mat_id.kernel_gemv_moe_mxfp4_f32_ns_wimg; + } + + cl_mem src1_sub_buffer, buf_src1_image, buf_src2; + + // create a sub_buffer for src2 + cl_buffer_region region; + region.origin = offset2; + region.size = ne20 * ne21 * sizeof(int); + buf_src2 = clCreateSubBuffer(extra2->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // set thread grid + global_size[0] = static_cast(((ne01 + 63) / 64) * 64); + global_size[1] = 4; + global_size[2] = static_cast(ne20); + local_size[1] = 4; + + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + src1_sub_buffer = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // create image for src1 + cl_image_format image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + cl_image_desc image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne10 * ne11 * ne12 / 4), 0,0,0,0,0,0,0, {src1_sub_buffer}}; + buf_src1_image = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), use_moe_decode_wimg ? &extra0_mxfp4->q_img : &extra0_mxfp4->q)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_mxfp4->e)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src1_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne11)); + + // launch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + // deallocate sub buffers and images + CL_CHECK(clReleaseMemObject(src1_sub_buffer)); + CL_CHECK(clReleaseMemObject(buf_src1_image)); + CL_CHECK(clReleaseMemObject(buf_src2)); + + } else { // for gemm + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_bin) { + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_bin; + } + + // Reorder router if called from test-backend-ops or when new router is generated. + // Otherwise reuse the reordered result from previous mul_mat_id call. + if ((strstr(src0->name, "as") != NULL) || backend_ctx->toggle_reorder) { + moe_router_reoerder(backend, src2, ne20); + backend_ctx->toggle_reorder = false; + } + + cl_mem sub_buf_src1_pre, sub_buf_dst, buf_dst_image; + cl_mem buf_src1_reordered = nullptr, image_src1_reordered = nullptr; + cl_mem buf_src2, buf_src2_emap; + + // dp4a (int8) prefill GEMM variant + static const char * mxfp4_moe_dp4a_env = getenv("GGML_OPENCL_MXFP4_MOE_DP4A"); + bool use_moe_dp4a = mxfp4_moe_dp4a_env + ? (atoi(mxfp4_moe_dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X1E); + // dot prod has to be available + use_moe_dp4a = backend_ctx->has_integer_dot && use_moe_dp4a; + // bin kernel takes precedence, dp4a bin kernel has higher priority than normal bin kernel + // ldck dp4a bin kernel (X1) has the same priority as normal bin kernel (X2/A8x), they are not expected to coexist. + const bool use_moe_dp4a_ldck = backend_ctx->has_integer_dot && + (!mxfp4_moe_dp4a_env || atoi(mxfp4_moe_dp4a_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_bin == nullptr && + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_bin == nullptr && + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin != nullptr; + if (use_moe_dp4a_ldck) { + use_moe_dp4a = true; + } else if (backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_bin == nullptr) { + use_moe_dp4a = use_moe_dp4a && backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_bin == nullptr; + } + + // Priority on A850: coopmat (fp16) > bin kernel > Adreno clc. The dp4a path is chosen by GGML_OPENCL_MXFP4_MOE_DP4A and has its own priority. + static const char * mxfp4_moe_coopmat_env = getenv("GGML_OPENCL_MXFP4_MOE_COOPMAT"); + const bool use_moe_coopmat = !use_moe_dp4a && + (mxfp4_moe_coopmat_env ? (atoi(mxfp4_moe_coopmat_env) != 0) : true) && + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_coopmat != nullptr; + if (use_moe_coopmat) { + kernel = backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_coopmat; + } + + cl_buffer_region region; + region.origin = 0; + region.size = sizeof(int) * max_post_router_tile * n_tile_size; + GGML_ASSERT(backend_ctx->prealloc_post_router.buffer); + buf_src2 = clCreateSubBuffer(backend_ctx->prealloc_post_router.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + region.origin = 0; + region.size = sizeof(short) * max_post_router_tile; + buf_src2_emap = clCreateSubBuffer(backend_ctx->prealloc_emap.buffer, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + // Reorder activations + // create a sub_buffer for src1 + region.origin = offset1; + region.size = ne10 * ne11 * ne12 * sizeof(float); + sub_buf_src1_pre = clCreateSubBuffer(extra1->data_device, 0, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &status); + CL_CHECK(status); + + unsigned short map_ratio = ne20 / ne11; + GGML_ASSERT(((map_ratio == 1) || (map_ratio == ne20)) && "Map ratio not supported\n"); + + // binary malu int8 GEMM (A850), same enable rule as the ldck bin kernel: dp4a not disabled by the env var + { + static const char * mxfp4_moe_malu_env = getenv("GGML_OPENCL_MXFP4_MOE_DP4A"); + if (backend_ctx->has_integer_dot && (!mxfp4_moe_malu_env || atoi(mxfp4_moe_malu_env) != 0) && + backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin != nullptr) { + unsigned short malu_map_ratio = ne20 / ne11; + GGML_ASSERT(((malu_map_ratio == 1) || (malu_map_ratio == ne20)) && "Map ratio not supported\n"); + ggml_cl_moe_gemm_malu_bin(backend_ctx, backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_malu_bin, + { extra0_mxfp4->q_img, extra0_mxfp4->e }, false, + sub_buf_src1_pre, buf_src2, buf_src2_emap, extrad->data_device, offsetd, (size_t)ne0 * ne1 * ne2, dst, + ne00, ne01, malu_map_ratio, max_post_router_tile, n_tile_size); + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + return; + } + } + + if (use_moe_coopmat) { + // f16 reordered activations, read by the coopmat kernel as a buffer + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(cl_half); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + + cl_kernel rk = backend_ctx->mul_mat_id.kernel_moe_reorder_b_f16; + CL_CHECK(clSetKernelArg(rk, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rk, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rk, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(rk, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rk, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(rk, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(rk, 6, sizeof(unsigned int), &n_tile_size)); + + size_t rk_local_size[3] = {256, 1, 1}; + size_t rk_global_size[3] = {static_cast(((ne00 / 8) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + backend_ctx->enqueue_ndrange_kernel(rk, 3, rk_global_size, rk_local_size, dst); + } else if (!use_moe_dp4a) { + // Create image for reordered src1 + // Use pre-allocated placeholder + region.origin = 0; + region.size = ne00 * max_post_router_tile * n_tile_size * sizeof(float); + backend_ctx->prealloc_act_trans.allocate(backend_ctx->context, region.size); + buf_src1_reordered = clCreateSubBuffer( + backend_ctx->prealloc_act_trans.buffer, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + cl_image_format image_format_buf_src1; + cl_image_desc image_desc_buf_src1; + image_format_buf_src1 = {CL_RGBA, CL_FLOAT}; + image_desc_buf_src1 = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne00 * max_post_router_tile * n_tile_size / 4), 0,0,0,0,0,0,0, {buf_src1_reordered}}; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_f32_ns_bin) { + // bin kernel uses slightly different image format + image_format_buf_src1 = {CL_R, CL_FLOAT}; + image_desc_buf_src1.image_width = static_cast(ne00 * max_post_router_tile * n_tile_size); + } + image_src1_reordered = clCreateImage(backend_ctx->context, CL_MEM_READ_ONLY, &image_format_buf_src1, &image_desc_buf_src1, NULL, &status); + CL_CHECK(status); + + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 2, sizeof(cl_mem), &buf_src1_reordered)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 4, sizeof(unsigned int), &ne00)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 5, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 6, sizeof(unsigned int), &n_tile_size)); + + size_t reorder_b_local_size[3] = {256, 1, 1}; + size_t reorder_b_global_size[3] = {static_cast(((ne00 / 4) + 255) / 256 * 256), static_cast(max_post_router_tile * n_tile_size), 1}; + + // Dispatch reorder kernel + backend_ctx->enqueue_ndrange_kernel(backend_ctx->mul_mat_id.kernel_moe_reorder_b, 3, reorder_b_global_size, reorder_b_local_size, dst); + } + + // MoE kernel prepare + // Create sub buffer for dst + region.origin = offsetd; + region.size = ne0 * ne1 * ne2 * sizeof(float); + sub_buf_dst = clCreateSubBuffer( + extrad->data_device, + 0, + CL_BUFFER_CREATE_TYPE_REGION, + ®ion, + &status); + CL_CHECK(status); + // Create image for dst + cl_image_format image_format_buf_dst = {CL_R, CL_FLOAT}; + cl_image_desc image_desc_buf_dst = {CL_MEM_OBJECT_IMAGE1D_BUFFER, static_cast(ne0 * ne1 * ne2), 0,0,0,0,0,0,0, {sub_buf_dst}}; + buf_dst_image = clCreateImage(backend_ctx->context, CL_MEM_WRITE_ONLY, &image_format_buf_dst, &image_desc_buf_dst, NULL, &status); + CL_CHECK(status); + + if (use_moe_dp4a) { + const size_t tok_slots = (size_t)max_post_router_tile * n_tile_size; + const size_t n_blocks = tok_slots * (ne00 / 32); + backend_ctx->prealloc_moe_qa.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + backend_ctx->prealloc_moe_sa.allocate(backend_ctx->context, n_blocks * sizeof(cl_half)); + if (use_moe_dp4a_ldck) { + backend_ctx->prealloc_moe_qa_trans.allocate(backend_ctx->context, tok_slots * ne00 * sizeof(cl_char)); + backend_ctx->prealloc_moe_da_trans.allocate(backend_ctx->context, n_blocks * sizeof(cl_float)); + // matches max_constant_size of src1_a_cm in the ldck kernel + backend_ctx->prealloc_moe_qda_on_chip.allocate(backend_ctx->context, 2304); + } + + // fused reorder + q8_1 quant straight from the original + // activations (no intermediate f32 reorder buffer). mxfp4 has no + // min term so the GEMM ignores sa, but reorder_quant still writes it. + const cl_uint n_kblocks = (cl_uint)(ne00 / 32); + cl_kernel rq = backend_ctx->mul_mat_id.kernel_moe_reorder_quant_a_q8_1; + CL_CHECK(clSetKernelArg(rq, 0, sizeof(cl_mem), &sub_buf_src1_pre)); + CL_CHECK(clSetKernelArg(rq, 1, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(rq, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(rq, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(rq, 4, sizeof(cl_mem), &backend_ctx->prealloc_moe_sa.buffer)); + CL_CHECK(clSetKernelArg(rq, 5, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(rq, 6, sizeof(cl_uint), &ne00)); + CL_CHECK(clSetKernelArg(rq, 7, sizeof(unsigned short), &map_ratio)); + CL_CHECK(clSetKernelArg(rq, 8, sizeof(cl_uint), &n_tile_size)); + CL_CHECK(clSetKernelArg(rq, 9, sizeof(cl_uint), &n_kblocks)); + size_t rq_local[2] = { 32, 1 }; + size_t rq_global[2] = { (size_t)(((n_kblocks + 31) / 32) * 32), tok_slots }; + backend_ctx->enqueue_ndrange_kernel(rq, 2, rq_global, rq_local, dst); + + // dp4a GEMM + cl_kernel dk = backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a; + if (backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_bin) { + dk = backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_bin; + } else if (use_moe_dp4a_ldck) { + dk = backend_ctx->mul_mat_id.kernel_gemm_moe_mxfp4_q8_1_dp4a_ldck_bin; + + // per-tile transpose of qa/da for the ldck kernel + cl_kernel tk = backend_ctx->mul_mat_id.kernel_transpose_activation_q8; + CL_CHECK(clSetKernelArg(tk, 0, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(tk, 1, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa_trans.buffer)); + CL_CHECK(clSetKernelArg(tk, 2, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + CL_CHECK(clSetKernelArg(tk, 3, sizeof(cl_mem), &backend_ctx->prealloc_moe_da_trans.buffer)); + CL_CHECK(clSetKernelArg(tk, 4, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(tk, 5, sizeof(cl_uint), &ne00)); + size_t tk_local[3] = { 32, 8, 1 }; + size_t tk_global[3] = { 32, (size_t)(ne00 / 4), (size_t)max_post_router_tile }; + backend_ctx->enqueue_ndrange_kernel(tk, 3, tk_global, tk_local, dst); + } + int aidx = 0; + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_mxfp4->q_img)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &extra0_mxfp4->e)); + if (use_moe_dp4a_ldck) { + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa_trans.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da_trans.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qda_on_chip.buffer)); + } else { + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_qa.buffer)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &backend_ctx->prealloc_moe_da.buffer)); + } + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(dk, aidx++, sizeof(int), &backend_ctx->adreno_use_moe_ragged_dp4)); + + size_t dp_global[3] = { 64, (size_t)((ne01 + 63) / 64), (size_t)max_post_router_tile }; + size_t dp_local[3] = { 64, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(dk, 3, dp_global, dp_local, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + return; + } + + // Set kernel args + int arg_idx = 0; + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_mxfp4->q_img)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &extra0_mxfp4->e)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), use_moe_coopmat ? &buf_src1_reordered : &image_src1_reordered)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_src2_emap)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &buf_dst_image)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_mem), &(backend_ctx->prealloc_total_tiles.buffer))); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_use_moe_ragged)); + CL_CHECK(clSetKernelArg(kernel, arg_idx++, sizeof(cl_uint), &backend_ctx->adreno_moe_ragged_skip_gran)); + + // set thread grid + global_size[1] = static_cast((ne01 + 63) / 64); + global_size[2] = static_cast(max_post_router_tile); + local_size[1] = 1; + local_size[2] = 1; + + // Dispatch kernel + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_size, local_size, dst); + + clReleaseMemObject(sub_buf_src1_pre); + clReleaseMemObject(buf_src1_reordered); + if (image_src1_reordered) { + clReleaseMemObject(image_src1_reordered); + } + clReleaseMemObject(buf_src2); + clReleaseMemObject(buf_src2_emap); + clReleaseMemObject(sub_buf_dst); + clReleaseMemObject(buf_dst_image); + } + return; + } // fallback to generic MoE mxfp4 kernel +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat_id.kernel_mul_mv_id_mxfp4_f32_flat; + + cl_mem q; + if (backend_ctx->gpu_family == INTEL) { + sgs = 16; + nsg = 2; + ndst = 2; + + q = extra0_mxfp4->q; + } else if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + nsg = 1; + ndst = 4; + + q = extra0_mxfp4->q_img; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra0_mxfp4->e)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); +#else // GGML_OPENCL_SOA_Q + kernel = backend_ctx->mul_mat_id.kernel_mul_mv_id_mxfp4_f32; + + if (backend_ctx->gpu_family == INTEL) { + sgs = 16; + nsg = 2; + ndst = 2; + } else if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + nsg = 2; + ndst = 2; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &r2)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &r3)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float)*sgs,nullptr)); +#endif // GGML_OPENCL_SOA_Q + break; + } + default: + GGML_ASSERT(false && "not implemented");; + } + + int _ne1 = 1; + int ne123 = dst_rows; + + size_t global_work_size[] = {(size_t)(ne01+ndst*nsg-1)/(ndst*nsg)*sgs, (size_t)(_ne1+nrows-1)/nrows*nsg, (size_t)ne123}; + size_t local_work_size[] = {(size_t)sgs, (size_t)nsg, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/neg.cpp b/ggml/src/ggml-opencl/ops/neg.cpp new file mode 100644 index 000000000000..182ce32078c2 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/neg.cpp @@ -0,0 +1,109 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_neg(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // neg + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "neg.cl.h" + }; +#else + const std::string kernel_src = read_file("neg.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->neg.kernel_neg_f32 = clCreateKernel(prog, "kernel_neg_f32", &err), err)); + CL_CHECK((backend_ctx->neg.kernel_neg_f32_4 = clCreateKernel(prog, "kernel_neg_f32_4", &err), err)); + CL_CHECK((backend_ctx->neg.kernel_neg_f32_nc = clCreateKernel(prog, "kernel_neg_f32_nc", &err), err)); + CL_CHECK((backend_ctx->neg.kernel_neg_f16 = clCreateKernel(prog, "kernel_neg_f16", &err), err)); + CL_CHECK((backend_ctx->neg.kernel_neg_f16_4 = clCreateKernel(prog, "kernel_neg_f16_4", &err), err)); + CL_CHECK((backend_ctx->neg.kernel_neg_f16_nc = clCreateKernel(prog, "kernel_neg_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_neg(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + cl_kernel kernel; + + if (ggml_is_contiguous(src0)) { + // Handle contiguous input + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->neg.kernel_neg_f32_4; + } else { + kernel = backend_ctx->neg.kernel_neg_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->neg.kernel_neg_f32; + } else { + kernel = backend_ctx->neg.kernel_neg_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &n)); + + size_t global_work_size[] = {(size_t)CEIL_DIV(n, 64)*64, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else { + // Handle non-contiguous input + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->neg.kernel_neg_f32_nc; + } else { + kernel = backend_ctx->neg.kernel_neg_f16_nc; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/nop.cpp b/ggml/src/ggml-opencl/ops/nop.cpp new file mode 100644 index 000000000000..9c0adc56ef8f --- /dev/null +++ b/ggml/src/ggml-opencl/ops/nop.cpp @@ -0,0 +1,17 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_nop(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + GGML_UNUSED(backend_ctx); + GGML_UNUSED(err); + GGML_UNUSED(compile_opts); +} + +void ggml_cl_nop(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + UNUSED(backend); + UNUSED(src0); + UNUSED(src1); + UNUSED(dst); +} diff --git a/ggml/src/ggml-opencl/ops/norm.cpp b/ggml/src/ggml-opencl/ops/norm.cpp new file mode 100644 index 000000000000..b7cfd6bd3f0b --- /dev/null +++ b/ggml/src/ggml-opencl/ops/norm.cpp @@ -0,0 +1,160 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_norm(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // norm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "norm.cl.h" + }; +#else + const std::string kernel_src = read_file("norm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->norm.kernel_norm = clCreateKernel(prog, "kernel_norm", &err), err)); + CL_CHECK((backend_ctx->norm.kernel_norm_mul_add = clCreateKernel(prog, "kernel_norm_mul_add", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + float eps; + memcpy(&eps, dst->op_params, sizeof(float)); + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + + int nth = 1; + while (nth < ne00 && nth < 64) { + nth *= 2; + } + + cl_kernel kernel = backend_ctx->norm.kernel_norm; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float), &eps)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float)*nth, NULL)); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +void ggml_opencl_op_norm_fused(ggml_backend_t backend, ggml_tensor * norm_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor) { + GGML_ASSERT(norm_tensor && mul_tensor && add_tensor); + + const ggml_tensor * src0 = norm_tensor->src[0]; + const ggml_tensor * src1 = mul_tensor->src[0] == norm_tensor ? mul_tensor->src[1] : mul_tensor->src[0]; + const ggml_tensor * src2 = add_tensor->src[0] == mul_tensor ? add_tensor->src[1] : add_tensor->src[0]; + const ggml_tensor * dst = add_tensor; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offset2 = extra2->offset + src2->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + float eps; + memcpy(&eps, norm_tensor->op_params, sizeof(float)); + + const int ne00 = src0->ne[0], ne01 = src0->ne[1], ne02 = src0->ne[2], ne03 = src0->ne[3]; + const cl_ulong nb01 = src0->nb[1], nb02 = src0->nb[2], nb03 = src0->nb[3]; + const int ne10 = src1->ne[0], ne11 = src1->ne[1], ne12 = src1->ne[2], ne13 = src1->ne[3]; + const cl_ulong nb11 = src1->nb[1], nb12 = src1->nb[2], nb13 = src1->nb[3]; + const int ne20 = src2->ne[0], ne21 = src2->ne[1], ne22 = src2->ne[2], ne23 = src2->ne[3]; + const cl_ulong nb21 = src2->nb[1], nb22 = src2->nb[2], nb23 = src2->nb[3]; + const cl_ulong nbd1 = dst->nb[1], nbd2 = dst->nb[2], nbd3 = dst->nb[3]; + + size_t sgs; + if (backend_ctx->gpu_family == ADRENO) sgs = 64; + else if (backend_ctx->gpu_family == INTEL) sgs = 32; + else GGML_ASSERT(false && "Unsupported GPU"); + + cl_kernel kernel = backend_ctx->norm.kernel_norm_mul_add; + + int nth = sgs; + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + while (nth < ne00/4 && nth < max_workgroup_size) nth *= 2; + nth = MIN(nth, max_workgroup_size); + nth = MIN(nth, ne00/4); + + size_t gws[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t lws[] = {(size_t)nth, 1, 1}; + size_t num_subgroups = (nth + sgs - 1) / sgs; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne22)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne23)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb22)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb23)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nbd1)); + CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_ulong), &nbd2)); + CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_ulong), &nbd3)); + CL_CHECK(clSetKernelArg(kernel, 32, sizeof(float), &eps)); + CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_float2) * num_subgroups, NULL)); + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, gws, lws, dst); +} diff --git a/ggml/src/ggml-opencl/ops/pad.cpp b/ggml/src/ggml-opencl/ops/pad.cpp new file mode 100644 index 000000000000..47b83e75d2b1 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/pad.cpp @@ -0,0 +1,122 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_pad(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // pad + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "pad.cl.h" + }; +#else + const std::string kernel_src = read_file("pad.cl"); +#endif + if (!kernel_src.empty()) { + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->pad.kernel_pad = clCreateKernel(prog, "kernel_pad", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } else { + GGML_LOG_WARN("ggml_opencl: pad kernel source not found or empty. Pad operations will not be available.\n"); + backend_ctx->pad.kernel_pad = nullptr; + } + } +} + +void ggml_cl_pad(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(src0->type == GGML_TYPE_F32); + GGML_ASSERT(dst->type == GGML_TYPE_F32); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + if (backend_ctx->pad.kernel_pad == nullptr) { + GGML_LOG_WARN("%s: pad kernel not available, skipping OpenCL execution.\n", __func__); + return; + } + + ggml_tensor_extra_cl * extra_src0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong off_src0 = extra_src0->offset + src0->view_offs; + cl_ulong off_dst = extra_dst->offset + dst->view_offs; + + const int s_ne0 = src0->ne[0]; + const int s_ne1 = src0->ne[1]; + const int s_ne2 = src0->ne[2]; + const int s_ne3 = src0->ne[3]; + + const int s_nb0 = src0->nb[0]; + const int s_nb1 = src0->nb[1]; + const int s_nb2 = src0->nb[2]; + const int s_nb3 = src0->nb[3]; + + const int d_ne0 = dst->ne[0]; + const int d_ne1 = dst->ne[1]; + const int d_ne2 = dst->ne[2]; + const int d_ne3 = dst->ne[3]; + + const int d_nb0 = dst->nb[0]; + const int d_nb1 = dst->nb[1]; + const int d_nb2 = dst->nb[2]; + const int d_nb3 = dst->nb[3]; + + const int lp0 = ((const int*)(dst->op_params))[0]; + const int rp0 = ((const int*)(dst->op_params))[1]; + const int lp1 = ((const int*)(dst->op_params))[2]; + const int rp1 = ((const int*)(dst->op_params))[3]; + const int lp2 = ((const int*)(dst->op_params))[4]; + const int rp2 = ((const int*)(dst->op_params))[5]; + const int lp3 = ((const int*)(dst->op_params))[6]; + const int rp3 = ((const int*)(dst->op_params))[7]; + + cl_kernel kernel = backend_ctx->pad.kernel_pad; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &off_dst)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &s_ne0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &s_ne1)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &s_ne2)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &s_ne3)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &s_nb0)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &s_nb1)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &s_nb2)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &s_nb3)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &d_ne0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &d_ne1)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &d_ne2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &d_ne3)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &d_nb0)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &d_nb1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &d_nb2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &d_nb3)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &lp0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(int), &rp0)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &lp1)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &rp1)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &lp2)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &rp2)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &lp3)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(int), &rp3)); + + size_t lws0 = 64; + size_t gws0 = (( (size_t)d_ne0 + lws0 - 1 ) / lws0) * lws0; + + size_t global_work_size[] = { gws0, (size_t)d_ne1, (size_t)d_ne2*d_ne3 }; + size_t local_work_size[] = { lws0, 1, 1 }; + + size_t * local_work_size_ptr = local_work_size; + if (d_ne0 % lws0 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/permute.cpp b/ggml/src/ggml-opencl/ops/permute.cpp new file mode 100644 index 000000000000..4e2a86d1ef7e --- /dev/null +++ b/ggml/src/ggml-opencl/ops/permute.cpp @@ -0,0 +1,12 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_permute(ggml_backend_opencl_context * backend_ctx) { + GGML_UNUSED(backend_ctx); +} + +void ggml_cl_permute( + ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + ggml_cl_nop(backend, src0, src1, dst); +} diff --git a/ggml/src/ggml-opencl/ops/relu.cpp b/ggml/src/ggml-opencl/ops/relu.cpp new file mode 100644 index 000000000000..4ca64b5d910e --- /dev/null +++ b/ggml/src/ggml-opencl/ops/relu.cpp @@ -0,0 +1,59 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_relu(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // relu + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "relu.cl.h" + }; +#else + const std::string kernel_src = read_file("relu.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->relu.kernel_relu = clCreateKernel(prog, "kernel_relu", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_relu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel = backend_ctx->relu.kernel_relu; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + const int64_t n = ggml_nelements(dst); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/repeat.cpp b/ggml/src/ggml-opencl/ops/repeat.cpp new file mode 100644 index 000000000000..c7909e1742f8 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/repeat.cpp @@ -0,0 +1,104 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_repeat(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // repeat + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "repeat.cl.h" + }; +#else + const std::string kernel_src = read_file("repeat.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->repeat.kernel_repeat_f32 = clCreateKernel(prog, "kernel_repeat_f32", &err), err)); + CL_CHECK((backend_ctx->repeat.kernel_repeat_f16 = clCreateKernel(prog, "kernel_repeat_f16", &err), err)); + CL_CHECK((backend_ctx->repeat.kernel_repeat_i32 = clCreateKernel(prog, "kernel_repeat_i32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_repeat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1_shape_def, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(dst->type == src0->type); + + UNUSED(src1_shape_def); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + const int ne2 = dst->ne[2]; + const int ne3 = dst->ne[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel; + switch (src0->type) { + case GGML_TYPE_F32: + kernel = backend_ctx->repeat.kernel_repeat_f32; + break; + case GGML_TYPE_F16: + case GGML_TYPE_I16: + case GGML_TYPE_BF16: + kernel = backend_ctx->repeat.kernel_repeat_f16; + break; + case GGML_TYPE_I32: + kernel = backend_ctx->repeat.kernel_repeat_i32; + break; + default: + GGML_ABORT("unsupported type"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne1*nth, (size_t)ne2, (size_t)ne3}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/reshape.cpp b/ggml/src/ggml-opencl/ops/reshape.cpp new file mode 100644 index 000000000000..97b508dc1616 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/reshape.cpp @@ -0,0 +1,12 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_reshape(ggml_backend_opencl_context * backend_ctx) { + GGML_UNUSED(backend_ctx); +} + +void ggml_cl_reshape( + ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + ggml_cl_nop(backend, src0, src1, dst); +} diff --git a/ggml/src/ggml-opencl/ops/rms_norm.cpp b/ggml/src/ggml-opencl/ops/rms_norm.cpp new file mode 100644 index 000000000000..41f17cea2cfe --- /dev/null +++ b/ggml/src/ggml-opencl/ops/rms_norm.cpp @@ -0,0 +1,304 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_rms_norm(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // rms_norm + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "rms_norm.cl.h" + }; +#else + const std::string kernel_src = read_file("rms_norm.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->rms_norm.kernel_rms_norm = clCreateKernel(prog, "kernel_rms_norm", &err), err)); + CL_CHECK((backend_ctx->rms_norm.kernel_rms_norm_mul = clCreateKernel(prog, "kernel_rms_norm_mul", &err), err)); + CL_CHECK((backend_ctx->rms_norm.kernel_rms_norm_mul_add = clCreateKernel(prog, "kernel_rms_norm_mul_add", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +} + +void ggml_opencl_op_rms_norm_mul_add_fused(ggml_backend_t backend, ggml_tensor * rms_norm_tensor, ggml_tensor * mul_tensor, ggml_tensor * add_tensor) { + GGML_ASSERT(rms_norm_tensor && mul_tensor && add_tensor); + + const ggml_tensor * src0 = rms_norm_tensor->src[0]; + const ggml_tensor * src1 = mul_tensor->src[0] == rms_norm_tensor ? mul_tensor->src[1] : mul_tensor->src[0]; + const ggml_tensor * src2 = add_tensor->src[0] == mul_tensor ? add_tensor->src[1] : add_tensor->src[0]; + const ggml_tensor * dst = add_tensor; + + GGML_ASSERT(src0 && src0->extra); + GGML_ASSERT(src1 && src1->extra); + GGML_ASSERT(src2 && src2->extra); + GGML_ASSERT(dst && dst->extra); + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *)src2->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offset2 = extra2->offset + src2->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + float eps; + memcpy(&eps, rms_norm_tensor->op_params, sizeof(float)); + + const int ne00 = src0->ne[0], ne01 = src0->ne[1], ne02 = src0->ne[2], ne03 = src0->ne[3]; + const cl_ulong nb01 = src0->nb[1], nb02 = src0->nb[2], nb03 = src0->nb[3]; + const int ne10 = src1->ne[0], ne11 = src1->ne[1], ne12 = src1->ne[2], ne13 = src1->ne[3]; + const cl_ulong nb11 = src1->nb[1], nb12 = src1->nb[2], nb13 = src1->nb[3]; + const int ne20 = src2->ne[0], ne21 = src2->ne[1], ne22 = src2->ne[2], ne23 = src2->ne[3]; + const cl_ulong nb21 = src2->nb[1], nb22 = src2->nb[2], nb23 = src2->nb[3]; + const cl_ulong nb1 = dst->nb[1], nb2 = dst->nb[2], nb3 = dst->nb[3]; + + GGML_ASSERT(ne00 % 4 == 0); + + size_t sgs; + if (backend_ctx->gpu_family == ADRENO) sgs = 64; + else if (backend_ctx->gpu_family == INTEL) sgs = 32; + else GGML_ASSERT(false && "Unsupported GPU"); + + cl_kernel kernel = backend_ctx->rms_norm.kernel_rms_norm_mul_add; + + int nth = sgs; + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + while (nth < ne00 && nth < max_workgroup_size) nth *= 2; + nth = MIN(nth, max_workgroup_size); + nth = MIN(nth, ne00); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(int), &ne20)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(int), &ne21)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &ne22)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &ne23)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nb21)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nb22)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nb23)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 32, sizeof(float), &eps)); + CL_CHECK(clSetKernelArg(kernel, 33, sizeof(float)*sgs, NULL)); + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +void ggml_cl_rms_norm(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + //ggml_backend_opencl_device_context * dev_ctx = + // (ggml_backend_opencl_device_context *)backend->device->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + float eps; + memcpy(&eps, dst->op_params, sizeof(float)); + + const int ne00 = src0 ? src0->ne[0] : 0; + const int ne01 = src0 ? src0->ne[1] : 0; + const int ne02 = src0 ? src0->ne[2] : 0; + const int ne03 = src0 ? src0->ne[3] : 0; + + const cl_ulong nb01 = src0 ? src0->nb[1] : 0; + const cl_ulong nb02 = src0 ? src0->nb[2] : 0; + const cl_ulong nb03 = src0 ? src0->nb[3] : 0; + + GGML_ASSERT(ne00 % 4 == 0); + + const int nth = 64; + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + cl_kernel kernel = backend_ctx->rms_norm.kernel_rms_norm; + + // Note, this kernel declares local memory in kernel args and the size + // depends on subgroup size. + // Note, this requires OpenCL 2.1 and above + // For now we use fixed subgroup size to simplify support for OpenCL 2.0. + size_t sgs; + //CL_CHECK(clGetKernelSubGroupInfo(kernel, dev_ctx->device, + // CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE, + // sizeof(local_work_size), local_work_size, + // sizeof(size_t), &sgs, NULL)); + if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + } else if (backend_ctx->gpu_family == INTEL) { + sgs = 32; + } else { + GGML_ASSERT(false && "Unsupported GPU"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(float), &eps)); + // This is local memory - the size depends on subgroup size. + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float)*nth/sgs, NULL)); + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} + +void ggml_opencl_op_rms_norm_fused(ggml_backend_t backend, ggml_tensor * rms_norm_tensor, ggml_tensor * mul_tensor) { + GGML_ASSERT(mul_tensor); + GGML_ASSERT(rms_norm_tensor); + + // src0 is the src of rms_norm, src1 is the other src of mul (one being rms_norm) + const ggml_tensor * src0 = rms_norm_tensor->src[0]; + const ggml_tensor * src1; + if (mul_tensor->src[0] == rms_norm_tensor) { + src1 = mul_tensor->src[1]; + } else if (mul_tensor->src[1] == rms_norm_tensor) { + src1 = mul_tensor->src[0]; + } else { + GGML_ASSERT(false && "Invalid args for rms_norm and mul"); + } + const ggml_tensor * dst = mul_tensor; + + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + float eps; + memcpy(&eps, rms_norm_tensor->op_params, sizeof(float)); + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne10 = src1->ne[0]; + const int ne11 = src1->ne[1]; + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; + + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + GGML_ASSERT(ne00 % 4 == 0); + + size_t sgs; + if (backend_ctx->gpu_family == ADRENO) { + sgs = 64; + } else if (backend_ctx->gpu_family == INTEL) { + sgs = 32; + } else { + GGML_ASSERT(false && "Unsupported GPU"); + } + + cl_kernel kernel = backend_ctx->rms_norm.kernel_rms_norm_mul; + + int nth = sgs; + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + while (nth < ne00 && nth < max_workgroup_size) { + nth *= 2; + } + nth = MIN(nth, max_workgroup_size); + nth = MIN(nth, ne00); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(float), &eps)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(float)*sgs, NULL)); + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/rope.cpp b/ggml/src/ggml-opencl/ops/rope.cpp new file mode 100644 index 000000000000..46265127dbd8 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/rope.cpp @@ -0,0 +1,220 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_rope(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // rope + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "rope.cl.h" + }; +#else + const std::string kernel_src = read_file("rope.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->rope.kernel_rope_norm_f32 = clCreateKernel(prog, "kernel_rope_norm_f32", &err), err)); + CL_CHECK((backend_ctx->rope.kernel_rope_norm_f16 = clCreateKernel(prog, "kernel_rope_norm_f16", &err), err)); + CL_CHECK((backend_ctx->rope.kernel_rope_neox_f32 = clCreateKernel(prog, "kernel_rope_neox_f32", &err), err)); + CL_CHECK((backend_ctx->rope.kernel_rope_neox_f16 = clCreateKernel(prog, "kernel_rope_neox_f16", &err), err)); + CL_CHECK((backend_ctx->rope.kernel_rope_multi_f32 = clCreateKernel(prog, "kernel_rope_multi_f32", &err), err)); + CL_CHECK((backend_ctx->rope.kernel_rope_multi_f16 = clCreateKernel(prog, "kernel_rope_multi_f16", &err), err)); + CL_CHECK((backend_ctx->rope.kernel_rope_vision_f32 = clCreateKernel(prog, "kernel_rope_vision_f32", &err), err)); + CL_CHECK((backend_ctx->rope.kernel_rope_vision_f16 = clCreateKernel(prog, "kernel_rope_vision_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_rope(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + ggml_tensor * src2 = dst->src[2]; + ggml_tensor_extra_cl * extra2 = src2 ? (ggml_tensor_extra_cl *)src2->extra : nullptr; + + cl_ulong offset2 = extra2 ? extra2->offset + src2->view_offs : offset0; + + const int ne00 = src0 ? src0->ne[0] : 0; + const int ne01 = src0 ? src0->ne[1] : 0; + const int ne02 = src0 ? src0->ne[2] : 0; + const int ne03 = src0 ? src0->ne[3] : 0; + + const cl_ulong nb00 = src0 ? src0->nb[0] : 0; + const cl_ulong nb01 = src0 ? src0->nb[1] : 0; + const cl_ulong nb02 = src0 ? src0->nb[2] : 0; + const cl_ulong nb03 = src0 ? src0->nb[3] : 0; + + const int ne10 = src1 ? src1->ne[0] : 0; + const int ne11 = src1 ? src1->ne[1] : 0; UNUSED(ne11); + const int ne12 = src1 ? src1->ne[2] : 0; UNUSED(ne12); + const int ne13 = src1 ? src1->ne[3] : 0; UNUSED(ne13); + + const int ne0 = dst ? dst->ne[0] : 0; + const int ne1 = dst ? dst->ne[1] : 0; + const int ne2 = dst ? dst->ne[2] : 0; + const int ne3 = dst ? dst->ne[3] : 0; + + const cl_ulong nb0 = dst ? dst->nb[0] : 0; + const cl_ulong nb1 = dst ? dst->nb[1] : 0; + const cl_ulong nb2 = dst ? dst->nb[2] : 0; + const cl_ulong nb3 = dst ? dst->nb[3] : 0; + + GGML_ASSERT(ne10 % ne02 == 0); + GGML_ASSERT(ne10 >= ne02); + + int nth = MIN(64, ne00); + + const int n_past = ((int *) dst->op_params)[0]; + const int n_dims = ((int *) dst->op_params)[1]; + const int mode = ((int *) dst->op_params)[2]; + const int n_ctx_orig = ((int32_t *) dst->op_params)[4]; + const int n_offs = ((int32_t *) dst->op_params)[15]; + + float freq_base; + float freq_scale; + float ext_factor; + float attn_factor; + float beta_fast; + float beta_slow; + int32_t sections[4]; + + memcpy(&freq_base, (int32_t *) dst->op_params + 5, sizeof(float)); + memcpy(&freq_scale, (int32_t *) dst->op_params + 6, sizeof(float)); + memcpy(&ext_factor, (int32_t *) dst->op_params + 7, sizeof(float)); + memcpy(&attn_factor, (int32_t *) dst->op_params + 8, sizeof(float)); + memcpy(&beta_fast, (int32_t *) dst->op_params + 9, sizeof(float)); + memcpy(&beta_slow, (int32_t *) dst->op_params + 10, sizeof(float)); + memcpy(§ions, (int32_t *) dst->op_params + 11, sizeof(int32_t)*4); + + const bool is_neox = mode & 2; + const bool is_mrope = mode & GGML_ROPE_TYPE_MROPE; + const bool is_vision = mode == GGML_ROPE_TYPE_VISION; + const int is_imrope = mode == GGML_ROPE_TYPE_IMROPE; + + if (is_mrope) { + GGML_ASSERT(sections[0] > 0 || sections[1] > 0 || sections[2] > 0); + } + + if (is_vision) { + GGML_ASSERT(n_dims == ne00/2); + GGML_ASSERT(n_offs == 0); + } + + cl_kernel kernel; + + if (is_neox) { + switch (src0->type) { + case GGML_TYPE_F32: + kernel = backend_ctx->rope.kernel_rope_neox_f32; + break; + case GGML_TYPE_F16: + kernel = backend_ctx->rope.kernel_rope_neox_f16; + break; + default: + GGML_ASSERT(false); + }; + } else if (is_mrope && !is_vision) { + switch (src0->type) { + case GGML_TYPE_F32: + kernel = backend_ctx->rope.kernel_rope_multi_f32; + break; + case GGML_TYPE_F16: + kernel = backend_ctx->rope.kernel_rope_multi_f16; + break; + default: + GGML_ASSERT(false); + }; + } else if (is_vision) { + switch (src0->type) { + case GGML_TYPE_F32: + kernel = backend_ctx->rope.kernel_rope_vision_f32; + break; + case GGML_TYPE_F16: + kernel = backend_ctx->rope.kernel_rope_vision_f16; + break; + default: + GGML_ASSERT(false); + } + } else { + switch (src0->type) { + case GGML_TYPE_F32: + kernel = backend_ctx->rope.kernel_rope_norm_f32; + break; + case GGML_TYPE_F16: + kernel = backend_ctx->rope.kernel_rope_norm_f16; + break; + default: + GGML_ASSERT(false); + }; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), extra2 ? &extra2->data_device : &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne3)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &n_past)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(int), &n_dims)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(int), &n_ctx_orig)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(float), &freq_base)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(float), &freq_scale)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(float), &ext_factor)); + CL_CHECK(clSetKernelArg(kernel, 30, sizeof(float), &attn_factor)); + CL_CHECK(clSetKernelArg(kernel, 31, sizeof(float), &beta_fast)); + CL_CHECK(clSetKernelArg(kernel, 32, sizeof(float), &beta_slow)); + // both mrope and vision kernels have sections + if (is_mrope || is_vision) { + CL_CHECK(clSetKernelArg(kernel, 33, sizeof(int32_t)*4, §ions)); + } + // only mrope has is_imrope + if (is_mrope && !is_vision) { + CL_CHECK(clSetKernelArg(kernel, 34, sizeof(int), &is_imrope)); + } + if (!is_mrope && !is_vision) { + CL_CHECK(clSetKernelArg(kernel, 33, sizeof(int), &n_offs)); + } else if (is_mrope && !is_vision) { + CL_CHECK(clSetKernelArg(kernel, 35, sizeof(int), &n_offs)); + } + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/scale.cpp b/ggml/src/ggml-opencl/ops/scale.cpp new file mode 100644 index 000000000000..bcf3521a567d --- /dev/null +++ b/ggml/src/ggml-opencl/ops/scale.cpp @@ -0,0 +1,100 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_scale(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // scale + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "scale.cl.h" + }; +#else + const std::string kernel_src = read_file("scale.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->scale.kernel_scale_f32 = clCreateKernel(prog, "kernel_scale_f32", &err), err)); + CL_CHECK((backend_ctx->scale.kernel_scale_f32_4 = clCreateKernel(prog, "kernel_scale_f32_4", &err), err)); + CL_CHECK((backend_ctx->scale.kernel_scale_f32_nc = clCreateKernel(prog, "kernel_scale_f32_nc", &err), err)); + CL_CHECK((backend_ctx->scale.kernel_scale_f16 = clCreateKernel(prog, "kernel_scale_f16", &err), err)); + CL_CHECK((backend_ctx->scale.kernel_scale_f16_4 = clCreateKernel(prog, "kernel_scale_f16_4", &err), err)); + CL_CHECK((backend_ctx->scale.kernel_scale_f16_nc = clCreateKernel(prog, "kernel_scale_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0 && src0->extra); + GGML_ASSERT(dst && dst->extra); + GGML_UNUSED(src1); + + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; + const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + const float scale = ggml_get_op_params_f32(dst, 0); + const float bias = ggml_get_op_params_f32(dst, 1); + const bool is_f16 = src0->type == GGML_TYPE_F16; + + cl_kernel kernel; + + if (ggml_is_contiguous(src0) && ggml_is_contiguous(dst)) { + size_t n = ggml_nelements(dst); + const size_t alignment = 4 * ggml_element_size(src0); + if (n % 4 == 0 && offset0 % alignment == 0 && offsetd % alignment == 0) { + kernel = is_f16 ? backend_ctx->scale.kernel_scale_f16_4 : backend_ctx->scale.kernel_scale_f32_4; + n /= 4; + } else { + kernel = is_f16 ? backend_ctx->scale.kernel_scale_f16 : backend_ctx->scale.kernel_scale_f32; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); + + size_t global_work_size[] = {n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + size_t * local_work_size_ptr = local_work_size; + if (n % local_work_size[0] != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); + } else { + kernel = is_f16 ? backend_ctx->scale.kernel_scale_f16_nc : backend_ctx->scale.kernel_scale_f32_nc; + const cl_ulong ne00 = src0->ne[0]; + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(float), &bias)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb3)); + + const size_t nth = 64; + size_t global_work_size[] = {(size_t)src0->ne[1] * nth, (size_t)src0->ne[2], (size_t)src0->ne[3]}; + size_t local_work_size[] = {nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/set.cpp b/ggml/src/ggml-opencl/ops/set.cpp new file mode 100644 index 000000000000..32a00b0eab11 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/set.cpp @@ -0,0 +1,93 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_set(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + GGML_UNUSED(backend_ctx); + GGML_UNUSED(err); + GGML_UNUSED(compile_opts); +} + +void ggml_cl_set(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT((src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_I32) && + src1->type == src0->type && dst->type == src0->type); + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + GGML_TENSOR_LOCALS(int, ne, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const cl_ulong pnb1 = ((const int32_t *)dst->op_params)[0]; + const cl_ulong pnb2 = ((const int32_t *)dst->op_params)[1]; + const cl_ulong pnb3 = ((const int32_t *)dst->op_params)[2]; + const cl_ulong offs = ((const int32_t *)dst->op_params)[3]; + const bool inplace = (bool)((const int32_t *)dst->op_params)[4]; + + cl_kernel kernel = nullptr; + + // for inplace case, dst is a view of src0 and is updated on top of it + // so for non-inplace case, copy src0 to dst first + if (!inplace) { + ggml_cl_cpy(backend, src0, dst, nullptr); + } + + // then copy src1 to dst with specified offset + if (src1->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->cpy.kernel_cpy_f32_f32; + } else if (src1->type == GGML_TYPE_I32 && dst->type == GGML_TYPE_I32) { + kernel = backend_ctx->cpy.kernel_cpy_i32_i32; + } else { + GGML_ASSERT(false && "not implemented"); + } + + offsetd += offs; + cl_ulong nb = ggml_element_size(dst); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &pnb1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &pnb2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &pnb3)); + + int max_local_size = backend_ctx->get_kernel_workgroup_size(kernel); + + const int nth = MIN(max_local_size, ne00); + + size_t global_work_size[] = {(size_t)ne11*nth, (size_t)ne12, (size_t)ne13}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/set_rows.cpp b/ggml/src/ggml-opencl/ops/set_rows.cpp new file mode 100644 index 000000000000..b54398129c3b --- /dev/null +++ b/ggml/src/ggml-opencl/ops/set_rows.cpp @@ -0,0 +1,201 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_set_rows(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // set_rows + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "set_rows.cl.h" + }; +#else + const std::string kernel_src = read_file("set_rows.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_f32_i64 = clCreateKernel(prog, "kernel_set_rows_f32_i64", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_f32_i32 = clCreateKernel(prog, "kernel_set_rows_f32_i32", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_f16_i64 = clCreateKernel(prog, "kernel_set_rows_f16_i64", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_f16_i32 = clCreateKernel(prog, "kernel_set_rows_f16_i32", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q8_0_i64 = clCreateKernel(prog, "kernel_set_rows_q8_0_i64", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q8_0_i32 = clCreateKernel(prog, "kernel_set_rows_q8_0_i32", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q8_0_soa_i64 = clCreateKernel(prog, "kernel_set_rows_q8_0_soa_i64", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q8_0_soa_i32 = clCreateKernel(prog, "kernel_set_rows_q8_0_soa_i32", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q4_0_i64 = clCreateKernel(prog, "kernel_set_rows_q4_0_i64", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q4_0_i32 = clCreateKernel(prog, "kernel_set_rows_q4_0_i32", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q4_0_soa_i64 = clCreateKernel(prog, "kernel_set_rows_q4_0_soa_i64", &err), err)); + CL_CHECK((backend_ctx->set_rows.kernel_set_rows_q4_0_soa_i32 = clCreateKernel(prog, "kernel_set_rows_q4_0_soa_i32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} +void ggml_cl_set_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(src1->type == GGML_TYPE_I64 || src1->type == GGML_TYPE_I32); + + // ne0 = ne00 + // ne2 = ne02 + // ne3 = ne03 + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + + GGML_TENSOR_LOCALS(int, ne1, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb1, src1, nb); + + GGML_TENSOR_LOCALS(int, ne, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + const int nblk0 = ne0/ggml_blck_size(dst->type); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + + const bool q8_0_soa = dst->type == GGML_TYPE_Q8_0 && ggml_cl_is_q8_0_soa(dst); + const bool q4_0_soa = dst->type == GGML_TYPE_Q4_0 && ggml_cl_is_q4_0_soa(dst); + const bool is_soa = q8_0_soa || q4_0_soa; + + cl_kernel kernel; + + if (q8_0_soa) { + kernel = (src1->type == GGML_TYPE_I64) + ? backend_ctx->set_rows.kernel_set_rows_q8_0_soa_i64 + : backend_ctx->set_rows.kernel_set_rows_q8_0_soa_i32; + } else if (q4_0_soa) { + kernel = (src1->type == GGML_TYPE_I64) + ? backend_ctx->set_rows.kernel_set_rows_q4_0_soa_i64 + : backend_ctx->set_rows.kernel_set_rows_q4_0_soa_i32; + } else { + switch (dst->type) { + case GGML_TYPE_F32: + kernel = (src1->type == GGML_TYPE_I64) + ? backend_ctx->set_rows.kernel_set_rows_f32_i64 + : backend_ctx->set_rows.kernel_set_rows_f32_i32; + break; + case GGML_TYPE_F16: + kernel = (src1->type == GGML_TYPE_I64) + ? backend_ctx->set_rows.kernel_set_rows_f16_i64 + : backend_ctx->set_rows.kernel_set_rows_f16_i32; + break; + case GGML_TYPE_Q8_0: + kernel = (src1->type == GGML_TYPE_I64) + ? backend_ctx->set_rows.kernel_set_rows_q8_0_i64 + : backend_ctx->set_rows.kernel_set_rows_q8_0_i32; + break; + case GGML_TYPE_Q4_0: + kernel = (src1->type == GGML_TYPE_I64) + ? backend_ctx->set_rows.kernel_set_rows_q4_0_i64 + : backend_ctx->set_rows.kernel_set_rows_q4_0_i32; + break; + default: + GGML_ABORT("not implemented"); + } + } + + fastdiv_vals ne11_ = init_fastdiv_values(ne11); + fastdiv_vals ne12_ = init_fastdiv_values(ne12); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + + if (is_soa) { + // The q/d subbuffers in q8_0/q4_0 extras are interchangeable here. + // For views (e.g. ggml_set_rows' `out`), follow view_src for the SoA extra. + const ggml_tensor * soa_src = dst->view_src != nullptr ? dst->view_src : dst; + cl_mem q_mem = nullptr; + cl_mem d_mem = nullptr; + if (q8_0_soa) { + ggml_tensor_extra_cl_q8_0 * e = (ggml_tensor_extra_cl_q8_0 *)soa_src->extra; + q_mem = e->q; + d_mem = e->d; + } else { + ggml_tensor_extra_cl_q4_0 * e = (ggml_tensor_extra_cl_q4_0 *)soa_src->extra; + q_mem = e->q; + d_mem = e->d; + } + cl_ulong offset_q = 0; + cl_ulong offset_d = 0; + const int ne1_dst = dst->ne[1]; + const int ne2_dst = dst->ne[2]; + const int ne3_dst = dst->ne[3]; + + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &q_mem)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset_q)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &d_mem)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset_d)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(fastdiv_vals), &ne11_)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(fastdiv_vals), &ne12_)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(int), &nblk0)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne1_dst)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(int), &ne2_dst)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(int), &ne3_dst)); + } else { + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(fastdiv_vals), &ne11_)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(fastdiv_vals), &ne12_)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(int), &nblk0)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb3)); + } + + int nth0 = 64; + if (backend_ctx->gpu_family == INTEL) { + nth0 = 32; + } else if (backend_ctx->gpu_family == ADRENO) { + nth0 = 64; + } + + int max_workgroup_size = backend_ctx->get_kernel_workgroup_size(kernel); + while (nth0 < nblk0 && nth0 < max_workgroup_size) { + nth0 *= 2; + } + + int rows_per_workgroup = 1; + if (nth0 > nblk0) { + rows_per_workgroup = nth0 / nblk0; + nth0 = nblk0; + } + + size_t global_work_size[] = { + (size_t)(ne01 + rows_per_workgroup - 1)/rows_per_workgroup*nth0, + (size_t)ne02*rows_per_workgroup, + (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth0, (size_t)rows_per_workgroup, 1}; + + // ne01 == 0 makes global_work_size[0] zero here; enqueue_ndrange_kernel drops the empty range. + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/sigmoid.cpp b/ggml/src/ggml-opencl/ops/sigmoid.cpp new file mode 100644 index 000000000000..0f03b8b52845 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/sigmoid.cpp @@ -0,0 +1,108 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_sigmoid(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // sigmoid + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "sigmoid.cl.h" + }; +#else + const std::string kernel_src = read_file("sigmoid.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->sigmoid.kernel_sigmoid_f32 = clCreateKernel(prog, "kernel_sigmoid_f32", &err), err)); + CL_CHECK((backend_ctx->sigmoid.kernel_sigmoid_f16 = clCreateKernel(prog, "kernel_sigmoid_f16", &err), err)); + CL_CHECK((backend_ctx->sigmoid.kernel_sigmoid_f32_nc = clCreateKernel(prog, "kernel_sigmoid_f32_nc", &err), err)); + CL_CHECK((backend_ctx->sigmoid.kernel_sigmoid_f16_nc = clCreateKernel(prog, "kernel_sigmoid_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_sigmoid(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + cl_kernel kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->sigmoid.kernel_sigmoid_f32_nc : backend_ctx->sigmoid.kernel_sigmoid_f16_nc; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + if (src0->type != GGML_TYPE_F32) { + const int is_bf16 = dst->type == GGML_TYPE_BF16; + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &is_bf16)); + } + + size_t global_work_size[] = {(size_t)ne01 * 64, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return; + } + + cl_kernel kernel; + if (src0->type == GGML_TYPE_F32 && dst->type == GGML_TYPE_F32) { + kernel = backend_ctx->sigmoid.kernel_sigmoid_f32; + } else if (src0->type == GGML_TYPE_F16 && dst->type == GGML_TYPE_F16) { + kernel = backend_ctx->sigmoid.kernel_sigmoid_f16; + } else if (src0->type == GGML_TYPE_BF16 && dst->type == GGML_TYPE_BF16) { + // bf16 converted to f16 + kernel = backend_ctx->sigmoid.kernel_sigmoid_f16; + } else { + GGML_ASSERT(false && "Unsupported data types for sigmoid (input and output must be both f32 or f16)"); + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + if (src0->type != GGML_TYPE_F32) { + const int is_bf16 = dst->type == GGML_TYPE_BF16; + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &is_bf16)); + } + + const int64_t n = ggml_nelements(dst); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/silu.cpp b/ggml/src/ggml-opencl/ops/silu.cpp new file mode 100644 index 000000000000..2297c790cb55 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/silu.cpp @@ -0,0 +1,98 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_silu(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // silu + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "silu.cl.h" + }; +#else + const std::string kernel_src = read_file("silu.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->silu.kernel_silu = clCreateKernel(prog, "kernel_silu", &err), err)); + CL_CHECK((backend_ctx->silu.kernel_silu_4 = clCreateKernel(prog, "kernel_silu_4", &err), err)); + CL_CHECK((backend_ctx->silu.kernel_silu_nc = clCreateKernel(prog, "kernel_silu_nc", &err), err)); + CL_CHECK((backend_ctx->silu.kernel_silu_f16 = clCreateKernel(prog, "kernel_silu_f16", &err), err)); + CL_CHECK((backend_ctx->silu.kernel_silu_f16_4 = clCreateKernel(prog, "kernel_silu_f16_4", &err), err)); + CL_CHECK((backend_ctx->silu.kernel_silu_f16_nc = clCreateKernel(prog, "kernel_silu_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_silu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + if (!ggml_is_contiguous(src0) || !ggml_is_contiguous(dst)) { + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + cl_kernel kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->silu.kernel_silu_nc : backend_ctx->silu.kernel_silu_f16_nc; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + size_t global_work_size[] = {(size_t)ne01 * 64, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {64, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + return; + } + + cl_kernel kernel; + + int n = ggml_nelements(dst); + + if (n % 4 == 0) { + kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->silu.kernel_silu_4 : backend_ctx->silu.kernel_silu_f16_4; + n /= 4; + } else { + kernel = src0->type == GGML_TYPE_F32 ? backend_ctx->silu.kernel_silu : backend_ctx->silu.kernel_silu_f16; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; // Let driver choose the work-group sizes. + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/soft_max.cpp b/ggml/src/ggml-opencl/ops/soft_max.cpp new file mode 100644 index 000000000000..2966eb87d8ff --- /dev/null +++ b/ggml/src/ggml-opencl/ops/soft_max.cpp @@ -0,0 +1,202 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_soft_max(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // softmax_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "softmax_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("softmax_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->soft_max.kernel_soft_max = clCreateKernel(prog, "kernel_soft_max", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // softmax_f16 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "softmax_f16.cl.h" + }; +#else + const std::string kernel_src = read_file("softmax_f16.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->soft_max.kernel_soft_max_f16 = clCreateKernel(prog, "kernel_soft_max_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // softmax_4_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "softmax_4_f32.cl.h" + }; +#else + const std::string kernel_src = read_file("softmax_4_f32.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->soft_max.kernel_soft_max_4 = clCreateKernel(prog, "kernel_soft_max_4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + + // softmax_4_f16 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "softmax_4_f16.cl.h" + }; +#else + const std::string kernel_src = read_file("softmax_4_f16.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->soft_max.kernel_soft_max_4_f16 = clCreateKernel(prog, "kernel_soft_max_4_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_soft_max(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + // Softmax can now fuse KQ mask and KQ scale, which used to be two additional + // ops before softmax. It now also fuses alibi if `max_bias > 0`. For llama, + // alibi is not used; however, for some other models, it is used. + // KQ_mask + if (src1) { + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + } + + const ggml_tensor * src2 = dst->src[2]; + if (src2) { + GGML_ASSERT(src2->extra); + } + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + ggml_tensor_extra_cl * extra1 = src1 ? (ggml_tensor_extra_cl *)src1->extra : nullptr; + ggml_tensor_extra_cl * extra2 = src2 ? (ggml_tensor_extra_cl *)src2->extra : nullptr; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_ulong offset1 = extra1 ? extra1->offset + src1->view_offs : offset0; + cl_ulong offset2 = extra2 ? extra2->offset + src2->view_offs : offset0; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_long nb01 = src0->nb[1]; + const cl_long nb02 = src0->nb[2]; + const cl_long nb03 = src0->nb[3]; + + const int ne12 = src1 ? src1->ne[2] : 0; + const int ne13 = src1 ? src1->ne[3] : 0; + + const cl_long nb11 = src1 ? src1->nb[1] : 0; + const cl_long nb12 = src1 ? src1->nb[2] : 0; + const cl_long nb13 = src1 ? src1->nb[3] : 0; + + const cl_long nb1 = dst->nb[1]; + const cl_long nb2 = dst->nb[2]; + const cl_long nb3 = dst->nb[3]; + + float scale, max_bias; + memcpy(&scale, dst->op_params + 0, sizeof(float)); + memcpy(&max_bias, dst->op_params + 1, sizeof(float)); + + const int n_head = src0->ne[2]; + const int n_head_log2 = 1u << (uint32_t) floorf(log2f((float) n_head)); + + const float m0 = powf(2.0f, -(max_bias ) / n_head_log2); + const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_head_log2); + + const bool use_f16 = (src1 && src1->type == GGML_TYPE_F16); + + // Local size must be wave size. Each workgroup is a wave, working on a row, + // where a row corresponds to leading dimension. + int nth = MIN(32, ne00); + + if (backend_ctx->gpu_family == INTEL) { + // This is the same as the initial value. + nth = MIN(32, ne00); + } + else if (backend_ctx->gpu_family == ADRENO) { + nth = 64; + } else { + GGML_ASSERT(false && "TODO: Unknown GPU"); + } + + cl_kernel kernel; + + if (ne00%4 == 0) { + if (use_f16) { + kernel = backend_ctx->soft_max.kernel_soft_max_4_f16; + } else { + kernel = backend_ctx->soft_max.kernel_soft_max_4; + } + } else { + if (use_f16) { + kernel = backend_ctx->soft_max.kernel_soft_max_f16; + } else { + kernel = backend_ctx->soft_max.kernel_soft_max; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), extra1 ? &extra1->data_device : &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), extra2 ? &extra2->data_device : &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(float), &scale)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(float), &max_bias)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(float), &m0)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(float), &m1)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(int), &n_head_log2)); + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/softplus.cpp b/ggml/src/ggml-opencl/ops/softplus.cpp new file mode 100644 index 000000000000..a43656713d17 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/softplus.cpp @@ -0,0 +1,123 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_softplus(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // softplus + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "softplus.cl.h" + }; +#else + const std::string kernel_src = read_file("softplus.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->softplus.kernel_softplus_f32 = clCreateKernel(prog, "kernel_softplus_f32", &err), err)); + CL_CHECK((backend_ctx->softplus.kernel_softplus_f32_4 = clCreateKernel(prog, "kernel_softplus_f32_4", &err), err)); + CL_CHECK((backend_ctx->softplus.kernel_softplus_f32_nc = clCreateKernel(prog, "kernel_softplus_f32_nc", &err), err)); + CL_CHECK((backend_ctx->softplus.kernel_softplus_f16 = clCreateKernel(prog, "kernel_softplus_f16", &err), err)); + CL_CHECK((backend_ctx->softplus.kernel_softplus_f16_4 = clCreateKernel(prog, "kernel_softplus_f16_4", &err), err)); + CL_CHECK((backend_ctx->softplus.kernel_softplus_f16_nc = clCreateKernel(prog, "kernel_softplus_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_softplus(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel; + + if (ggml_is_contiguous(src0)) { + // Handle contiguous input + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->softplus.kernel_softplus_f32_4; + } else { + kernel = backend_ctx->softplus.kernel_softplus_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->softplus.kernel_softplus_f32; + } else { + kernel = backend_ctx->softplus.kernel_softplus_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); + } else { + // Handle non-contiguous input + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->softplus.kernel_softplus_f32_nc; + } else { + kernel = backend_ctx->softplus.kernel_softplus_f16_nc; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/solve_tri.cpp b/ggml/src/ggml-opencl/ops/solve_tri.cpp new file mode 100644 index 000000000000..1303f5a3bf57 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/solve_tri.cpp @@ -0,0 +1,89 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_solve_tri(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // solve_tri_f32 + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "solve_tri.cl.h" + }; +#else + const std::string kernel_src = read_file("solve_tri.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->solve_tri.kernel_solve_tri_f32 = clCreateKernel(prog, "kernel_solve_tri_f32", &err), err)); + GGML_LOG_CONT("."); + CL_CHECK(clReleaseProgram(prog)); + } +} + +void ggml_cl_solve_tri(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel = backend_ctx->solve_tri.kernel_solve_tri_f32; + GGML_ASSERT(kernel != nullptr); + + const int n = src0->ne[0]; + const int k = src1->ne[0]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb10 = src1->nb[0]; + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong),&nb02)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong),&nb03)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong),&nb10)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong),&nb11)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong),&nb12)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong),&nb13)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong),&nb0)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong),&nb1)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong),&nb2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong),&nb3)); + + size_t global_work_size[3]= { (size_t)k, (size_t)dst->ne[2], (size_t)dst->ne[3]}; + size_t local_work_size[] = {16, 4, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/sqr.cpp b/ggml/src/ggml-opencl/ops/sqr.cpp new file mode 100644 index 000000000000..a5a572478ca4 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/sqr.cpp @@ -0,0 +1,77 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_sqr(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // sqr + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "sqr.cl.h" + }; +#else + const std::string kernel_src = read_file("sqr.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->sqr.kernel_sqr_cont_f32 = clCreateKernel(prog, "kernel_sqr_cont_f32", &err), err)); + CL_CHECK((backend_ctx->sqr.kernel_sqr_cont_f32_4 = clCreateKernel(prog, "kernel_sqr_cont_f32_4", &err), err)); + CL_CHECK((backend_ctx->sqr.kernel_sqr_cont_f16 = clCreateKernel(prog, "kernel_sqr_cont_f16", &err), err)); + CL_CHECK((backend_ctx->sqr.kernel_sqr_cont_f16_4 = clCreateKernel(prog, "kernel_sqr_cont_f16_4", &err), err)); + + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_sqr(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel; + + // Currently assumes src0 is contiguous + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->sqr.kernel_sqr_cont_f32_4; + } else { + kernel = backend_ctx->sqr.kernel_sqr_cont_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->sqr.kernel_sqr_cont_f32; + } else { + kernel = backend_ctx->sqr.kernel_sqr_cont_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/sqrt.cpp b/ggml/src/ggml-opencl/ops/sqrt.cpp new file mode 100644 index 000000000000..1ba74b453709 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/sqrt.cpp @@ -0,0 +1,77 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_sqrt(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // sqrt + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "sqrt.cl.h" + }; +#else + const std::string kernel_src = read_file("sqrt.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->sqrt.kernel_sqrt_cont_f32 = clCreateKernel(prog, "kernel_sqrt_cont_f32", &err), err)); + CL_CHECK((backend_ctx->sqrt.kernel_sqrt_cont_f32_4 = clCreateKernel(prog, "kernel_sqrt_cont_f32_4", &err), err)); + CL_CHECK((backend_ctx->sqrt.kernel_sqrt_cont_f16 = clCreateKernel(prog, "kernel_sqrt_cont_f16", &err), err)); + CL_CHECK((backend_ctx->sqrt.kernel_sqrt_cont_f16_4 = clCreateKernel(prog, "kernel_sqrt_cont_f16_4", &err), err)); + + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_sqrt(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + cl_kernel kernel; + + // Currently assumes src0 is contiguous + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->sqrt.kernel_sqrt_cont_f32_4; + } else { + kernel = backend_ctx->sqrt.kernel_sqrt_cont_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->sqrt.kernel_sqrt_cont_f32; + } else { + kernel = backend_ctx->sqrt.kernel_sqrt_cont_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/ssm_conv.cpp b/ggml/src/ggml-opencl/ops/ssm_conv.cpp new file mode 100644 index 000000000000..5a0c9c35a6ac --- /dev/null +++ b/ggml/src/ggml-opencl/ops/ssm_conv.cpp @@ -0,0 +1,88 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_ssm_conv(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // ssm_conv + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "ssm_conv.cl.h" + }; +#else + const std::string kernel_src = read_file("ssm_conv.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->ssm_conv.kernel_ssm_conv_f32_f32 = clCreateKernel(prog, "kernel_ssm_conv_f32_f32", &err), err)); + CL_CHECK((backend_ctx->ssm_conv.kernel_ssm_conv_f32_f32_4 = clCreateKernel(prog, "kernel_ssm_conv_f32_f32_4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_ssm_conv(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + int ne01 = src0->ne[1]; + cl_ulong nb00 = src0->nb[0]; + cl_ulong nb01 = src0->nb[1]; + cl_ulong nb02 = src0->nb[2]; + + int ne10 = src1->ne[0]; + cl_ulong nb11 = src1->nb[1]; + + int ne1 = dst->ne[1]; + int ne2 = dst->ne[2]; + cl_ulong nb0 = dst->nb[0]; + cl_ulong nb1 = dst->nb[1]; + cl_ulong nb2 = dst->nb[2]; + + cl_kernel kernel = backend_ctx->ssm_conv.kernel_ssm_conv_f32_f32; + + if (ne10 % 4 == 0) { + kernel = backend_ctx->ssm_conv.kernel_ssm_conv_f32_f32_4; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb2)); + + size_t global_work_size[] = {(size_t)ne01, (size_t)ne1, (size_t)ne2}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (ne01 % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/ssm_scan.cpp b/ggml/src/ggml-opencl/ops/ssm_scan.cpp new file mode 100644 index 000000000000..f6be755930e9 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/ssm_scan.cpp @@ -0,0 +1,187 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_ssm_scan(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "ssm_scan.cl.h" + }; +#else + const std::string kernel_src = read_file("ssm_scan.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->ssm_scan.kernel_ssm_scan_f32 = clCreateKernel(prog, "kernel_ssm_scan_f32", &err), err)); + CL_CHECK((backend_ctx->ssm_scan.kernel_ssm_scan_f32_mamba2_d128 = clCreateKernel(prog, "kernel_ssm_scan_f32_mamba2_d128", &err), err)); + CL_CHECK((backend_ctx->ssm_scan.kernel_ssm_scan_f32_mamba2_d256 = clCreateKernel(prog, "kernel_ssm_scan_f32_mamba2_d256", &err), err)); + + cl_kernel * kernels[] = { + &backend_ctx->ssm_scan.kernel_ssm_scan_f32_mamba2_d128, + &backend_ctx->ssm_scan.kernel_ssm_scan_f32_mamba2_d256 + }; + + // specialized kernels use subgroups and assume subgroup size is 64, + // if device does not support subgroups or subgroup size is not 64, + // release these kernels + for (int i = 0; i < 2; ++i) { + size_t subgroup_size = 0; +#if CL_TARGET_OPENCL_VERSION >= 210 + const size_t local_work_size[] = { 64, 1 }; + const cl_int subgroup_err = clGetKernelSubGroupInfo(*kernels[i], backend_ctx->device, CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE, + sizeof(local_work_size), local_work_size, sizeof(subgroup_size), &subgroup_size, nullptr); + if (subgroup_err != CL_SUCCESS) { + subgroup_size = 0; + } +#endif + // The specialized kernels reduce over one 64-lane subgroup. + if (subgroup_size != 64) { + CL_CHECK(clReleaseKernel(*kernels[i])); + *kernels[i] = nullptr; + } + } + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); +} + +void ggml_cl_ssm_scan(ggml_backend_t backend, ggml_tensor * dst) { + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(dst->src[0]); + GGML_ASSERT(dst->src[0]->extra); + GGML_ASSERT(dst->src[1]); + GGML_ASSERT(dst->src[1]->extra); + GGML_ASSERT(dst->src[2]); + GGML_ASSERT(dst->src[2]->extra); + GGML_ASSERT(dst->src[3]); + GGML_ASSERT(dst->src[3]->extra); + GGML_ASSERT(dst->src[4]); + GGML_ASSERT(dst->src[4]->extra); + GGML_ASSERT(dst->src[5]); + GGML_ASSERT(dst->src[5]->extra); + GGML_ASSERT(dst->src[6]); + GGML_ASSERT(dst->src[6]->extra); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) dst->src[0]->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *) dst->src[1]->extra; + ggml_tensor_extra_cl * extra2 = (ggml_tensor_extra_cl *) dst->src[2]->extra; + ggml_tensor_extra_cl * extra3 = (ggml_tensor_extra_cl *) dst->src[3]->extra; + ggml_tensor_extra_cl * extra4 = (ggml_tensor_extra_cl *) dst->src[4]->extra; + ggml_tensor_extra_cl * extra5 = (ggml_tensor_extra_cl *) dst->src[5]->extra; + ggml_tensor_extra_cl * extra6 = (ggml_tensor_extra_cl *) dst->src[6]->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + dst->src[0]->view_offs; + const cl_ulong offset1 = extra1->offset + dst->src[1]->view_offs; + const cl_ulong offset2 = extra2->offset + dst->src[2]->view_offs; + const cl_ulong offset3 = extra3->offset + dst->src[3]->view_offs; + const cl_ulong offset4 = extra4->offset + dst->src[4]->view_offs; + const cl_ulong offset5 = extra5->offset + dst->src[5]->view_offs; + const cl_ulong offset6 = extra6->offset + dst->src[6]->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + const ggml_tensor * s = dst->src[0]; + const ggml_tensor * x = dst->src[1]; + const ggml_tensor * dt = dst->src[2]; + const ggml_tensor * A = dst->src[3]; + const ggml_tensor * B = dst->src[4]; + const ggml_tensor * C = dst->src[5]; + + const cl_ulong s_nb1 = s->nb[1]; + const cl_ulong s_nb2 = s->nb[2]; + const cl_ulong s_nb3 = s->nb[3]; + const cl_ulong x_nb1 = x->nb[1]; + const cl_ulong x_nb2 = x->nb[2]; + const cl_ulong x_nb3 = x->nb[3]; + const cl_ulong dt_nb1 = dt->nb[1]; + const cl_ulong dt_nb2 = dt->nb[2]; + const cl_ulong A_nb1 = A->nb[1]; + const cl_ulong B_nb1 = B->nb[1]; + const cl_ulong B_nb2 = B->nb[2]; + const cl_ulong B_nb3 = B->nb[3]; + const cl_ulong C_nb1 = C->nb[1]; + const cl_ulong C_nb2 = C->nb[2]; + const cl_ulong C_nb3 = C->nb[3]; + + const cl_uint A_ne0 = A->ne[0]; + const cl_uint d_state = s->ne[0]; + const cl_int head_dim = x->ne[0]; + const cl_int n_head = x->ne[1]; + const cl_int n_group = B->ne[1]; + const cl_int n_tokens = x->ne[2]; + const cl_uint n_seqs = x->ne[3]; + const cl_uint K = ggml_get_op_params_i32(dst, 0); + const cl_ulong s_off_bytes = (cl_ulong) ggml_nelements(x) * sizeof(float); + + cl_kernel kernel = backend_ctx->ssm_scan.kernel_ssm_scan_f32; + size_t nth = d_state; + if (A_ne0 == 1 && K == 1) { + cl_kernel kernel_mamba2 = nullptr; + if (d_state == 128) { + kernel_mamba2 = backend_ctx->ssm_scan.kernel_ssm_scan_f32_mamba2_d128; + } else if (d_state == 256) { + kernel_mamba2 = backend_ctx->ssm_scan.kernel_ssm_scan_f32_mamba2_d256; + } + if (kernel_mamba2 != nullptr) { + kernel = kernel_mamba2; + nth = 64; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra2->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offset2)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &extra3->data_device)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offset3)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &extra4->data_device)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offset4)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_mem), &extra5->data_device)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &offset5)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_mem), &extra6->data_device)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &offset6)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &s_nb2)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &s_nb3)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &x_nb2)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &x_nb3)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &dt_nb1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &dt_nb2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &A_nb1)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &B_nb2)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &B_nb3)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(cl_ulong), &C_nb2)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &C_nb3)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &s_off_bytes)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_int), &head_dim)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_int), &n_head)); + CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_int), &n_group)); + CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_int), &n_tokens)); + + if (kernel == backend_ctx->ssm_scan.kernel_ssm_scan_f32) { + CL_CHECK(clSetKernelArg(kernel, 32, sizeof(cl_ulong), &s_nb1)); + CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_ulong), &x_nb1)); + CL_CHECK(clSetKernelArg(kernel, 34, sizeof(cl_ulong), &B_nb1)); + CL_CHECK(clSetKernelArg(kernel, 35, sizeof(cl_ulong), &C_nb1)); + CL_CHECK(clSetKernelArg(kernel, 36, sizeof(cl_uint), &A_ne0)); + CL_CHECK(clSetKernelArg(kernel, 37, sizeof(cl_uint), &d_state)); + CL_CHECK(clSetKernelArg(kernel, 38, sizeof(cl_uint), &n_seqs)); + CL_CHECK(clSetKernelArg(kernel, 39, sizeof(cl_uint), &K)); + CL_CHECK(clSetKernelArg(kernel, 40, d_state * sizeof(float), nullptr)); + } + + size_t global_work_size[] = { + (size_t) head_dim * (size_t) n_head * nth, + (size_t) n_seqs, + }; + size_t local_work_size[] = { nth, 1 }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/sub.cpp b/ggml/src/ggml-opencl/ops/sub.cpp new file mode 100644 index 000000000000..f6a5897fc4e7 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/sub.cpp @@ -0,0 +1,147 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_sub(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // sub + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "sub.cl.h" + }; +#else + const std::string kernel_src = read_file("sub.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->sub.kernel_sub = clCreateKernel(prog, "kernel_sub", &err), err)); + CL_CHECK((backend_ctx->sub.kernel_sub_row = clCreateKernel(prog, "kernel_sub_row", &err), err)); + CL_CHECK((backend_ctx->sub.kernel_sub_f16 = clCreateKernel(prog, "kernel_sub_f16", &err), err)); + CL_CHECK((backend_ctx->sub.kernel_sub_row_f16 = clCreateKernel(prog, "kernel_sub_row_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_sub(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(src1); + GGML_ASSERT(src1->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + GGML_ASSERT(src0->type == src1->type); + GGML_ASSERT(src0->type == dst->type); + GGML_ASSERT(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16); + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne10 = src1->ne[0]; + const int ne11 = src1->ne[1]; + const int ne12 = src1->ne[2]; + const int ne13 = src1->ne[3]; + + const cl_ulong nb10 = src1->nb[0]; + const cl_ulong nb11 = src1->nb[1]; + const cl_ulong nb12 = src1->nb[2]; + const cl_ulong nb13 = src1->nb[3]; + + const int ne0 = dst->ne[0]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra1 = (ggml_tensor_extra_cl *)src1->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offset1 = extra1->offset + src1->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + bool bcast_row = false; + cl_kernel kernel; + + if (ggml_nelements(src1) == ne10 && ggml_is_contiguous(src1) && ne00 % 4 == 0 && ne10 % 4 == 0) { + GGML_ASSERT(ggml_is_contiguous(src0)); + + // src1 is a row + GGML_ASSERT(ne11 == 1); + + bcast_row = true; + int ne = ne00 / 4; + + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->sub.kernel_sub_row; + } else { + kernel = backend_ctx->sub.kernel_sub_row_f16; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne)); + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->sub.kernel_sub; + } else { + kernel = backend_ctx->sub.kernel_sub_f16; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra1->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offset1)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne10)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne11)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne12)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne13)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nb10)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nb11)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nb12)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nb13)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nb3)); + } + + if (bcast_row) { + int n = ggml_nelements(dst)/4; + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } else { + unsigned int nth = MIN(64, ne0); + size_t global_work_size[] = {ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/sum_rows.cpp b/ggml/src/ggml-opencl/ops/sum_rows.cpp new file mode 100644 index 000000000000..cf1e9631c548 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/sum_rows.cpp @@ -0,0 +1,84 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_sum_rows(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // sum_rows + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "sum_rows.cl.h" + }; +#else + const std::string kernel_src = read_file("sum_rows.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->sum_rows.kernel_sum_rows_f32 = clCreateKernel(prog, "kernel_sum_rows_f32", &err), err)); + CL_CHECK((backend_ctx->sum_rows.kernel_sum_rows_f32_4 = clCreateKernel(prog, "kernel_sum_rows_f32_4", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_sum_rows(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_UNUSED(src1); + + GGML_ASSERT(src0->nb[0] == ggml_type_size(src0->type)); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel; + + const bool is_c4 = ne00 % 4 == 0; + if (is_c4) { + kernel = backend_ctx->sum_rows.kernel_sum_rows_f32_4; + } else { + kernel = backend_ctx->sum_rows.kernel_sum_rows_f32; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne03)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nb3)); + + size_t global_work_size[] = {64 * (size_t)ne01, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)64, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/tanh.cpp b/ggml/src/ggml-opencl/ops/tanh.cpp new file mode 100644 index 000000000000..e8ce7e21b5df --- /dev/null +++ b/ggml/src/ggml-opencl/ops/tanh.cpp @@ -0,0 +1,123 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_tanh(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // tanh + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "tanh.cl.h" + }; +#else + const std::string kernel_src = read_file("tanh.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->tanh.kernel_tanh_f32 = clCreateKernel(prog, "kernel_tanh_f32", &err), err)); + CL_CHECK((backend_ctx->tanh.kernel_tanh_f32_4 = clCreateKernel(prog, "kernel_tanh_f32_4", &err), err)); + CL_CHECK((backend_ctx->tanh.kernel_tanh_f32_nc = clCreateKernel(prog, "kernel_tanh_f32_nc", &err), err)); + CL_CHECK((backend_ctx->tanh.kernel_tanh_f16 = clCreateKernel(prog, "kernel_tanh_f16", &err), err)); + CL_CHECK((backend_ctx->tanh.kernel_tanh_f16_4 = clCreateKernel(prog, "kernel_tanh_f16_4", &err), err)); + CL_CHECK((backend_ctx->tanh.kernel_tanh_f16_nc = clCreateKernel(prog, "kernel_tanh_f16_nc", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } +} + +void ggml_cl_tanh(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const cl_ulong nb0 = dst->nb[0]; + const cl_ulong nb1 = dst->nb[1]; + const cl_ulong nb2 = dst->nb[2]; + const cl_ulong nb3 = dst->nb[3]; + + cl_kernel kernel; + + if (ggml_is_contiguous(src0)) { + // Handle contiguous input + int n = ggml_nelements(dst); + if (n % 4 == 0) { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->tanh.kernel_tanh_f32_4; + } else { + kernel = backend_ctx->tanh.kernel_tanh_f16_4; + } + n /= 4; + } else { + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->tanh.kernel_tanh_f32; + } else { + kernel = backend_ctx->tanh.kernel_tanh_f16; + } + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); + } else { + // Handle non-contiguous input + if (src0->type == GGML_TYPE_F32) { + kernel = backend_ctx->tanh.kernel_tanh_f32_nc; + } else { + kernel = backend_ctx->tanh.kernel_tanh_f16_nc; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + int nth = 64; + + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/timestep_embedding.cpp b/ggml/src/ggml-opencl/ops/timestep_embedding.cpp new file mode 100644 index 000000000000..ee3c32f05339 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/timestep_embedding.cpp @@ -0,0 +1,72 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_timestep_embedding(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // timestep_embedding + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "tsembd.cl.h" + }; +#else + + const std::string kernel_src = read_file("tsembd.cl"); +#endif + if (!kernel_src.empty()) { + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->timestep_embedding.kernel_timestep_embedding = clCreateKernel(prog, "kernel_timestep_embedding", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } else { + GGML_LOG_WARN("ggml_opencl: timestep_embedding kernel source not found or empty. This op will not be available.\n"); + backend_ctx->timestep_embedding.kernel_timestep_embedding = nullptr; + } + } +} + +void ggml_cl_timestep_embedding(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(src0->type == GGML_TYPE_F32); + GGML_ASSERT(dst->type == GGML_TYPE_F32); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + if (backend_ctx->timestep_embedding.kernel_timestep_embedding == nullptr) { + GGML_LOG_WARN("%s: timestep_embedding kernel not available, skipping OpenCL execution.\n", __func__); + return; + } + + ggml_tensor_extra_cl * extra_src0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong off_src0 = extra_src0->offset + src0->view_offs; + cl_ulong off_dst = extra_dst->offset + dst->view_offs; + + const int logical_dim = dst->op_params[0]; + const int max_period = dst->op_params[1]; + const int dst_nb1_bytes = dst->nb[1]; + + cl_kernel kernel = backend_ctx->timestep_embedding.kernel_timestep_embedding; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &off_dst)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &dst_nb1_bytes)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &logical_dim)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &max_period)); + + size_t gws0 = (size_t)(((logical_dim + 1) / 2) + 1); + + size_t gws1 = (size_t)src0->ne[0]; + + size_t global_work_size[] = {gws0, gws1, 1}; + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, NULL, dst); +} diff --git a/ggml/src/ggml-opencl/ops/top_k.cpp b/ggml/src/ggml-opencl/ops/top_k.cpp new file mode 100644 index 000000000000..6c521913ab18 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/top_k.cpp @@ -0,0 +1,99 @@ +#include "../cl-common.h" + +void ggml_cl_load_kernels_top_k(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "top_k.cl.h" + }; +#else + const std::string kernel_src = read_file("top_k.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->top_k.kernel_top_k_f32 = clCreateKernel(prog, "kernel_top_k_f32", &err), err)); + CL_CHECK((backend_ctx->top_k.kernel_top_k_merge_f32 = clCreateKernel(prog, "kernel_top_k_merge_f32", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); +} + +void ggml_cl_top_k(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_UNUSED(src1); + + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *) src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + + const int k = dst->ne[0]; + cl_kernel kernel = backend_ctx->top_k.kernel_top_k_f32; + const int max_wg = backend_ctx->get_kernel_workgroup_size(kernel); + + int nth = 1; + const int target = MIN(512, MAX(32, ne00/4)); + while (2*nth <= MIN(target, max_wg)) { + nth *= 2; + } + + const size_t n_rows = ggml_nrows(src0); + const bool tiled = ne00 > 32768 && k > 0 && k <= 256 && n_rows <= 4; + const int tile_width = tiled ? 4096 : ne00; + const int n_tiles = tiled ? 1 + (ne00 - 1)/tile_width : 1; + const int n_candidates = (n_tiles - 1)*k + MIN(k, ne00 - (n_tiles - 1)*tile_width); + cl_mem candidates = nullptr; + if (tiled) { + GGML_ASSERT(n_rows <= SIZE_MAX/sizeof(cl_uint2)/(size_t) n_candidates); + backend_ctx->prealloc_top_k.allocate(backend_ctx->context, n_rows*(size_t) n_candidates*sizeof(cl_uint2)); + candidates = backend_ctx->prealloc_top_k.buffer; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 12, MAX(259, 2*nth)*sizeof(cl_uint), nullptr)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_mem), &candidates)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(int), &tile_width)); + + size_t global_work_size[] = { (size_t) nth*n_tiles, n_rows, 1 }; + size_t local_work_size[] = { (size_t) nth, 1, 1 }; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); + + if (tiled) { + // The global top-k is contained in the top-k of each tile. + kernel = backend_ctx->top_k.kernel_top_k_merge_f32; + const int max_wg_merge = backend_ctx->get_kernel_workgroup_size(kernel); + + int nth_merge = 1; + const int target_merge = MIN(512, MAX(32, n_candidates/4)); + while (2*nth_merge <= MIN(target_merge, max_wg_merge)) { + nth_merge *= 2; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &candidates)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &n_candidates)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &k)); + CL_CHECK(clSetKernelArg(kernel, 5, MAX(259, 2*nth_merge)*sizeof(cl_uint), nullptr)); + + global_work_size[0] = nth_merge; + local_work_size[0] = nth_merge; + + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global_work_size, local_work_size, dst); + } +} diff --git a/ggml/src/ggml-opencl/ops/top_k_mask.cpp b/ggml/src/ggml-opencl/ops/top_k_mask.cpp new file mode 100644 index 000000000000..1b4cd34f800b --- /dev/null +++ b/ggml/src/ggml-opencl/ops/top_k_mask.cpp @@ -0,0 +1,137 @@ +#include "../cl-common.h" + +void ggml_cl_load_kernels_top_k_mask(ggml_backend_opencl_context * backend_ctx) { + cl_int err; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "top_k_mask.cl.h" + }; +#else + const std::string kernel_src = read_file("top_k_mask.cl"); +#endif + // Scores can contain NaN and -inf, so do not use the default fast-math options. + const std::string opencl_c_std = + std::string("CL") + std::to_string(backend_ctx->opencl_c_version.major) + "." + std::to_string(backend_ctx->opencl_c_version.minor); + const std::string opts = "-cl-std=" + opencl_c_std + + (backend_ctx->adreno_use_large_buffer ? " -qcom-enable-large-buffer" : ""); + for (int i = 0; i < 2; ++i) { + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), opts + " -DMASK_F16=" + std::to_string(i == 0)); + CL_CHECK((backend_ctx->top_k_mask.kernel_top_k_mask[i] = clCreateKernel(prog, "kernel_top_k_mask", &err), err)); + CL_CHECK((backend_ctx->top_k_mask.kernel_top_k_mask_fill[i] = clCreateKernel(prog, "kernel_top_k_mask_fill", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + } + GGML_LOG_CONT("."); +} + +void ggml_cl_top_k_mask(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *) backend->context; + const ggml_tensor * score = dst->src[2]; + const ggml_tensor * blocks = dst->src[3]; + const ggml_tensor * extra = dst->src[4]; + const int type = dst->type == GGML_TYPE_F16 ? 0 : 1; + cl_kernel kernel = backend_ctx->top_k_mask.kernel_top_k_mask[type]; + + const ggml_tensor_extra_cl * extram = (const ggml_tensor_extra_cl *) src0->extra; + const ggml_tensor_extra_cl * extrak = (const ggml_tensor_extra_cl *) src1->extra; + const ggml_tensor_extra_cl * extras = score ? (const ggml_tensor_extra_cl *) score->extra : nullptr; + const ggml_tensor_extra_cl * extrab = blocks ? (const ggml_tensor_extra_cl *) blocks->extra : nullptr; + const ggml_tensor_extra_cl * extrae = extra ? (const ggml_tensor_extra_cl *) extra->extra : nullptr; + const ggml_tensor_extra_cl * extrad = (const ggml_tensor_extra_cl *) dst->extra; + + const cl_mem buffer_s = extras ? extras->data_device : nullptr; + const cl_mem buffer_b = extrab ? extrab->data_device : nullptr; + const cl_mem buffer_e = extrae ? extrae->data_device : nullptr; + + const cl_ulong offsetm = extram->offset + src0->view_offs; + const cl_ulong offsetk = extrak->offset + src1->view_offs; + const cl_ulong offsets = extras ? extras->offset + score->view_offs : 0; + const cl_ulong offsetb = extrab ? extrab->offset + blocks->view_offs : 0; + const cl_ulong offsete = extrae ? extrae->offset + extra->view_offs : 0; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + // single launch: fill == true, two launches: fill = false + // X2 benefits from a parallel fill for long single rows; mobile Adreno favors one launch. + const cl_int fill = !(backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E && + ggml_nrows(dst) == 1 && dst->ne[0] >= 65536 && ggml_is_contiguous(dst)); + + if (!fill) { + GGML_ASSERT(ggml_is_contiguous(dst)); + + cl_kernel kernel_fill = backend_ctx->top_k_mask.kernel_top_k_mask_fill[type]; + + const cl_ulong n = ggml_nelements(dst); + const size_t nv = 16/ggml_type_size(dst->type); + const size_t nth = MIN((size_t) 256, backend_ctx->get_kernel_workgroup_size(kernel_fill)); + + CL_CHECK(clSetKernelArg(kernel_fill, 0, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel_fill, 1, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel_fill, 2, sizeof(cl_ulong), &n)); + + size_t global[] = {((n + nv - 1)/nv + nth - 1)/nth*nth}; + size_t local[] = {nth}; + backend_ctx->enqueue_ndrange_kernel(kernel_fill, 1, global, local, dst); + } + + GGML_TENSOR_LOCALS(cl_ulong, nem, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nbm, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nek, src1, ne); + GGML_TENSOR_LOCALS(cl_ulong, nbk, src1, nb); + GGML_TENSOR_LOCALS(cl_ulong, nes, score, ne); + GGML_TENSOR_LOCALS(cl_ulong, nbs, score, nb); + GGML_TENSOR_LOCALS(cl_ulong, neb, blocks, ne); + GGML_TENSOR_LOCALS(cl_ulong, nbb, blocks, nb); + GGML_TENSOR_LOCALS(cl_ulong, nee, extra, ne); + GGML_TENSOR_LOCALS(cl_ulong, nbe, extra, nb); + GGML_TENSOR_LOCALS(cl_ulong, ned, dst, ne); + GGML_TENSOR_LOCALS(cl_ulong, nbd, dst, nb); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extram->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetm)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrak->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetk)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buffer_s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &offsets)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &buffer_b)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offsetb)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_mem), &buffer_e)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &offsete)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nem0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(cl_ulong), &nem1)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(cl_ulong), &nem2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(cl_ulong), &nem3)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(cl_ulong), &nbm1)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(cl_ulong), &nbm2)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(cl_ulong), &nbm3)); + CL_CHECK(clSetKernelArg(kernel, 19, sizeof(cl_ulong), &nek0)); + CL_CHECK(clSetKernelArg(kernel, 20, sizeof(cl_ulong), &nbk0)); + CL_CHECK(clSetKernelArg(kernel, 21, sizeof(cl_ulong), &nbk1)); + CL_CHECK(clSetKernelArg(kernel, 22, sizeof(cl_ulong), &nbk2)); + CL_CHECK(clSetKernelArg(kernel, 23, sizeof(cl_ulong), &nbk3)); + CL_CHECK(clSetKernelArg(kernel, 24, sizeof(cl_ulong), &nes0)); + CL_CHECK(clSetKernelArg(kernel, 25, sizeof(cl_ulong), &nbs0)); + CL_CHECK(clSetKernelArg(kernel, 26, sizeof(cl_ulong), &nbs1)); + CL_CHECK(clSetKernelArg(kernel, 27, sizeof(cl_ulong), &nbs2)); + CL_CHECK(clSetKernelArg(kernel, 28, sizeof(cl_ulong), &nbs3)); + CL_CHECK(clSetKernelArg(kernel, 29, sizeof(cl_ulong), &neb0)); + CL_CHECK(clSetKernelArg(kernel, 30, sizeof(cl_ulong), &neb1)); + CL_CHECK(clSetKernelArg(kernel, 31, sizeof(cl_ulong), &nbb0)); + CL_CHECK(clSetKernelArg(kernel, 32, sizeof(cl_ulong), &nbb1)); + CL_CHECK(clSetKernelArg(kernel, 33, sizeof(cl_ulong), &nee0)); + CL_CHECK(clSetKernelArg(kernel, 34, sizeof(cl_ulong), &nbe0)); + CL_CHECK(clSetKernelArg(kernel, 35, sizeof(cl_ulong), &nbe1)); + CL_CHECK(clSetKernelArg(kernel, 36, sizeof(cl_ulong), &nbe2)); + CL_CHECK(clSetKernelArg(kernel, 37, sizeof(cl_ulong), &nbe3)); + CL_CHECK(clSetKernelArg(kernel, 38, sizeof(cl_ulong), &ned1)); + CL_CHECK(clSetKernelArg(kernel, 39, sizeof(cl_ulong), &ned2)); + CL_CHECK(clSetKernelArg(kernel, 40, sizeof(cl_ulong), &nbd1)); + CL_CHECK(clSetKernelArg(kernel, 41, sizeof(cl_ulong), &nbd2)); + CL_CHECK(clSetKernelArg(kernel, 42, sizeof(cl_ulong), &nbd3)); + CL_CHECK(clSetKernelArg(kernel, 43, sizeof(cl_int), &fill)); + + const size_t nth = MIN((size_t) 512, backend_ctx->get_kernel_workgroup_size(kernel)); + size_t global[] = {nth, (size_t) ggml_nrows(dst)}; + size_t local[] = {nth, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst); +} diff --git a/ggml/src/ggml-opencl/ops/transpose.cpp b/ggml/src/ggml-opencl/ops/transpose.cpp new file mode 100644 index 000000000000..4897d0f287d3 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/transpose.cpp @@ -0,0 +1,12 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_transpose(ggml_backend_opencl_context * backend_ctx) { + GGML_UNUSED(backend_ctx); +} + +void ggml_cl_transpose( + ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + ggml_cl_nop(backend, src0, src1, dst); +} diff --git a/ggml/src/ggml-opencl/ops/tri.cpp b/ggml/src/ggml-opencl/ops/tri.cpp new file mode 100644 index 000000000000..75f69df00449 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/tri.cpp @@ -0,0 +1,62 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_tri(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // tri + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "tri.cl.h" + }; +#else + const std::string kernel_src = read_file("tri.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->tri.kernel_tri = clCreateKernel(prog, "kernel_tri_f32", &err), err)); + GGML_LOG_CONT("."); + + CL_CHECK(clReleaseProgram(prog)); + } +} + +void ggml_cl_tri(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + UNUSED(src1); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int tri_type = ggml_get_op_params_i32(dst, 0); + const int64_t n = ggml_nelements(dst); + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + + cl_kernel kernel = backend_ctx->tri.kernel_tri; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &n)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &tri_type)); + + size_t local_work_size[1] = { 256 }; + size_t global_work_size[1] = { ((size_t)n + local_work_size[0] - 1) / local_work_size[0] * local_work_size[0] }; + + backend_ctx->enqueue_ndrange_kernel(kernel, 1, global_work_size, local_work_size, dst); +} diff --git a/ggml/src/ggml-opencl/ops/unary-ext.cpp b/ggml/src/ggml-opencl/ops/unary-ext.cpp new file mode 100644 index 000000000000..4e827a1b4ca5 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/unary-ext.cpp @@ -0,0 +1,133 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_unary_ext(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // unary_ext (sgn, step, elu, hardswish, hardsigmoid, floor, ceil, round, trunc) + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "unary_ext.cl.h" + }; +#else + const std::string kernel_src = read_file("unary_ext.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); +#define CL_UNARY_EXT_K(op) \ + CL_CHECK((backend_ctx->unary_ext.kernel_##op##_f32 = clCreateKernel(prog, "kernel_" #op "_f32", &err), err)); \ + CL_CHECK((backend_ctx->unary_ext.kernel_##op##_f32_4 = clCreateKernel(prog, "kernel_" #op "_f32_4", &err), err)); \ + CL_CHECK((backend_ctx->unary_ext.kernel_##op##_f32_nc = clCreateKernel(prog, "kernel_" #op "_f32_nc", &err), err)); \ + CL_CHECK((backend_ctx->unary_ext.kernel_##op##_f16 = clCreateKernel(prog, "kernel_" #op "_f16", &err), err)); \ + CL_CHECK((backend_ctx->unary_ext.kernel_##op##_f16_4 = clCreateKernel(prog, "kernel_" #op "_f16_4", &err), err)); \ + CL_CHECK((backend_ctx->unary_ext.kernel_##op##_f16_nc = clCreateKernel(prog, "kernel_" #op "_f16_nc", &err), err)); + CL_UNARY_EXT_K(sgn) + CL_UNARY_EXT_K(step) + CL_UNARY_EXT_K(elu) + CL_UNARY_EXT_K(hardswish) + CL_UNARY_EXT_K(hardsigmoid) + CL_UNARY_EXT_K(floor) + CL_UNARY_EXT_K(ceil) + CL_UNARY_EXT_K(round) + CL_UNARY_EXT_K(trunc) + CL_UNARY_EXT_K(log) +#undef CL_UNARY_EXT_K + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +} + +// Shared driver for the extended unary ops (unary_ext.cl), same selection as +// ggml_cl_abs: contiguous picks the vec4 kernel when the element count is a +// multiple of 4 (else scalar); non-contiguous uses the stride-addressed kernel. +static void ggml_cl_unary_ext(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst, + cl_kernel k_f32, cl_kernel k_f32_4, cl_kernel k_f32_nc, + cl_kernel k_f16, cl_kernel k_f16_4, cl_kernel k_f16_nc) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + ggml_tensor_extra_cl * extra0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extrad = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong offset0 = extra0->offset + src0->view_offs; + cl_ulong offsetd = extrad->offset + dst->view_offs; + + const int ne00 = src0->ne[0], ne01 = src0->ne[1], ne02 = src0->ne[2], ne03 = src0->ne[3]; + const cl_ulong nb00 = src0->nb[0], nb01 = src0->nb[1], nb02 = src0->nb[2], nb03 = src0->nb[3]; + const cl_ulong nb0 = dst->nb[0], nb1 = dst->nb[1], nb2 = dst->nb[2], nb3 = dst->nb[3]; + + const bool is_f16 = (src0->type == GGML_TYPE_F16); + cl_kernel kernel; + + if (ggml_is_contiguous(src0)) { + int n = ggml_nelements(dst); + if (n % 4 == 0) { + kernel = is_f16 ? k_f16_4 : k_f32_4; + n /= 4; + } else { + kernel = is_f16 ? k_f16 : k_f32; + } + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + + size_t global_work_size[] = {(size_t)n, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + size_t * local_work_size_ptr = local_work_size; + if (n % 64 != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); + } else { + kernel = is_f16 ? k_f16_nc : k_f32_nc; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + + int nth = 64; + size_t global_work_size[] = {(size_t)ne01*nth, (size_t)ne02, (size_t)ne03}; + size_t local_work_size[] = {(size_t)nth, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst); + } +} + +#define GGML_CL_UNARY_EXT_WRAP(FN, OP) \ +void FN(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { \ + UNUSED(src1); \ + ggml_backend_opencl_context *c = (ggml_backend_opencl_context *)backend->context; \ + ggml_cl_unary_ext(backend, src0, dst, c->unary_ext.kernel_##OP##_f32, c->unary_ext.kernel_##OP##_f32_4, \ + c->unary_ext.kernel_##OP##_f32_nc, c->unary_ext.kernel_##OP##_f16, \ + c->unary_ext.kernel_##OP##_f16_4, c->unary_ext.kernel_##OP##_f16_nc); \ +} + +GGML_CL_UNARY_EXT_WRAP(ggml_cl_sgn, sgn) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_step, step) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_elu, elu) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_hardswish, hardswish) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_hardsigmoid, hardsigmoid) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_floor, floor) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_ceil, ceil) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_round, round) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_trunc, trunc) +GGML_CL_UNARY_EXT_WRAP(ggml_cl_log, log) + +#undef GGML_CL_UNARY_EXT_WRAP diff --git a/ggml/src/ggml-opencl/ops/upscale.cpp b/ggml/src/ggml-opencl/ops/upscale.cpp new file mode 100644 index 000000000000..cded8d378d2f --- /dev/null +++ b/ggml/src/ggml-opencl/ops/upscale.cpp @@ -0,0 +1,148 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_upscale(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // upscale + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "upscale.cl.h" + }; +#else + const std::string kernel_src = read_file("upscale.cl"); +#endif + if (!kernel_src.empty()) { + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->upscale.kernel_upscale = clCreateKernel(prog, "kernel_upscale", &err), err)); + cl_int err_bilinear; + backend_ctx->upscale.kernel_upscale_bilinear = clCreateKernel(prog, "kernel_upscale_bilinear", &err_bilinear); + if (err_bilinear != CL_SUCCESS) { + GGML_LOG_WARN("ggml_opencl: kernel_upscale_bilinear not found in upscale.cl. Bilinear upscale will not be available. Error: %d\n", err_bilinear); + backend_ctx->upscale.kernel_upscale_bilinear = nullptr; + } + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } else { + GGML_LOG_WARN("ggml_opencl: upscale kernel source not found or empty. Upscale operations will not be available.\n"); + backend_ctx->upscale.kernel_upscale = nullptr; + backend_ctx->upscale.kernel_upscale_bilinear = nullptr; + } + } +} + +void ggml_cl_upscale(ggml_backend_t backend, const ggml_tensor * src0, ggml_tensor * dst) { + GGML_ASSERT(src0); + GGML_ASSERT(src0->extra); + GGML_ASSERT(dst); + GGML_ASSERT(dst->extra); + GGML_ASSERT(src0->type == GGML_TYPE_F32); + GGML_ASSERT(dst->type == GGML_TYPE_F32); + + ggml_backend_opencl_context *backend_ctx = (ggml_backend_opencl_context *)backend->context; + + const int mode_flags = (ggml_scale_mode) ggml_get_op_params_i32(dst, 0); + const ggml_scale_mode mode = (ggml_scale_mode) (mode_flags & 0xFF); + cl_kernel kernel = nullptr; + + if (mode == GGML_SCALE_MODE_NEAREST) { + kernel = backend_ctx->upscale.kernel_upscale; + if (kernel == nullptr) { + GGML_LOG_WARN("%s: nearest upscale kernel not available, skipping OpenCL execution.\n", __func__); + return; + } + } else if (mode == GGML_SCALE_MODE_BILINEAR) { + kernel = backend_ctx->upscale.kernel_upscale_bilinear; + if (kernel == nullptr) { + GGML_LOG_WARN("%s: bilinear upscale kernel not available, skipping OpenCL execution.\n", __func__); + return; + } + } else { + GGML_LOG_WARN("%s: unsupported upscale mode %d, skipping OpenCL execution.\n", __func__, mode); + return; + } + + ggml_tensor_extra_cl * extra_src0 = (ggml_tensor_extra_cl *)src0->extra; + ggml_tensor_extra_cl * extra_dst = (ggml_tensor_extra_cl *)dst->extra; + + cl_ulong off_src0 = extra_src0->offset + src0->view_offs; + cl_ulong off_dst = extra_dst->offset + dst->view_offs; + + const cl_ulong nb00 = src0->nb[0]; + const cl_ulong nb01 = src0->nb[1]; + const cl_ulong nb02 = src0->nb[2]; + const cl_ulong nb03 = src0->nb[3]; + + const int ne00 = src0->ne[0]; + const int ne01 = src0->ne[1]; + const int ne02 = src0->ne[2]; + const int ne03 = src0->ne[3]; + + const int ne0 = dst->ne[0]; + const int ne1 = dst->ne[1]; + const int ne2 = dst->ne[2]; + const int ne3 = dst->ne[3]; + + float sf0 = (float)ne0 / ne00; + float sf1 = (float)ne1 / ne01; + float sf2 = (float)ne2 / ne02; + float sf3 = (float)ne3 / ne03; + + float pixel_offset = 0.5f; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra_src0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra_dst->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &off_dst)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb03)); + + if (mode == GGML_SCALE_MODE_NEAREST) { + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne3)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(float), &sf0)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &sf1)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &sf2)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &sf3)); + } else if (mode == GGML_SCALE_MODE_BILINEAR) { + if (mode_flags & GGML_SCALE_FLAG_ALIGN_CORNERS) { + sf0 = ne0 > 1 && ne00 > 1 ? (float)(ne0 - 1) / (ne00 - 1) : sf0; + sf1 = ne1 > 1 && ne01 > 1 ? (float)(ne1 - 1) / (ne01 - 1) : sf1; + pixel_offset = 0.0f; + } + + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(int), &ne0)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne1)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne2)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(int), &ne3)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &sf0)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &sf1)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &sf2)); + CL_CHECK(clSetKernelArg(kernel, 17, sizeof(float), &sf3)); + CL_CHECK(clSetKernelArg(kernel, 18, sizeof(float), &pixel_offset)); + } + + + size_t dst_total_elements = (size_t)ne0 * ne1 * ne2 * ne3; + if (dst_total_elements == 0) { + return; + } + size_t global_work_size[] = { dst_total_elements, 1, 1 }; + size_t local_work_size_pref = 256; + size_t local_work_size[] = { MIN(local_work_size_pref, dst_total_elements), 1, 1}; + + size_t * local_work_size_ptr = local_work_size; + if (dst_total_elements % local_work_size[0] != 0 && !backend_ctx->non_uniform_workgroups) { + local_work_size_ptr = nullptr; + } + + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size_ptr, dst); +} diff --git a/ggml/src/ggml-opencl/ops/view.cpp b/ggml/src/ggml-opencl/ops/view.cpp new file mode 100644 index 000000000000..b2a0672d80fe --- /dev/null +++ b/ggml/src/ggml-opencl/ops/view.cpp @@ -0,0 +1,12 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_view(ggml_backend_opencl_context * backend_ctx) { + GGML_UNUSED(backend_ctx); +} + +void ggml_cl_view( + ggml_backend_t backend, const ggml_tensor * src0, + const ggml_tensor * src1, ggml_tensor * dst) { + ggml_cl_nop(backend, src0, src1, dst); +} diff --git a/ggml/src/ggml-opencl/ops/xielu.cpp b/ggml/src/ggml-opencl/ops/xielu.cpp new file mode 100644 index 000000000000..9d8fabe9e6c4 --- /dev/null +++ b/ggml/src/ggml-opencl/ops/xielu.cpp @@ -0,0 +1,64 @@ +#include "../cl-common.h" +#include "../ops.h" + +void ggml_cl_load_kernels_xielu(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "xielu.cl.h" + }; +#else + const std::string kernel_src = read_file("xielu.cl"); +#endif + cl_program prog = build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + CL_CHECK((backend_ctx->xielu.kernel_xielu_f32 = clCreateKernel(prog, "kernel_xielu_f32", &err), err)); + CL_CHECK((backend_ctx->xielu.kernel_xielu_f16 = clCreateKernel(prog, "kernel_xielu_f16", &err), err)); + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); +} + +void ggml_cl_xielu(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) { + UNUSED(src1); + + auto * backend_ctx = (ggml_backend_opencl_context *) backend->context; + cl_kernel kernel = src0->type == GGML_TYPE_F16 ? backend_ctx->xielu.kernel_xielu_f16 : backend_ctx->xielu.kernel_xielu_f32; + + const auto * extra0 = (const ggml_tensor_extra_cl *) src0->extra; + const auto * extrad = (const ggml_tensor_extra_cl *) dst->extra; + + const cl_ulong offset0 = extra0->offset + src0->view_offs; + const cl_ulong offsetd = extrad->offset + dst->view_offs; + + GGML_TENSOR_LOCALS(int, ne0, src0, ne); + GGML_TENSOR_LOCALS(cl_ulong, nb0, src0, nb); + GGML_TENSOR_LOCALS(cl_ulong, nb, dst, nb); + + const float alpha_n = ggml_get_op_params_f32(dst, 1); + const float alpha_p = ggml_get_op_params_f32(dst, 2); + const float beta = ggml_get_op_params_f32(dst, 3); + const float eps = ggml_get_op_params_f32(dst, 4); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra0->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offset0)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extrad->data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsetd)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &nb02)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &nb03)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &nb0)); + CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_ulong), &nb1)); + CL_CHECK(clSetKernelArg(kernel, 11, sizeof(cl_ulong), &nb2)); + CL_CHECK(clSetKernelArg(kernel, 12, sizeof(cl_ulong), &nb3)); + CL_CHECK(clSetKernelArg(kernel, 13, sizeof(float), &alpha_n)); + CL_CHECK(clSetKernelArg(kernel, 14, sizeof(float), &alpha_p)); + CL_CHECK(clSetKernelArg(kernel, 15, sizeof(float), &beta)); + CL_CHECK(clSetKernelArg(kernel, 16, sizeof(float), &eps)); + + const size_t nth = 64; + size_t global[] = {(size_t) ne01*nth, (size_t) ne02, (size_t) ne03}; + size_t local[] = {nth, 1, 1}; + backend_ctx->enqueue_ndrange_kernel(kernel, 3, global, local, dst); +} diff --git a/ggml/src/ggml-opencl/repack.cpp b/ggml/src/ggml-opencl/repack.cpp new file mode 100644 index 000000000000..78df3886a4bb --- /dev/null +++ b/ggml/src/ggml-opencl/repack.cpp @@ -0,0 +1,2702 @@ +#include "cl-common.h" + +void ggml_cl_load_kernels_repack(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + // cvt + { +#ifdef GGML_OPENCL_EMBED_KERNELS + const std::string kernel_src { + #include "cvt.cl.h" + }; +#else + const std::string kernel_src = read_file("cvt.cl"); +#endif + cl_program prog = + build_program_from_source(backend_ctx, kernel_src.c_str(), compile_opts); + + CL_CHECK((backend_ctx->repack.kernel_convert_block_q1_0 = clCreateKernel(prog, "kernel_convert_block_q1_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q1_0 = clCreateKernel(prog, "kernel_restore_block_q1_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_0_noshuffle = clCreateKernel(prog, "kernel_convert_block_q4_0_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_0_noshuffle = clCreateKernel(prog, "kernel_restore_block_q4_0_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_0 = clCreateKernel(prog, "kernel_convert_block_q4_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_0 = clCreateKernel(prog, "kernel_restore_block_q4_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_0_trans4_ns = clCreateKernel(prog, "kernel_convert_block_q4_0_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_0_trans4_ns = clCreateKernel(prog, "kernel_restore_block_q4_0_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_1_noshuffle = clCreateKernel(prog, "kernel_convert_block_q4_1_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_1_noshuffle = clCreateKernel(prog, "kernel_restore_block_q4_1_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_1 = clCreateKernel(prog, "kernel_convert_block_q4_1", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_1 = clCreateKernel(prog, "kernel_restore_block_q4_1", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_1_trans4_ns = clCreateKernel(prog, "kernel_convert_block_q4_1_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_1_trans4_ns = clCreateKernel(prog, "kernel_restore_block_q4_1_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_0 = clCreateKernel(prog, "kernel_convert_block_q5_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_0 = clCreateKernel(prog, "kernel_restore_block_q5_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_0_noshuffle = clCreateKernel(prog, "kernel_convert_block_q5_0_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_0_noshuffle = clCreateKernel(prog, "kernel_restore_block_q5_0_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_1_noshuffle = clCreateKernel(prog, "kernel_convert_block_q5_1_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_1_noshuffle = clCreateKernel(prog, "kernel_restore_block_q5_1_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_0_trans4_ns = clCreateKernel(prog, "kernel_convert_block_q5_0_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_0_trans4_ns = clCreateKernel(prog, "kernel_restore_block_q5_0_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_1 = clCreateKernel(prog, "kernel_convert_block_q5_1", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_1 = clCreateKernel(prog, "kernel_restore_block_q5_1", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_1_trans4_ns = clCreateKernel(prog, "kernel_convert_block_q5_1_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_1_trans4_ns = clCreateKernel(prog, "kernel_restore_block_q5_1_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_k_trans4_ns = clCreateKernel(prog, "kernel_convert_block_q4_k_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_k_trans4_ns = clCreateKernel(prog, "kernel_restore_block_q4_k_trans4_ns", &err), err)); +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_k_tiled_ns = clCreateKernel(prog, "kernel_convert_block_q4_k_tiled_ns", &err), err)); +#endif + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_k_trans4_ns = clCreateKernel(prog, "kernel_convert_block_q5_k_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_k_trans4_ns = clCreateKernel(prog, "kernel_restore_block_q5_k_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q6_k_trans4_ns = clCreateKernel(prog, "kernel_convert_block_q6_k_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q6_k_trans4_ns = clCreateKernel(prog, "kernel_restore_block_q6_k_trans4_ns", &err), err)); +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + CL_CHECK((backend_ctx->repack.kernel_convert_block_q6_k_tiled_ns = clCreateKernel(prog, "kernel_convert_block_q6_k_tiled_ns", &err), err)); +#endif + CL_CHECK((backend_ctx->repack.kernel_convert_block_mxfp4 = clCreateKernel(prog, "kernel_convert_block_mxfp4", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_mxfp4_trans = clCreateKernel(prog, "kernel_convert_block_mxfp4_trans", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_mxfp4_trans4_ns = clCreateKernel(prog, "kernel_convert_block_mxfp4_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_mxfp4_trans4_ns = clCreateKernel(prog, "kernel_restore_block_mxfp4_trans4_ns", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_mxfp4_trans = clCreateKernel(prog, "kernel_restore_block_mxfp4_trans", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_mxfp4 = clCreateKernel(prog, "kernel_restore_block_mxfp4", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q8_0 = clCreateKernel(prog, "kernel_convert_block_q8_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q8_0 = clCreateKernel(prog, "kernel_restore_block_q8_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q8_0_trans = clCreateKernel(prog, "kernel_restore_block_q8_0_trans", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_dequant_q8_0_f16_view_aos = clCreateKernel(prog, "kernel_dequant_q8_0_f16_view_aos", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_dequant_q8_0_f32_view_aos = clCreateKernel(prog, "kernel_dequant_q8_0_f32_view_aos", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_dequant_q4_0_f16_view_aos = clCreateKernel(prog, "kernel_dequant_q4_0_f16_view_aos", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_dequant_q4_0_f32_view_aos = clCreateKernel(prog, "kernel_dequant_q4_0_f32_view_aos", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_K = clCreateKernel(prog, "kernel_convert_block_q4_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_K = clCreateKernel(prog, "kernel_restore_block_q4_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q4_K_noshuffle = clCreateKernel(prog, "kernel_convert_block_q4_K_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q4_K_noshuffle = clCreateKernel(prog, "kernel_restore_block_q4_K_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_K = clCreateKernel(prog, "kernel_convert_block_q5_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_K = clCreateKernel(prog, "kernel_restore_block_q5_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q5_K_noshuffle = clCreateKernel(prog, "kernel_convert_block_q5_K_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q5_K_noshuffle = clCreateKernel(prog, "kernel_restore_block_q5_K_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q2_k_noshuffle = clCreateKernel(prog, "kernel_convert_block_q2_k_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q2_k_noshuffle = clCreateKernel(prog, "kernel_restore_block_q2_k_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q3_k_noshuffle = clCreateKernel(prog, "kernel_convert_block_q3_k_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q3_k_noshuffle = clCreateKernel(prog, "kernel_restore_block_q3_k_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q3_K = clCreateKernel(prog, "kernel_convert_block_q3_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q3_K = clCreateKernel(prog, "kernel_restore_block_q3_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q2_K = clCreateKernel(prog, "kernel_convert_block_q2_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q2_K = clCreateKernel(prog, "kernel_restore_block_q2_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq2_xxs = clCreateKernel(prog, "kernel_convert_block_iq2_xxs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq2_xxs = clCreateKernel(prog, "kernel_restore_block_iq2_xxs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq2_xs = clCreateKernel(prog, "kernel_convert_block_iq2_xs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq2_xs = clCreateKernel(prog, "kernel_restore_block_iq2_xs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq2_s = clCreateKernel(prog, "kernel_convert_block_iq2_s", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq2_s = clCreateKernel(prog, "kernel_restore_block_iq2_s", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q2_0 = clCreateKernel(prog, "kernel_convert_block_q2_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q2_0 = clCreateKernel(prog, "kernel_restore_block_q2_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq1_s = clCreateKernel(prog, "kernel_convert_block_iq1_s", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq1_s = clCreateKernel(prog, "kernel_restore_block_iq1_s", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq1_m = clCreateKernel(prog, "kernel_convert_block_iq1_m", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq1_m = clCreateKernel(prog, "kernel_restore_block_iq1_m", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq3_xxs = clCreateKernel(prog, "kernel_convert_block_iq3_xxs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq3_xxs = clCreateKernel(prog, "kernel_restore_block_iq3_xxs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq3_s = clCreateKernel(prog, "kernel_convert_block_iq3_s", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq3_s = clCreateKernel(prog, "kernel_restore_block_iq3_s", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq4_xs_noshuffle = clCreateKernel(prog, "kernel_convert_block_iq4_xs_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq4_xs_noshuffle = clCreateKernel(prog, "kernel_restore_block_iq4_xs_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq4_xs = clCreateKernel(prog, "kernel_convert_block_iq4_xs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq4_xs = clCreateKernel(prog, "kernel_restore_block_iq4_xs", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q6_K = clCreateKernel(prog, "kernel_convert_block_q6_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q6_K = clCreateKernel(prog, "kernel_restore_block_q6_K", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_q6_K_noshuffle = clCreateKernel(prog, "kernel_convert_block_q6_K_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_q6_K_noshuffle = clCreateKernel(prog, "kernel_restore_block_q6_K_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq4_nl = clCreateKernel(prog, "kernel_convert_block_iq4_nl", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq4_nl = clCreateKernel(prog, "kernel_restore_block_iq4_nl", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_block_iq4_nl_noshuffle = clCreateKernel(prog, "kernel_convert_block_iq4_nl_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_restore_block_iq4_nl_noshuffle = clCreateKernel(prog, "kernel_restore_block_iq4_nl_noshuffle", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_bf16_to_f16 = clCreateKernel(prog, "kernel_convert_bf16_to_f16", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_convert_f16_to_bf16 = clCreateKernel(prog, "kernel_convert_f16_to_bf16", &err), err)); +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + CL_CHECK((backend_ctx->repack.kernel_moe_expand_scale_q8_0 = clCreateKernel(prog, "kernel_moe_expand_scale_q8_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_moe_expand_scale_q5_0 = clCreateKernel(prog, "kernel_moe_expand_scale_q5_0", &err), err)); + CL_CHECK((backend_ctx->repack.kernel_moe_expand_scale_q5_K = clCreateKernel(prog, "kernel_moe_expand_scale_q5_K", &err), err)); +#endif + CL_CHECK(clReleaseProgram(prog)); + GGML_LOG_CONT("."); + } + +} +static cl_mem ggml_cl_create_temp_upload_buffer( + cl_context context, cl_command_queue queue, + size_t nbytes, const void * data, + const char * tensor_name_for_log) +{ + cl_int err; + cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); + if (err != CL_SUCCESS) { + clFinish(queue); + buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); + } + if (err == CL_SUCCESS) { + const cl_int werr = clEnqueueWriteBuffer(queue, buf, CL_TRUE, 0, nbytes, data, 0, NULL, NULL); + if (werr == CL_SUCCESS) { + return buf; + } + clReleaseMemObject(buf); + } + buf = clCreateBuffer(context, + CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR | CL_MEM_HOST_WRITE_ONLY, + nbytes, NULL, &err); + if (err != CL_SUCCESS) { + return NULL; + } + void * mapped = clEnqueueMapBuffer(queue, buf, CL_TRUE, + CL_MAP_WRITE_INVALIDATE_REGION, 0, nbytes, 0, NULL, NULL, &err); + if (err != CL_SUCCESS) { + clReleaseMemObject(buf); + return NULL; + } + memcpy(mapped, data, nbytes); + const cl_int uerr = clEnqueueUnmapMemObject(queue, buf, mapped, 0, NULL, NULL); + if (uerr != CL_SUCCESS) { + clReleaseMemObject(buf); + return NULL; + } + if (tensor_name_for_log) { + GGML_LOG_INFO("ggml_opencl: %s (%.1f MiB) - device alloc failed, using CL_MEM_ALLOC_HOST_PTR fallback\n", + tensor_name_for_log, nbytes / 1024.0 / 1024.0); + } + return buf; +} + +void ggml_backend_opencl_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data, size_t offset, size_t size) { + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; + ggml_backend_opencl_context * backend_ctx = dev_ctx->backend_ctx; + + cl_context context = backend_ctx->context; + cl_command_queue queue = backend_ctx->queue; + +#ifdef GGML_OPENCL_SOA_Q + if (tensor->type == GGML_TYPE_Q2_K) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q2_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q2_K(); + extra->noshuffle = ggml_cl_q2_k_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * (blck/4); + const size_t size_sc = n_blk * (blck/16); + const size_t size_dm = n_blk * 2 * sizeof(ggml_fp16_t); + GGML_ASSERT(size_qs + size_sc + size_dm == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + auto previous_origin = region.origin; + + region.origin = align_to(previous_origin + size_qs, backend_ctx->alignment); + region.size = size_sc; + CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + + region.origin = align_to(previous_origin + size_sc, backend_ctx->alignment); + region.size = size_dm; + CL_CHECK((extra->dm = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = extra->noshuffle ? backend_ctx->repack.kernel_convert_block_q2_k_noshuffle + : backend_ctx->repack.kernel_convert_block_q2_K; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/16, m, true, true); + transpose_2d_as_32b(backend_ctx, extra->dm, extra->dm, size_dm, k/(int)blck, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_sc = size_sc; + extra->size_dm = size_dm; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_Q3_K) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q3_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q3_K(); + extra->noshuffle = ggml_cl_q3_k_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * (blck/4); + const size_t size_hm = n_blk * (blck/8); + const size_t size_sc = n_blk * 12; + const size_t size_d = n_blk * sizeof(ggml_fp16_t); + GGML_ASSERT(size_qs + size_hm + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + auto previous_origin = region.origin; + + region.origin = align_to(previous_origin + size_qs, backend_ctx->alignment); + region.size = size_hm; + CL_CHECK((extra->hm = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + + region.origin = align_to(previous_origin + size_hm, backend_ctx->alignment); + region.size = size_sc; + CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + + region.origin = align_to(previous_origin + size_sc, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = extra->noshuffle ? backend_ctx->repack.kernel_convert_block_q3_k_noshuffle + : backend_ctx->repack.kernel_convert_block_q3_K; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->hm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->hm, extra->hm, size_hm, k/8, m, true, true); + transpose_2d_as_32b(backend_ctx, extra->sc, extra->sc, size_sc, 3*k/(int)blck, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_hm = size_hm; + extra->size_sc = size_sc; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_IQ3_S) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq3_s * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq3_s(); + extra->noshuffle = ggml_cl_iq3_s_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 64; + const size_t size_sg = n_blk * 32; + const size_t size_qh = n_blk * 8; + const size_t size_sc = n_blk * 4; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_sg + size_qh + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_sg; + CL_CHECK((extra->sg = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sg, backend_ctx->alignment); + region.size = size_qh; + CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); + region.size = size_sc; + CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sc, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq3_s; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sg)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->sc)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->sg, extra->sg, size_sg, k/8, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, k/32, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/64, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/256, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_sg = size_sg; + extra->size_qh = size_qh; + extra->size_sc = size_sc; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_IQ3_XXS) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq3_xxs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq3_xxs(); + extra->noshuffle = ggml_cl_iq3_xxs_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 64; + const size_t size_sas = n_blk * 32; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_sas + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_sas; + CL_CHECK((extra->sas = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sas, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq3_xxs; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sas)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); + transpose_2d_as_32b(backend_ctx, extra->sas, extra->sas, size_sas, k/32, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/256, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_sas = size_sas; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_IQ1_M) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq1_m * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq1_m(); + extra->noshuffle = ggml_cl_iq1_m_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 32; + const size_t size_qh = n_blk * 16; + const size_t size_sc = n_blk * 8; + GGML_ASSERT(size_qs + size_qh + size_sc == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_qh; + CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); + region.size = size_sc; + CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq1_m; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, k/16, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->sc, extra->sc, size_sc, k/64, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_qh = size_qh; + extra->size_sc = size_sc; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_IQ1_S) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq1_s * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq1_s(); + extra->noshuffle = ggml_cl_iq1_s_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 32; + const size_t size_qh = n_blk * 16; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_qh + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_qh; + CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq1_s; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->qh, extra->qh, size_qh, k/32, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_qh = size_qh; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_IQ2_S) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq2_s * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq2_s(); + extra->noshuffle = ggml_cl_iq2_s_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 32; + const size_t size_sg = n_blk * 32; + const size_t size_qh = n_blk * 8; + const size_t size_sc = n_blk * 8; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_sg + size_qh + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_sg; + CL_CHECK((extra->sg = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sg, backend_ctx->alignment); + region.size = size_qh; + CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qh, backend_ctx->alignment); + region.size = size_sc; + CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sc, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq2_s; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sg)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->sc)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->sg, extra->sg, size_sg, k/8, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, k/32, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/32, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_sg = size_sg; + extra->size_qh = size_qh; + extra->size_sc = size_sc; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_IQ2_XS) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq2_xs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq2_xs(); + extra->noshuffle = ggml_cl_iq2_xs_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 64; + const size_t size_sc = n_blk * 8; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_sc + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_sc; + CL_CHECK((extra->sc = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sc, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq2_xs; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, extra->sc, size_sc, k/32, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_sc = size_sc; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_IQ2_XXS) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq2_xxs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq2_xxs(); + extra->noshuffle = ggml_cl_iq2_xxs_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 32; + const size_t size_sas = n_blk * 32; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_sas + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_sas; + CL_CHECK((extra->sas = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sas, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq2_xxs; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sas)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/8, m, true, true); + transpose_2d_as_32b(backend_ctx, extra->sas, extra->sas, size_sas, k/32, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/(int)blck, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_sas = size_sas; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_Q1_0) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q1_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q1_0(); + + // q1_0 block = ggml_half d + (QK1_0/8) quant bytes = 2 + 16 = 18 bytes + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)/8); + GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + // The original tensor memory is divided into scales and quants, i.e., + // we first store scales, then quants. + cl_buffer_region region; + + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for quants. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q1_0; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + + // q is uint32 (32 sign bits each); d is one half per 128-block. +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (enable_adreno_trans_weight(backend_ctx, tensor)) { + int M = tensor->ne[1]; // ne01 + int K = tensor->ne[0]; // ne00 + + GGML_ASSERT(K % 128 == 0); + GGML_ASSERT(M % 4 == 0); + GGML_ASSERT(tensor->ne[2] == 1); + GGML_ASSERT(tensor->ne[3] == 1); + + transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/32, M); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/128, M); + } // end transpose +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + return; + } + + if (tensor->type == GGML_TYPE_Q2_0) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q2_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q2_0(); + extra->noshuffle = ggml_cl_q2_0_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 16; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q2_0; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/64, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + // We separate the quantized bits and scale from block_q4_0 by using an + // additional kernel, where each thread handles a block. We first read the + // original weights into a temporary buffer, then create two separate + // buffers for quantized bits and scales, which are then populated by the + // conversion kernel. + if (tensor->type == GGML_TYPE_Q4_0) { + // Views can't SoA-ify here — parent owns the layout (see q8_0 guard). + // A view of an AoS tensor (the KV cache, written by a state restore) + // is written in place. + if (tensor->view_src != nullptr || !ggml_is_contiguous(tensor)) { + if (!ggml_cl_is_q4_0_soa(tensor)) { + ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; + CL_CHECK(clEnqueueWriteBuffer( + queue, extra_aos->data_device, CL_TRUE, + extra_aos->offset + tensor->view_offs + offset, + size, data, 0, NULL, NULL)); + } + return; + } + // Tensors should have been preallocated, therefore they should + // already have ggml_tensor_extra_cl as extra. + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q4_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q4_0(); + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); + + // We consider the specified offset arg as always, although For weights + // the offset arg should be 0 (we do not assert this). + //GGML_ASSERT(offset == 0); + + // We create subbuffers from the original tensor buffer for scales and + // quants - i.e., scales and quants are aliases into the buffer object + // that backs the original tensor. This is a cleaner way to adapt to the + // new memory management. + // In the old code, we allocate new buffers for scales and quants + // respectively, which could still be done but would result in double + // allocation; properly deallocating the preallocated buffer that backs + // the tensors is tricky and would leak the backend specific information + // into the general backend code. + // Does this create misaligned subbuffers (alignment is 1024) in certain + // cases ? + cl_buffer_region region; + + // The original tensor memory is divided into scales and quants, i.e., + // we first store scales, then quants. + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for quants. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno moe q4_0 kernel needs special transpose and unshuffling + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_0_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + // Create image for Q + cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_q = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->q } + }; + extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); + tensor->extra = extra; + // MoE tensors are also SOA'ed + ctx->q4_0_soa_tensors.insert(tensor); + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_0; + + // The optimized kernels need weights in natural order, so unshuffle. + if (use_adreno_kernels(backend_ctx, tensor)) { + kernel = backend_ctx->repack.kernel_convert_block_q4_0_noshuffle; + } +#else + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_0; +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + ctx->q4_0_soa_tensors.insert(tensor); + + // transpose the weights and scales +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Only do transpose for large, non batched matrix + // TODO: use preallocated images instead of sub-buffer then image + if (use_adreno_kernels(backend_ctx, tensor)) { + int M = tensor->ne[1]; + int K = tensor->ne[0]; + + GGML_ASSERT(K % 32 == 0); + + if (use_q4_0_bin_kernels(backend_ctx, tensor)) { + cl_int err; + cl_image_format wimg_fmt; + cl_image_desc wimg_desc; + + // transpose quants as 32-bit words (M-first) + GGML_ASSERT(M % 64 == 0); + transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K / 8, M); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K / 32, M); + + wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&wimg_desc, 0, sizeof(wimg_desc)); + wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + wimg_desc.image_width = (size_t)M * K / 8; + wimg_desc.buffer = extra->q; + CL_CHECK((extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); + + wimg_fmt = { CL_R, CL_HALF_FLOAT }; + memset(&wimg_desc, 0, sizeof(wimg_desc)); + wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + wimg_desc.image_width = (size_t)M * K / 32; + wimg_desc.buffer = extra->d; + CL_CHECK((extra->d_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); + } else { + // Transpose q and d as ushort + transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); + } + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + return; + } + if (tensor->type == GGML_TYPE_Q4_1) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q4_1 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q4_1(); + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_m = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + GGML_ASSERT(size_d + size_m + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); + + cl_buffer_region region; + + // The original tensor memory is divided into scales and quants, i.e., + // we first store scales, mins, then quants. + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for mins. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_m; + extra->m = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for quants. + region.origin = align_to(previous_origin + size_m, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno moe q4_1 kernel needs special transpose and unshuffling + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_1_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + // Create image for Q + cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_q = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->q } + }; + extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); + tensor->extra = extra; + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + // normal q4_1 repack +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_1; + + if (use_adreno_kernels(backend_ctx, tensor)) { + kernel = backend_ctx->repack.kernel_convert_block_q4_1_noshuffle; + } +#else + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_1; +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_kernels(backend_ctx, tensor)) { + + int M = tensor->ne[1]; + int K = tensor->ne[0]; + + GGML_ASSERT(K % 32 == 0); + + // Transpose q as ushort + transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); + // Transpose d as ushort + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); + // Transpose m as ushort + transpose_2d_as_16b(backend_ctx, extra->m, extra->m, size_m, K/32, M); + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + return; + } + if (tensor->type == GGML_TYPE_Q5_0) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q5_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q5_0(); + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_qs = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(int32_t); + GGML_ASSERT(size_d + size_qs + size_qh == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); + + cl_buffer_region region; + + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for qh. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_qh; + extra->qh = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for qs. + region.origin = align_to(previous_origin + size_qh, backend_ctx->alignment); + region.size = size_qs; + extra->qs = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno moe q5_0 kernel needs special transpose and unshuffling + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_0_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + // Create image for Q + cl_image_format img_format_qs = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_qs = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->qs } + }; + extra->qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_qs, &img_desc_qs, NULL, &err); + tensor->extra = extra; + + // Generic dp4a MoE path + { + static const char * q5dp4a_env = getenv("GGML_OPENCL_Q5_MOE_DP4A"); + const bool q5dp4a = q5dp4a_env ? (atoi(q5dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + if (q5dp4a && ne02 > 1 && (ne00 % 32 == 0)) { + size_t nb32 = (size_t)ne00 / 32; + size_t sc_elems = (size_t)ne02 * ne01 * nb32 * 2; + size_t mn_elems = (size_t)ne02 * ne01 * nb32; + extra->scale = clCreateBuffer(context, CL_MEM_READ_WRITE, sc_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); + extra->min = clCreateBuffer(context, CL_MEM_READ_WRITE, mn_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); + cl_kernel ek = backend_ctx->repack.kernel_moe_expand_scale_q5_0; + CL_CHECK(clSetKernelArg(ek, 0, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(ek, 1, sizeof(cl_mem), &extra->scale)); + CL_CHECK(clSetKernelArg(ek, 2, sizeof(cl_mem), &extra->min)); + CL_CHECK(clSetKernelArg(ek, 3, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(ek, 4, sizeof(int), &ne01)); + size_t eg[3] = { (size_t)(((ne01 + 63) / 64) * 64), nb32, (size_t)ne02 }; + size_t el[3] = { 64, 1, 1 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, ek, 3, NULL, eg, el, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + } + } + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_0_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + + int M = tensor->ne[1]; + int K = tensor->ne[0]; + GGML_ASSERT(K % 32 == 0); + + // Transpose qs as ushort + transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, K/4, M); + // Transpose qh as uchar + transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, K/8, M); + // Transpose d as ushort + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_0; + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64) * 64, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + return; + } + if (tensor->type == GGML_TYPE_Q5_1) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q5_1 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q5_1(); + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_m = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_qs = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(int32_t); + GGML_ASSERT(size_d + size_m + size_qs + size_qh == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); + + cl_buffer_region region; + + // The original tensor memory is divided into scales and quants, i.e., + // we first store scales, mins, then quants. + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for mins. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_m; + extra->m = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for qh. + region.origin = align_to(previous_origin + size_m, backend_ctx->alignment); + region.size = size_qh; + extra->qh = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for qs. + region.origin = align_to(previous_origin + size_qh, backend_ctx->alignment); + region.size = size_qs; + extra->qs = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno moe q5_1 kernel needs special transpose and unshuffling + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_1_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->m)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + // Create image for Q + cl_image_format img_format_qs = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_qs = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->qs } + }; + extra->qs_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_qs, &img_desc_qs, NULL, &err); + tensor->extra = extra; + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_1_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->m)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + + int M = tensor->ne[1]; + int K = tensor->ne[0]; + GGML_ASSERT(K % 32 == 0); + + // Transpose qs as ushort + transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, K/4, M); + // Transpose qh as uchar + transpose_2d_as_8b(backend_ctx, extra->qh, extra->qh, size_qh, K/8, M); + // Transpose d as ushort + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); + // Transpose m as ushort + transpose_2d_as_16b(backend_ctx, extra->m, extra->m, size_m, K/32, M); + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_1; + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->m)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64) * 64, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + return; + } + if (tensor->type == GGML_TYPE_MXFP4) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_mxfp4 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_mxfp4(); + + size_t size_e = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(char); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + GGML_ASSERT(size_e + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); + + // The original tensor memory is divided into scales and quants, i.e., + // we first store scales, then quants. + cl_buffer_region region; + + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_e; + extra->e = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for quants. + region.origin = align_to(previous_origin + size_e, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno moe mxfp4 kernel needs special transpose and unshuffling + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_mxfp4_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->e)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + tensor->extra = extra; + + // Create image for Q + cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_q = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->q } + }; + extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); + tensor->extra = extra; + + return; + } + +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_mxfp4; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->e)); + + size_t global_work_size[3] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[3] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + // Create image for Q + cl_image_format img_format_q = {CL_RG, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_q = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor)/32*2), + 0, 0, 0, 0, 0, 0, 0, + { extra->q } + }; + extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); + tensor->extra = extra; + + return; + } + if (tensor->type == GGML_TYPE_Q8_0) { + // Views share the parent's buffer; parent owns SoA conversion. + // A view of an AoS tensor (the KV cache, written by a state restore) + // is written in place. + if (tensor->view_src != nullptr || !ggml_is_contiguous(tensor)) { + if (!ggml_cl_is_q8_0_soa(tensor)) { + ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; + CL_CHECK(clEnqueueWriteBuffer( + queue, extra_aos->data_device, CL_TRUE, + extra_aos->offset + tensor->view_offs + offset, + size, data, 0, NULL, NULL)); + } + return; + } + + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q8_0 * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q8_0(); + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)*sizeof(char)); + GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); + + // The original tensor memory is divided into scales and quants, i.e., + // we first store scales, then quants. + cl_buffer_region region; + + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for quants. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q8_0; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + ctx->q8_0_soa_tensors.insert(tensor); + + // Generic dp4a MoE path (opt-in GGML_OPENCL_Q8_MOE_DP4A) +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + { + static const char * q8dp4a_env = getenv("GGML_OPENCL_Q8_MOE_DP4A"); + const bool q8dp4a = q8dp4a_env ? (atoi(q8dp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + if (q8dp4a && tensor->ne[2] > 1 && (tensor->ne[0] % 32 == 0)) { + int ne00 = (int)tensor->ne[0]; + int ne01 = (int)tensor->ne[1]; + int ne02 = (int)tensor->ne[2]; + size_t nb32 = (size_t)ne00 / 32; + size_t scale_elems = (size_t)ne02 * ne01 * nb32 * 2; // 2 per-16-seg scales / 32-block + extra->scale = clCreateBuffer(context, CL_MEM_READ_WRITE, scale_elems * sizeof(cl_half), NULL, &err); + CL_CHECK(err); + cl_kernel ek = backend_ctx->repack.kernel_moe_expand_scale_q8_0; + CL_CHECK(clSetKernelArg(ek, 0, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(ek, 1, sizeof(cl_mem), &extra->scale)); + CL_CHECK(clSetKernelArg(ek, 2, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(ek, 3, sizeof(int), &ne01)); + size_t eg[3] = { (size_t)(((ne01 + 63) / 64) * 64), nb32, (size_t)ne02 }; + size_t el[3] = { 64, 1, 1 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, ek, 3, NULL, eg, el, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + } + } +#endif + + // Transpose the weights and scales +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (enable_adreno_trans_weight(backend_ctx, tensor)) { + + int M = tensor->ne[1]; // ne01 + int K = tensor->ne[0]; // ne00 + + GGML_ASSERT(K % 32 == 0); + GGML_ASSERT(M % 4 == 0); + GGML_ASSERT(tensor->ne[2] == 1); + GGML_ASSERT(tensor->ne[3] == 1); + + transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/4, M); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); + } // end transpose +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + return; + } + if (tensor->type == GGML_TYPE_IQ4_NL) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq4_nl * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq4_nl(); + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)/2); + GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "set_tensor: temp upload buffer alloc failed"); + + cl_buffer_region region; + + // Create subbuffer for scales. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for quants. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + + #ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq4_nl; + if (use_adreno_kernels(backend_ctx, tensor)) { + kernel = backend_ctx->repack.kernel_convert_block_iq4_nl_noshuffle; + } + #else + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_iq4_nl; + #endif + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64)*64, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_kernels(backend_ctx, tensor)) { + int M = tensor->ne[1]; + int K = tensor->ne[0]; + GGML_ASSERT(K % 32 == 0); + + // Transpose q as ushort + transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); + // Transpose d as ushort + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/32, M); + } +#endif + return; + } + if (tensor->type == GGML_TYPE_IQ4_XS) { + GGML_ASSERT(offset == 0 && size == ggml_nbytes(tensor)); + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tensors in OpenCL backend should have been allocated and initialized"); + + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_iq4_xs * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_iq4_xs(); + extra->noshuffle = ggml_cl_iq4_xs_use_noshuffle(backend_ctx, tensor); + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + const size_t n_blk = ggml_nelements(tensor) / blck; + + const size_t size_qs = n_blk * 128; + const size_t size_sl = n_blk * 4; + const size_t size_sh = n_blk * 2; + const size_t size_d = n_blk * 2; + GGML_ASSERT(size_qs + size_sl + size_sh + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + CL_CHECK(clEnqueueWriteBuffer( + queue, data_device, CL_TRUE, 0, + ggml_nbytes(tensor), data, 0, NULL, NULL)); + + cl_buffer_region region; + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_qs; + CL_CHECK((extra->qs = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_qs, backend_ctx->alignment); + region.size = size_sl; + CL_CHECK((extra->sl = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sl, backend_ctx->alignment); + region.size = size_sh; + CL_CHECK((extra->sh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + region.origin = align_to(region.origin + size_sh, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = extra->noshuffle ? backend_ctx->repack.kernel_convert_block_iq4_xs_noshuffle : backend_ctx->repack.kernel_convert_block_iq4_xs; + cl_ulong nb_arg = (cl_ulong)n_blk; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->sl)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->sh)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_blk, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clReleaseMemObject(data_device)); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (extra->noshuffle) { + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_16b(backend_ctx, extra->qs, extra->qs, size_qs, k/4, m, true, true); + transpose_2d_as_32b(backend_ctx, extra->sl, extra->sl, size_sl, k/256, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->sh, extra->sh, size_sh, k/256, m, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, k/256, m, true, true); + } +#endif + + extra->size_qs = size_qs; + extra->size_sl = size_sl; + extra->size_sh = size_sh; + extra->size_d = size_d; + + tensor->extra = extra; + return; + } + + if (tensor->type == GGML_TYPE_Q4_K) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q4_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q4_K(); + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_dm = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(3 * ggml_blck_size(tensor->type) / 64); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + GGML_ASSERT(size_d + size_dm + size_s + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "q4_K set_tensor: temp upload buffer alloc failed"); + + cl_buffer_region region; + + // Create subbuffer for d. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for mins. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_dm; + extra->dm = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for s. + region.origin = align_to(previous_origin + size_dm, backend_ctx->alignment); + region.size = size_s; + extra->s = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for quants. + region.origin = align_to(previous_origin + size_s, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_k_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_q = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->q } + }; + extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); + CL_CHECK(err); + tensor->extra = extra; + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Tiled-wide convert for the long-vocab lm_head/embed (opt-in). The embed/ + // output q4_K weight (token_embd.weight, ne1=vocab) is NOT matched by + // use_adreno_moe_kernels, so it lands here in the general branch. Produce + // the final 64-row-tiled canonical layout directly into q/d/dm/s (buffer + // sizes already match), read back by kernel_gemv_noshuffle_q4_k_f32_tiled. + if (use_q4k_tiled(backend_ctx, tensor)) { + cl_kernel tk = backend_ctx->repack.kernel_convert_block_q4_k_tiled_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + + CL_CHECK(clSetKernelArg(tk, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(tk, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(tk, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(tk, 3, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(tk, 4, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(tk, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(tk, 6, sizeof(int), &ne01)); + + size_t gws[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t lws[] = {64, 1, 1}; + + cl_event tevt; + CL_CHECK(clEnqueueNDRangeKernel(queue, tk, 3, NULL, gws, lws, 0, NULL, &tevt)); + CL_CHECK(clWaitForEvents(1, &tevt)); + CL_CHECK(clReleaseMemObject(data_device)); + + extra->q_img = nullptr; + tensor->extra = extra; + return; + } + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_K; + if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor)) { + kernel = backend_ctx->repack.kernel_convert_block_q4_K_noshuffle; + } +#else + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q4_K; +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + tensor->extra = extra; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor)) { + + int M = tensor->ne[1]; + int K = tensor->ne[0]; + + GGML_ASSERT(K % 32 == 0); + + if (use_q4_k_bin_kernels(backend_ctx, tensor)) { + cl_int err; + cl_image_format wimg_fmt; + cl_image_desc wimg_desc; + + // transpose quants as 32-bit words (M-first) + GGML_ASSERT(M % 64 == 0); + transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/8, M); + + wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&wimg_desc, 0, sizeof(wimg_desc)); + wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + wimg_desc.image_width = (size_t)M * K / 8; + wimg_desc.buffer = extra->q; + CL_CHECK((extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); + } else { + // Transpose q as ushort + transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); + } + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/256, M); + transpose_2d_as_16b(backend_ctx, extra->dm, extra->dm, size_dm, K/256, M); + + // Transpose s as uchar + transpose_2d_as_8b(backend_ctx, extra->s, extra->s, size_s, K/256*12, M, true, true); + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + return; + } + if (tensor->type == GGML_TYPE_Q5_K) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q5_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q5_K(); + + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/8; + size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(3*ggml_blck_size(tensor->type)/64); + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_dm = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + GGML_ASSERT(size_q + size_qh + size_s + size_d + size_dm == ggml_nbytes(tensor) && + "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "q5_K set_tensor: temp upload buffer alloc failed"); + + cl_buffer_region region; + + // Create subbuffer for d. + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_d; + extra->d = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + auto previous_origin = region.origin; + + // Create subbuffer for dm. + region.origin = align_to(previous_origin + size_d, backend_ctx->alignment); + region.size = size_dm; + extra->dm = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for s. + region.origin = align_to(previous_origin + size_dm, backend_ctx->alignment); + region.size = size_s; + extra->s = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for q (lower 4 bits) + region.origin = align_to(previous_origin + size_s, backend_ctx->alignment); + region.size = size_q; + extra->q = clCreateSubBuffer( + extra_orig->data_device, CL_MEM_READ_WRITE, + CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err); + CL_CHECK(err); + previous_origin = region.origin; + + // Create subbuffer for qh (upper 1 bit) + region.origin = align_to(previous_origin + size_q, backend_ctx->alignment); + region.size = size_qh; + CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + CL_CHECK(err); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_k_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + cl_image_format img_format_q = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_q = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->q } + }; + extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_q, &img_desc_q, NULL, &err); + CL_CHECK(err); + tensor->extra = extra; + + // Generic dp4a MoE path + { + static const char * q5kdp4a_env = getenv("GGML_OPENCL_Q5K_MOE_DP4A"); + const bool q5kdp4a = q5kdp4a_env ? (atoi(q5kdp4a_env) != 0) + : (backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); + if (q5kdp4a && ne02 > 1 && (ne00 % 256 == 0)) { + size_t nb32 = (size_t)ne00 / 32; + size_t sc_elems = (size_t)ne02 * ne01 * nb32 * 2; + size_t mn_elems = (size_t)ne02 * ne01 * nb32; + extra->scale = clCreateBuffer(context, CL_MEM_READ_WRITE, sc_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); + extra->min = clCreateBuffer(context, CL_MEM_READ_WRITE, mn_elems * sizeof(cl_half), NULL, &err); CL_CHECK(err); + cl_kernel ek = backend_ctx->repack.kernel_moe_expand_scale_q5_K; + CL_CHECK(clSetKernelArg(ek, 0, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(ek, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(ek, 2, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(ek, 3, sizeof(cl_mem), &extra->scale)); + CL_CHECK(clSetKernelArg(ek, 4, sizeof(cl_mem), &extra->min)); + CL_CHECK(clSetKernelArg(ek, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(ek, 6, sizeof(int), &ne01)); + size_t eg[3] = { (size_t)(((ne01 + 63) / 64) * 64), (size_t)(ne00 / 256), (size_t)ne02 }; + size_t el[3] = { 64, 1, 1 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, ek, 3, NULL, eg, el, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + } + } + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_K; + if (enable_adreno_trans_weight_q5_K(backend_ctx, tensor)) { + kernel = backend_ctx->repack.kernel_convert_block_q5_K_noshuffle; + } +#else + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q5_K; +#endif + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + extra->size_q = size_q; + extra->size_qh = size_qh; + extra->size_s = size_s; + extra->size_d = size_d; + extra->size_dm = size_dm; + + tensor->extra = extra; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (enable_adreno_trans_weight_q5_K(backend_ctx, tensor)) { + + int M = tensor->ne[1]; + int K = tensor->ne[0]; + + GGML_ASSERT(K % 32 == 0); + + if (use_q5_k_bin_kernels(backend_ctx, tensor)) { + cl_int err; + cl_image_format wimg_fmt; + cl_image_desc wimg_desc; + + // transpose q as 32-bit words (M-first); qh/d/dm stay in their existing layout + // (both new ILA kernels read qh via the existing [K/8][M] uchar plane directly). + GGML_ASSERT(M % 64 == 0); + transpose_2d_as_32b(backend_ctx, extra->q, extra->q, size_q, K/8, M); + + wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; + memset(&wimg_desc, 0, sizeof(wimg_desc)); + wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + wimg_desc.image_width = (size_t)M * K / 8; + wimg_desc.buffer = extra->q; + CL_CHECK((extra->q_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); + + // Transpose s as uchar + transpose_2d_as_8b(backend_ctx, extra->s, extra->s, size_s, K/256*12, M, true, true); + } else { + // Transpose q as ushort + transpose_2d_as_16b(backend_ctx, extra->q, extra->q, size_q, K/4, M); + } + transpose_2d_as_8b (backend_ctx, extra->qh, extra->qh, size_qh, K/8, M); + transpose_2d_as_16b(backend_ctx, extra->d, extra->d, size_d, K/256, M); + transpose_2d_as_16b(backend_ctx, extra->dm, extra->dm, size_dm, K/256, M); + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + return; + } + if (tensor->type == GGML_TYPE_Q6_K) { + ggml_tensor_extra_cl * extra_orig = (ggml_tensor_extra_cl *)tensor->extra; + GGML_ASSERT(extra_orig && "Tesnors in OpenCL backend should have been allocated and initialized"); + + // Allocate the new extra and create aliases from the original. + ggml_backend_opencl_buffer_context * ctx = (ggml_backend_opencl_buffer_context *) buffer->context; + ggml_tensor_extra_cl_q6_K * extra = ctx->ggml_opencl_alloc_temp_tensor_extra_q6_K(); + + size_t size_ql = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/4; + size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/16; + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + GGML_ASSERT(size_ql + size_qh + size_s + size_d == ggml_nbytes(tensor) && + "Incorrect tensor size"); + + cl_int err; + cl_mem data_device = ggml_cl_create_temp_upload_buffer(context, queue, ggml_nbytes(tensor), data, tensor->name); + GGML_ASSERT(data_device != NULL && "q6_K set_tensor: temp upload buffer alloc failed"); + + cl_buffer_region region; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Adreno MoE Q6_K kernel needs special transposed layout + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + size_t moe_size_ql = (size_t)(ggml_nelements(tensor) / 8) * sizeof(uint32_t); // 4 bits per element + size_t moe_size_qh = (size_t)(ggml_nelements(tensor) / 16) * sizeof(uint32_t); // 2 bits per element + size_t moe_size_s = size_s; + size_t moe_size_d = size_d; + + // Subbuffer for ql + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = moe_size_ql; + CL_CHECK((extra->ql = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + auto previous_origin = region.origin; + + // Subbuffer for qh + region.origin = align_to(previous_origin + moe_size_ql, backend_ctx->alignment); + region.size = moe_size_qh; + CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + + // Subbuffer for scales + region.origin = align_to(previous_origin + moe_size_qh, backend_ctx->alignment); + region.size = moe_size_s; + CL_CHECK((extra->s = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + + // Subbuffer for d + region.origin = align_to(previous_origin + moe_size_s, backend_ctx->alignment); + region.size = moe_size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q6_k_trans4_ns; + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->ql)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + // Create image for ql + cl_image_format img_format_ql = {CL_R, CL_UNSIGNED_INT32}; + cl_image_desc img_desc_ql = { + CL_MEM_OBJECT_IMAGE1D_BUFFER, + static_cast(ggml_nelements(tensor) / 8), + 0, 0, 0, 0, 0, 0, 0, + { extra->ql } + }; + extra->ql_img = clCreateImage(context, CL_MEM_READ_ONLY, &img_format_ql, &img_desc_ql, NULL, &err); + tensor->extra = extra; + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + // Subbuffer for ql + region.origin = align_to(extra_orig->offset + tensor->view_offs + offset, backend_ctx->alignment); + region.size = size_ql; + CL_CHECK((extra->ql = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + auto previous_origin = region.origin; + + // Subbuffer for qh + region.origin = align_to(previous_origin + size_ql, backend_ctx->alignment); + region.size = size_qh; + CL_CHECK((extra->qh = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + + // Subbuffer for scales + region.origin = align_to(previous_origin + size_qh, backend_ctx->alignment); + region.size = size_s; + CL_CHECK((extra->s = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + + // Create subbuffer for d. + region.origin = align_to(previous_origin + size_s, backend_ctx->alignment); + region.size = size_d; + CL_CHECK((extra->d = clCreateSubBuffer(extra_orig->data_device, CL_MEM_READ_WRITE, CL_BUFFER_CREATE_TYPE_REGION, ®ion, &err), err)); + previous_origin = region.origin; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Tiled-wide convert for the long-vocab lm_head/embed (opt-in). The embed + // /output q6_K weight (e.g. token_embd.weight, ne1=vocab) is NOT matched by + // use_adreno_moe_kernels, so it lands here in the general branch. Produce + // the final 64-row-tiled canonical layout directly into ql/qh/s/d (buffer + // sizes already match), read back by kernel_gemv_noshuffle_q6_K_f32_tiled. + // Bypasses the plain-SOA convert + per-array transpose below. + if (use_q6k_tiled(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_convert_block_q6_k_tiled_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->ql)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(int), &ne01)); + + size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + extra->size_ql = size_ql; + extra->size_qh = size_qh; + extra->size_s = size_s; + extra->size_d = size_d; + tensor->extra = extra; + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + // Flatten the weights + cl_kernel kernel; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + kernel = backend_ctx->repack.kernel_convert_block_q6_K; + if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor)) { + kernel = backend_ctx->repack.kernel_convert_block_q6_K_noshuffle; + } +#else + kernel = backend_ctx->repack.kernel_convert_block_q6_K; +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + cl_uchar mask = 0xff; + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->ql)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)CEIL_DIV(n_blk, 64)*64, 1, 1}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + + extra->size_ql = size_ql; + extra->size_qh = size_qh; + extra->size_s = size_s; + extra->size_d = size_d; + + tensor->extra = extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor)) { + cl_int M = tensor->ne[1]; // ne01 + cl_int K = tensor->ne[0]; // ne00 + + if (use_q6_k_bin_kernels(backend_ctx, tensor)) { + GGML_ASSERT(K % 256 == 0); + GGML_ASSERT(M % 64 == 0); + + transpose_2d_as_32b(backend_ctx, extra->ql, extra->ql, size_ql, K/8, M); + transpose_2d_as_32b(backend_ctx, extra->qh, extra->qh, size_qh, K/16, M); + + cl_image_format wimg_fmt = { CL_R, CL_UNSIGNED_INT32 }; + cl_image_desc wimg_desc; + memset(&wimg_desc, 0, sizeof(wimg_desc)); + wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + wimg_desc.image_width = static_cast(ggml_nelements(tensor) / 8); + wimg_desc.buffer = extra->ql; + CL_CHECK((extra->ql_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); + + memset(&wimg_desc, 0, sizeof(wimg_desc)); + wimg_desc.image_type = CL_MEM_OBJECT_IMAGE1D_BUFFER; + wimg_desc.image_width = static_cast(ggml_nelements(tensor) / 16); + wimg_desc.buffer = extra->qh; + CL_CHECK((extra->qh_img = clCreateImage(context, CL_MEM_READ_ONLY, &wimg_fmt, &wimg_desc, NULL, &err), err)); + } else { + // Transpose ql as ushort + transpose_2d_as_16b(backend_ctx, + extra->ql, extra->ql, size_ql, K/4, M); + + // Transpose qh as uchar + transpose_2d_as_8b(backend_ctx, + extra->qh, extra->qh, size_qh, K/4, M); + + // Transpose s as ushort + transpose_2d_as_16b(backend_ctx, + extra->s, extra->s, size_s, K/16/2, M); + } + // Transpose d as ushort + transpose_2d_as_16b(backend_ctx, + extra->d, extra->d, size_d, K/256, M); + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + return; + } +#endif // GGML_OPENCL_SOA_Q + + // convert bf16 to f16 and store as f16 in device buffer + if (tensor->type == GGML_TYPE_BF16) { + GGML_ASSERT(offset % sizeof(ggml_fp16_t) == 0 && size % sizeof(ggml_fp16_t) == 0 + && "Offset and size must be multiples of 2 for bf16 tensors"); + + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; + GGML_ASSERT(extra); + + cl_ulong n_elements = size / sizeof(ggml_fp16_t); + cl_ulong off_dst = (extra->offset + tensor->view_offs + offset) / sizeof(ggml_fp16_t); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, + size, const_cast(data), &err); + CL_CHECK(err); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_bf16_to_f16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_ulong), &off_dst)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &n_elements)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_elements, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseMemObject(data_device)); + CL_CHECK(clReleaseEvent(evt)); + + return; + } + + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; + GGML_ASSERT(extra); + + // a view reuses its parent's extra, whose offset does not include view_offs + CL_CHECK(clEnqueueWriteBuffer( + queue, extra->data_device, CL_TRUE, extra->offset + tensor->view_offs + offset, + size, data, 0, NULL, NULL)); + + GGML_UNUSED(buffer); +} diff --git a/ggml/src/ggml-opencl/unpack.cpp b/ggml/src/ggml-opencl/unpack.cpp new file mode 100644 index 000000000000..cf76adc34f3b --- /dev/null +++ b/ggml/src/ggml-opencl/unpack.cpp @@ -0,0 +1,1795 @@ +#include "cl-common.h" + +void ggml_cl_load_kernels_unpack(ggml_backend_opencl_context * backend_ctx) { + cl_int err; + const std::string & compile_opts = backend_ctx->kernel_compile_opts; + GGML_UNUSED(backend_ctx); + GGML_UNUSED(err); + GGML_UNUSED(compile_opts); +} +static cl_mem ggml_cl_create_temp_download_buffer( + cl_context context, cl_command_queue queue, + size_t nbytes, const char * tensor_name_for_log) +{ + cl_int err; + cl_mem buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); + if (err != CL_SUCCESS) { + clFinish(queue); + buf = clCreateBuffer(context, CL_MEM_READ_WRITE, nbytes, NULL, &err); + } + if (err == CL_SUCCESS) { + return buf; + } + buf = clCreateBuffer(context, + CL_MEM_WRITE_ONLY | CL_MEM_ALLOC_HOST_PTR | CL_MEM_HOST_READ_ONLY, + nbytes, NULL, &err); + if (err != CL_SUCCESS) { + return NULL; + } + if (tensor_name_for_log) { + GGML_LOG_INFO("ggml_opencl: %s download (%.1f MiB) - device alloc failed, using CL_MEM_ALLOC_HOST_PTR fallback\n", + tensor_name_for_log, nbytes / 1024.0 / 1024.0); + } + return buf; +} + +void ggml_backend_opencl_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data, size_t offset, size_t size) { + GGML_ASSERT(tensor->extra); + + ggml_backend_opencl_device_context * dev_ctx = (ggml_backend_opencl_device_context *) buffer->buft->device->context; + ggml_backend_opencl_context *backend_ctx = dev_ctx->backend_ctx; + + cl_context context = backend_ctx->context; + cl_command_queue queue = backend_ctx->queue; + + // Make sure all previously submitted commands in other devices are finished. + sync_with_other_backends(backend_ctx); + +#ifdef GGML_OPENCL_SOA_Q + if (tensor->type == GGML_TYPE_Q2_K) { + ggml_tensor_extra_cl_q2_K * extra = (ggml_tensor_extra_cl_q2_K *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, sc = extra->sc, dm = extra->dm; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_sc, buf_dm; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + buf_sc.allocate(context, extra->size_sc); + buf_dm.allocate(context, extra->size_dm); + qs = buf_qs.buffer; + sc = buf_sc.buffer; + dm = buf_dm.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/16, true, true); + transpose_2d_as_32b(backend_ctx, extra->dm, dm, extra->size_dm, m, k/(int)blck, true, true); + } +#endif + cl_kernel kernel = extra->noshuffle ? backend_ctx->repack.kernel_restore_block_q2_k_noshuffle + : backend_ctx->repack.kernel_restore_block_q2_K; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_Q3_K) { + ggml_tensor_extra_cl_q3_K * extra = (ggml_tensor_extra_cl_q3_K *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, hm = extra->hm, sc = extra->sc, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_hm, buf_sc, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + buf_hm.allocate(context, extra->size_hm); + buf_sc.allocate(context, extra->size_sc); + buf_d.allocate(context, extra->size_d); + qs = buf_qs.buffer; + hm = buf_hm.buffer; + sc = buf_sc.buffer; + d = buf_d.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); + transpose_2d_as_8b(backend_ctx, extra->hm, hm, extra->size_hm, m, k/8, true, true); + transpose_2d_as_32b(backend_ctx, extra->sc, sc, extra->size_sc, m, 3*k/(int)blck, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); + } +#endif + cl_kernel kernel = extra->noshuffle ? backend_ctx->repack.kernel_restore_block_q3_k_noshuffle + : backend_ctx->repack.kernel_restore_block_q3_K; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &hm)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_IQ3_S) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq3_s * extra = (ggml_tensor_extra_cl_iq3_s *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, sg = extra->sg, qh = extra->qh, sc = extra->sc, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_sg, buf_qh, buf_sc, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + buf_sg.allocate(context, extra->size_sg); + buf_qh.allocate(context, extra->size_qh); + buf_sc.allocate(context, extra->size_sc); + buf_d.allocate(context, extra->size_d); + + qs = buf_qs.buffer; + sg = buf_sg.buffer; + qh = buf_qh.buffer; + sc = buf_sc.buffer; + d = buf_d.buffer; + + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); + transpose_2d_as_8b(backend_ctx, extra->sg, sg, extra->size_sg, m, k/8, true, true); + transpose_2d_as_8b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/32, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/64, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/256, true, true); + } +#endif + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq3_s; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_IQ3_XXS) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq3_xxs * extra = (ggml_tensor_extra_cl_iq3_xxs *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, sas = extra->sas, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_sas, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + buf_sas.allocate(context, extra->size_sas); + buf_d.allocate(context, extra->size_d); + + qs = buf_qs.buffer; + sas = buf_sas.buffer; + d = buf_d.buffer; + + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); + transpose_2d_as_32b(backend_ctx, extra->sas, sas, extra->size_sas, m, k/32, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/256, true, true); + } +#endif + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq3_xxs; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_IQ1_M) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq1_m * extra = (ggml_tensor_extra_cl_iq1_m *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, qh = extra->qh, sc = extra->sc; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_qh, buf_sc; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + qs = buf_qs.buffer; + buf_qh.allocate(context, extra->size_qh); + qh = buf_qh.buffer; + buf_sc.allocate(context, extra->size_sc); + sc = buf_sc.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); + transpose_2d_as_8b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/16, true, true); + transpose_2d_as_16b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/64, true, true); + } +#endif + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq1_m; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &sc)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_IQ1_S) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq1_s * extra = (ggml_tensor_extra_cl_iq1_s *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, qh = extra->qh, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_qh, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + qs = buf_qs.buffer; + buf_qh.allocate(context, extra->size_qh); + qh = buf_qh.buffer; + buf_d.allocate(context, extra->size_d); + d = buf_d.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); + transpose_2d_as_16b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/32, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); + } +#endif + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq1_s; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_IQ2_S) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq2_s * extra = (ggml_tensor_extra_cl_iq2_s *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, sg = extra->sg, qh = extra->qh, sc = extra->sc, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_sg, buf_qh, buf_sc, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + qs = buf_qs.buffer; + buf_sg.allocate(context, extra->size_sg); + sg = buf_sg.buffer; + buf_qh.allocate(context, extra->size_qh); + qh = buf_qh.buffer; + buf_sc.allocate(context, extra->size_sc); + sc = buf_sc.buffer; + buf_d.allocate(context, extra->size_d); + d = buf_d.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); + transpose_2d_as_8b(backend_ctx, extra->sg, sg, extra->size_sg, m, k/8, true, true); + transpose_2d_as_8b(backend_ctx, extra->qh, qh, extra->size_qh, m, k/32, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/32, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); + } +#endif + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq2_s; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sg)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &qh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &sc)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_IQ2_XS) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq2_xs * extra = (ggml_tensor_extra_cl_iq2_xs *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, sc = extra->sc, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_sc, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + qs = buf_qs.buffer; + buf_sc.allocate(context, extra->size_sc); + sc = buf_sc.buffer; + buf_d.allocate(context, extra->size_d); + d = buf_d.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_16b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); + transpose_2d_as_8b(backend_ctx, extra->sc, sc, extra->size_sc, m, k/32, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); + } +#endif + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq2_xs; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sc)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_IQ2_XXS) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq2_xxs * extra = (ggml_tensor_extra_cl_iq2_xxs *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, sas = extra->sas, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_sas, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + qs = buf_qs.buffer; + buf_sas.allocate(context, extra->size_sas); + sas = buf_sas.buffer; + buf_d.allocate(context, extra->size_d); + d = buf_d.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/8, true, true); + transpose_2d_as_32b(backend_ctx, extra->sas, sas, extra->size_sas, m, k/32, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/(int)blck, true, true); + } +#endif + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq2_xxs; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sas)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_Q1_0) { + ggml_tensor_extra_cl_q1_0 * extra = (ggml_tensor_extra_cl_q1_0 *)tensor->extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (enable_adreno_trans_weight(backend_ctx, tensor)) { + ggml_cl_buffer buf_trans_q; + ggml_cl_buffer buf_trans_d; + ggml_cl_buffer buf_unpacked; + + int M = tensor->ne[1]; + int K = tensor->ne[0]; + + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*(ggml_blck_size(tensor->type)/8); + + buf_trans_q.allocate(backend_ctx->context, size_q); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/32); + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/128); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q1_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } +#endif + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q1_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer(queue, data_device, CL_TRUE, offset, size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + + if (tensor->type == GGML_TYPE_Q2_0) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_q2_0 * extra = (ggml_tensor_extra_cl_q2_0 *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + qs = buf_qs.buffer; + buf_d.allocate(context, extra->size_d); + d = buf_d.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_8b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/64, true, true); + } +#endif + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q2_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + // In end-to-end runs, get_tensor is usually used to get back the logits, + // where we can simply do clEnqueueReadBuffer since they are f32. + // However, in test-backend-ops, the GPU graph is copied to the CPU backend, + // which requires reading back quantized weight tensors. + // To properly support this, we need to restore block_q4_0 struct arrays + // from the flattened buffers. + if (tensor->type == GGML_TYPE_Q4_0) { + // KV-cache q4_0 stays AoS — direct readback, no SoA restore. + if (!ggml_cl_is_q4_0_soa(tensor)) { + ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; + CL_CHECK(clEnqueueReadBuffer( + queue, extra_aos->data_device, CL_TRUE, + extra_aos->offset + tensor->view_offs + offset, + size, data, 0, NULL, NULL)); + return; + } + // SoA extra lives on the parent tensor — follow view_src. + const ggml_tensor * extra_src = tensor->view_src != nullptr ? tensor->view_src : tensor; + ggml_tensor_extra_cl_q4_0 * extra = (ggml_tensor_extra_cl_q4_0 *)extra_src->extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_0_trans4_ns; + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (use_adreno_kernels(backend_ctx, tensor)) { + ggml_cl_buffer buf_trans_q; + ggml_cl_buffer buf_trans_d; + ggml_cl_buffer buf_unpacked; + + cl_int M = tensor->ne[1]; // ne01 + cl_int K = tensor->ne[0]; // ne00 + + GGML_ASSERT(K % 32 == 0); + GGML_ASSERT(M % 4 == 0); + + size_t size_q = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; + size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); + GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + buf_trans_q.allocate(backend_ctx->context, size_q); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + if (use_q4_0_bin_kernels(backend_ctx, tensor)) { + transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K / 8); + } else { + transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K / 4); + } + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_0_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); + + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } +#endif + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_Q4_1) { + ggml_tensor_extra_cl_q4_1 * extra = (ggml_tensor_extra_cl_q4_1 *)tensor->extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_1_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->m)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (use_adreno_kernels(backend_ctx, tensor)) { + static ggml_cl_buffer buf_trans_q; + static ggml_cl_buffer buf_trans_m; + static ggml_cl_buffer buf_trans_d; + static ggml_cl_buffer buf_unpacked; + + cl_int M = tensor->ne[1]; + cl_int K = tensor->ne[0]; + + GGML_ASSERT(K % ggml_blck_size(tensor->type) == 0); + + size_t size_q = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; + size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); + size_t size_m = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); + GGML_ASSERT(size_d + size_q + size_m == ggml_nbytes(tensor) && "Incorrect tensor size"); + + buf_trans_q.allocate(backend_ctx->context, size_q); + buf_trans_m.allocate(backend_ctx->context, size_m); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + // transpose q, d, m back + transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); + transpose_2d_as_16b(backend_ctx, extra->m, buf_trans_m.buffer, size_m, M, K/32); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_1_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_m.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_F0)); + + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } +#endif + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_1; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->m)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_Q5_0) { + ggml_tensor_extra_cl_q5_0 * extra = (ggml_tensor_extra_cl_q5_0 *)tensor->extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + // TODO: use ggml_cl_buffer to manage this temporary buffer + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_0_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (use_adreno_kernels(backend_ctx, tensor)) { + ggml_cl_buffer buf_trans_qs; + ggml_cl_buffer buf_trans_qh; + ggml_cl_buffer buf_trans_d; + ggml_cl_buffer buf_unpacked; + + cl_int M = tensor->ne[1]; + cl_int K = tensor->ne[0]; + + GGML_ASSERT(K % 32 == 0); + + size_t size_qs = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; + size_t size_qh = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(int32_t); + size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); + + buf_trans_qs.allocate(backend_ctx->context, size_qs); + buf_trans_qh.allocate(backend_ctx->context, size_qh); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + transpose_2d_as_16b(backend_ctx, extra->qs, buf_trans_qs.buffer, size_qs, M, K/4); + transpose_2d_as_8b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/8); + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_0_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_qs.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_F0)); + + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &data_device)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_Q5_1) { + ggml_tensor_extra_cl_q5_1 * extra = (ggml_tensor_extra_cl_q5_1 *)tensor->extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + // TODO: use ggml_cl_buffer to manage this temporary buffer + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_1_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + + if (use_adreno_kernels(backend_ctx, tensor)) { + ggml_cl_buffer buf_trans_qs; + ggml_cl_buffer buf_trans_qh; + ggml_cl_buffer buf_trans_d; + ggml_cl_buffer buf_trans_m; + ggml_cl_buffer buf_unpacked; + + cl_int M = tensor->ne[1]; + cl_int K = tensor->ne[0]; + GGML_ASSERT(K % 32 == 0); + + size_t size_qs = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*ggml_blck_size(tensor->type)/2; + size_t size_qh = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(int32_t); + size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); + size_t size_m = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); + + buf_trans_qs.allocate(backend_ctx->context, size_qs); + buf_trans_qh.allocate(backend_ctx->context, size_qh); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_trans_m.allocate(backend_ctx->context, size_m); + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + // Transpose back: from col-major to row-major + transpose_2d_as_16b(backend_ctx, extra->qs, buf_trans_qs.buffer, size_qs, M, K/4); + transpose_2d_as_8b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/8); + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); + transpose_2d_as_16b(backend_ctx, extra->m, buf_trans_m.buffer, size_m, M, K/32); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_1_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_qs.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_m.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); + + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, + ggml_nbytes(tensor), NULL, &err); + CL_CHECK(err); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_1; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->m)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_MXFP4) { + ggml_tensor_extra_cl_mxfp4 * extra = (ggml_tensor_extra_cl_mxfp4 *)tensor->extra; + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_mxfp4_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->e)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 32), static_cast(ne02)}; + size_t local_work_size[3] = {64, 2, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_mxfp4; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->e)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_Q8_0) { + // KV-cache q8_0 stays AoS (see Q4_0 branch). + if (!ggml_cl_is_q8_0_soa(tensor)) { + ggml_tensor_extra_cl * extra_aos = (ggml_tensor_extra_cl *) tensor->extra; + CL_CHECK(clEnqueueReadBuffer( + queue, extra_aos->data_device, CL_TRUE, + extra_aos->offset + tensor->view_offs + offset, + size, data, 0, NULL, NULL)); + return; + } + // SoA extra lives on the parent — follow view_src. + const ggml_tensor * extra_src = tensor->view_src != nullptr ? tensor->view_src : tensor; + ggml_tensor_extra_cl_q8_0 * extra = (ggml_tensor_extra_cl_q8_0 *)extra_src->extra; + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (enable_adreno_trans_weight(backend_ctx, tensor)) { + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q8_0_trans; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + GGML_ASSERT(tensor->ne[2] == 1); + GGML_ASSERT(tensor->ne[3] == 1); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_int), &ne01)); + + size_t global_work_size[3] = {static_cast(((ne01 + 63) / 64) * 64), 1, 1}; + size_t local_work_size[3] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } +#endif + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q8_0; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_IQ4_NL) { + ggml_tensor_extra_cl_iq4_nl * extra = (ggml_tensor_extra_cl_iq4_nl *)tensor->extra; + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_kernels(backend_ctx, tensor)) { + static ggml_cl_buffer buf_trans_q; + static ggml_cl_buffer buf_trans_d; + static ggml_cl_buffer buf_unpacked; + + cl_int M = tensor->ne[1]; + cl_int K = tensor->ne[0]; + GGML_ASSERT(K % 32 == 0); + + size_t size_q = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*(ggml_blck_size(tensor->type)/2); + size_t size_d = (ggml_nelements(tensor)/ggml_blck_size(tensor->type))*sizeof(ggml_fp16_t); + GGML_ASSERT(size_d + size_q == ggml_nbytes(tensor) && "Incorrect tensor size"); + + buf_trans_q.allocate(backend_ctx->context, size_q); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + // transpose q, d back + transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/32); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq4_nl_noshuffle; + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_uchar), &mask_F0)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)n_blk, 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } +#endif + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_iq4_nl; + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)n_blk, 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_IQ4_XS) { + if (tensor->view_src) { + offset += tensor->view_offs; + tensor = tensor->view_src; + } + ggml_tensor_extra_cl_iq4_xs * extra = (ggml_tensor_extra_cl_iq4_xs *)tensor->extra; + + const size_t blck = (size_t)ggml_blck_size(tensor->type); + + ggml_cl_buffer buf_unpacked; + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + const size_t n_blk = (size_t)ggml_nelements(tensor) / blck; + cl_ulong nb_arg = (cl_ulong)n_blk; + + cl_mem qs = extra->qs, sl = extra->sl, sh = extra->sh, d = extra->d; +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + ggml_cl_buffer buf_qs, buf_sl, buf_sh, buf_d; + if (extra->noshuffle) { + buf_qs.allocate(context, extra->size_qs); + buf_sl.allocate(context, extra->size_sl); + buf_sh.allocate(context, extra->size_sh); + buf_d.allocate(context, extra->size_d); + + qs = buf_qs.buffer; + sl = buf_sl.buffer; + sh = buf_sh.buffer; + d = buf_d.buffer; + const int m = tensor->ne[1]; + const int k = tensor->ne[0]; + transpose_2d_as_16b(backend_ctx, extra->qs, qs, extra->size_qs, m, k/4, true, true); + transpose_2d_as_32b(backend_ctx, extra->sl, sl, extra->size_sl, m, k/256, true, true); + transpose_2d_as_16b(backend_ctx, extra->sh, sh, extra->size_sh, m, k/256, true, true); + transpose_2d_as_16b(backend_ctx, extra->d, d, extra->size_d, m, k/256, true, true); + } +#endif + + cl_kernel kernel = extra->noshuffle ? backend_ctx->repack.kernel_restore_block_iq4_xs_noshuffle : backend_ctx->repack.kernel_restore_block_iq4_xs; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &qs)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &sl)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &sh)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &nb_arg)); + + size_t gws[] = { (n_blk + 63) / 64 * 64 }; + size_t lws[] = { 64 }; + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 1, NULL, gws, lws, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + return; + } + + if (tensor->type == GGML_TYPE_Q4_K) { + ggml_tensor_extra_cl_q4_K * extra = (ggml_tensor_extra_cl_q4_K *)tensor->extra; + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Undo the 64-row-tiled canonical pack (kernel_convert_block_q4_k_tiled_ns). + // Without this, a read-back of a tiled weight returns the tiled bytes + // reinterpreted as block_q4_K -- which is how test-backend-ops builds its + // CPU reference (ggml_backend_graph_copy -> tensor_get), so the tiled path + // "failed" the suite while computing the correct product. + if (use_q4k_tiled(backend_ctx, tensor)) { + const int ne00v = tensor->ne[0]; + const int ne01v = tensor->ne[1]; + const int nbv = ne00v / 256; + const size_t n_blk = (size_t)nbv * ne01v; + + std::vector tq(n_blk*32); + std::vector td(n_blk), tdm(n_blk); + std::vector ts(n_blk*12); + CL_CHECK(clEnqueueReadBuffer(queue, extra->q, CL_TRUE, 0, tq.size()*4, tq.data(), 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->d, CL_TRUE, 0, td.size()*2, td.data(), 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->dm, CL_TRUE, 0, tdm.size()*2, tdm.data(), 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->s, CL_TRUE, 0, ts.size(), ts.data(), 0, NULL, NULL)); + + std::vector rebuilt(ggml_nbytes(tensor), 0); + for (int i01 = 0; i01 < ne01v; ++i01) { + const int rt = i01/64, rit = i01%64; + for (int i00 = 0; i00 < nbv; ++i00) { + uint8_t * b = rebuilt.data() + ((size_t)i00 + (size_t)i01*nbv)*144; + const int tb = rt*nbv + i00; + const size_t si = (size_t)tb*64 + rit; + + memcpy(b + 0, &td [si], 2); + memcpy(b + 2, &tdm[si], 2); + memcpy(b + 4, &ts[si*12], 12); + + uint32_t qw[32]; + for (int gr = 0; gr < 8; ++gr) { + const size_t base = ((size_t)tb*8 + gr)*64 + rit; + for (int j = 0; j < 4; ++j) qw[gr*4 + j] = tq[base*4 + j]; + } + uint8_t * q = b + 16; + for (int e = 0; e < 256; ++e) { + const int g = e>>6, w = e&63, h = w>>5, l = w&31; + const uint32_t code = (qw[e>>3] >> ((e&7)*4)) & 0xF; + q[g*32 + l] |= (uint8_t)(h ? (code << 4) : code); + } + } + } + memcpy(data, rebuilt.data() + offset, size); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_k_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q4_K(backend_ctx, tensor)) { + int M = tensor->ne[1]; + int K = tensor->ne[0]; + + size_t size_q = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_dm = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*12; + + static ggml_cl_buffer buf_trans_q; + static ggml_cl_buffer buf_trans_d; + static ggml_cl_buffer buf_trans_dm; + static ggml_cl_buffer buf_trans_s; + + buf_trans_q.allocate(backend_ctx->context, size_q); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_trans_dm.allocate(backend_ctx->context, size_dm); + buf_trans_s.allocate(backend_ctx->context, size_s); + + // Transpose q, d, dm, s back + if (use_q4_k_bin_kernels(backend_ctx, tensor)) { + transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/8); + } else { + transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); + } + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/256); + transpose_2d_as_16b(backend_ctx, extra->dm, buf_trans_dm.buffer, size_dm, M, K/256); + transpose_2d_as_8b (backend_ctx, extra->s, buf_trans_s.buffer, size_s, M, K/256*12, true, true); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_K_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_s.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_dm.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q4_K; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_Q5_K) { + ggml_tensor_extra_cl_q5_K * extra = (ggml_tensor_extra_cl_q5_K *)tensor->extra; + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_k_trans4_ns; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (enable_adreno_trans_weight_q5_K(backend_ctx, tensor)) { + int M = tensor->ne[1]; + int K = tensor->ne[0]; + + size_t size_q = extra->size_q; + size_t size_qh = extra->size_qh; + size_t size_s = extra->size_s; + size_t size_d = extra->size_d; + size_t size_dm = extra->size_dm; + + static ggml_cl_buffer buf_trans_q; + static ggml_cl_buffer buf_trans_qh; + static ggml_cl_buffer buf_trans_s; + static ggml_cl_buffer buf_trans_d; + static ggml_cl_buffer buf_trans_dm; + + buf_trans_q.allocate(backend_ctx->context, size_q); + buf_trans_qh.allocate(backend_ctx->context, size_qh); + buf_trans_s.allocate(backend_ctx->context, size_s); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_trans_dm.allocate(backend_ctx->context, size_dm); + + // bin kernel transposes s but src kernel does not + cl_mem buf_s = extra->s; + + if (use_q5_k_bin_kernels(backend_ctx, tensor)) { + transpose_2d_as_32b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/8); + transpose_2d_as_8b (backend_ctx, extra->s, buf_trans_s.buffer, size_s, M, K/256*12, true, true); + buf_s = buf_trans_s.buffer; + } else { + transpose_2d_as_16b(backend_ctx, extra->q, buf_trans_q.buffer, size_q, M, K/4); + } + transpose_2d_as_8b (backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/8); + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/256); + transpose_2d_as_16b(backend_ctx, extra->dm, buf_trans_dm.buffer, size_dm, M, K/256); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_K_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_q.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &buf_s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_trans_dm.buffer)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q5_K; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->q)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &extra->dm)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {(size_t)ggml_nelements(tensor)/ggml_blck_size(tensor->type), 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (tensor->type == GGML_TYPE_Q6_K) { + ggml_tensor_extra_cl_q6_K * extra = (ggml_tensor_extra_cl_q6_K *)tensor->extra; + +#ifdef GGML_OPENCL_USE_ADRENO_KERNELS + // Undo the 64-row-tiled canonical pack (kernel_convert_block_q6_k_tiled_ns). + // See the q4_K tiled restore above for why a read-back path is required. + if (use_q6k_tiled(backend_ctx, tensor)) { + const int ne00v = tensor->ne[0]; + const int ne01v = tensor->ne[1]; + const int nbv = ne00v / 256; + const size_t n_blk = (size_t)nbv * ne01v; + + std::vector tql(n_blk*32), tqh(n_blk*16); + std::vector ts(n_blk*16); + std::vector td(n_blk); + CL_CHECK(clEnqueueReadBuffer(queue, extra->ql, CL_TRUE, 0, tql.size()*4, tql.data(), 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->qh, CL_TRUE, 0, tqh.size()*4, tqh.data(), 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->s, CL_TRUE, 0, ts.size(), ts.data(), 0, NULL, NULL)); + CL_CHECK(clEnqueueReadBuffer(queue, extra->d, CL_TRUE, 0, td.size()*2, td.data(), 0, NULL, NULL)); + + std::vector rebuilt(ggml_nbytes(tensor), 0); + for (int i01 = 0; i01 < ne01v; ++i01) { + const int rt = i01/64, rit = i01%64; + for (int i00 = 0; i00 < nbv; ++i00) { + uint8_t * b = rebuilt.data() + ((size_t)i00 + (size_t)i01*nbv)*210; + const int tb = rt*nbv + i00; + const size_t si = (size_t)tb*64 + rit; + + uint32_t qlw[32], qhw[16]; + for (int g = 0; g < 8; ++g) { + const size_t base = ((size_t)tb*8 + g)*64 + rit; + for (int j = 0; j < 4; ++j) qlw[g*4 + j] = tql[base*4 + j]; + } + for (int g = 0; g < 4; ++g) { + const size_t base = ((size_t)tb*4 + g)*64 + rit; + for (int j = 0; j < 4; ++j) qhw[g*4 + j] = tqh[base*4 + j]; + } + + uint8_t * ql = b; + uint8_t * qh = b + 128; + for (int e = 0; e < 256; ++e) { + const int n = (e >= 128) ? 1 : 0; + const int within = e - n*128, q = within/32, l = within%32; + const int off_ql = n*64, off_qh = n*32; + const uint8_t low4 = (qlw[e>>3] >> ((e&7)*4)) & 0xF; + const uint8_t hi2 = (qhw[e>>4] >> ((e&15)*2)) & 0x3; + if (q == 0) ql[off_ql + l] |= low4; + else if (q == 1) ql[off_ql + l + 32] |= low4; + else if (q == 2) ql[off_ql + l] |= (uint8_t)(low4 << 4); + else ql[off_ql + l + 32] |= (uint8_t)(low4 << 4); + qh[off_qh + l] |= (uint8_t)(hi2 << (q*2)); + } + memcpy(b + 192, &ts[si*16], 16); + memcpy(b + 208, &td[si], 2); + } + } + memcpy(data, rebuilt.data() + offset, size); + return; + } + if (use_adreno_moe_kernels(backend_ctx, tensor)) { + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q6_k_trans4_ns; + + cl_uchar mask_0F = 0x0F; + cl_uchar mask_F0 = 0xF0; + + int ne00 = tensor->ne[0]; + int ne01 = tensor->ne[1]; + int ne02 = tensor->ne[2]; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->ql)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_int), &ne00)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_int), &ne01)); + CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_uchar), &mask_0F)); + CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_uchar), &mask_F0)); + + size_t global_work_size[] = {static_cast(((ne01 + 63) / 64) * 64), static_cast(ne00 / 256), static_cast(ne02)}; + size_t local_work_size[] = {64, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } + if (use_adreno_kernels(backend_ctx, tensor) && !use_flat_gemv_for_large_m_q6_K(backend_ctx, tensor)) { + static ggml_cl_buffer buf_trans_ql; + static ggml_cl_buffer buf_trans_qh; + static ggml_cl_buffer buf_trans_s; + static ggml_cl_buffer buf_trans_d; + static ggml_cl_buffer buf_unpacked; + + cl_int M = tensor->ne[1]; // ne01 + cl_int K = tensor->ne[0]; // ne00 + + GGML_ASSERT(K % ggml_blck_size(tensor->type) == 0); + + size_t size_ql = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/2; + size_t size_qh = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/4; + size_t size_s = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*ggml_blck_size(tensor->type)/16; + size_t size_d = ggml_nelements(tensor)/ggml_blck_size(tensor->type)*sizeof(ggml_fp16_t); + GGML_ASSERT(size_ql + size_qh + size_s + size_d == ggml_nbytes(tensor) && "Incorrect tensor size"); + + buf_trans_ql.allocate(backend_ctx->context, size_ql); + buf_trans_qh.allocate(backend_ctx->context, size_qh); + buf_trans_d.allocate(backend_ctx->context, size_d); + buf_unpacked.allocate(backend_ctx->context, ggml_nbytes(tensor)); + + cl_mem s_buffer; + if (use_q6_k_bin_kernels(backend_ctx, tensor)) { + transpose_2d_as_32b(backend_ctx, extra->ql, buf_trans_ql.buffer, size_ql, M, K/8); + transpose_2d_as_32b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/16); + // s is left row-major, untransposed, for the binary layout. + s_buffer = extra->s; + } else { + // transpose ql, qh, s and d back + buf_trans_s.allocate(backend_ctx->context, size_s); + transpose_2d_as_16b(backend_ctx, extra->ql, buf_trans_ql.buffer, size_ql, M, K/4); + transpose_2d_as_8b(backend_ctx, extra->qh, buf_trans_qh.buffer, size_qh, M, K/4); + transpose_2d_as_16b(backend_ctx, extra->s, buf_trans_s.buffer, size_s, M, K/16/2); + s_buffer = buf_trans_s.buffer; + } + transpose_2d_as_16b(backend_ctx, extra->d, buf_trans_d.buffer, size_d, M, K/256); + + // unpack + cl_uchar mask = 0xFF; + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q6_K_noshuffle; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &buf_trans_ql.buffer)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &buf_trans_qh.buffer)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &s_buffer)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &buf_trans_d.buffer)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &buf_unpacked.buffer)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)n_blk, 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer(queue, buf_unpacked.buffer, CL_TRUE, offset, size, data, 0, NULL, NULL)); + + return; + } +#endif // GGML_OPENCL_USE_ADRENO_KERNELS + + cl_mem data_device = ggml_cl_create_temp_download_buffer(context, queue, ggml_nbytes(tensor), tensor->name); + GGML_ASSERT(data_device != NULL && "get_tensor: temp download buffer alloc failed"); + + cl_uchar mask = 0xFF; + cl_ulong n_blk = ggml_nelements(tensor)/ggml_blck_size(tensor->type); + cl_kernel kernel = backend_ctx->repack.kernel_restore_block_q6_K; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->ql)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_mem), &extra->qh)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &extra->s)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_mem), &extra->d)); + CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_uchar), &mask)); + CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_ulong), &n_blk)); + + size_t global_work_size[] = {(size_t)n_blk, 1, 1}; + size_t local_work_size[] = {1, 1, 1}; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, + global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, offset, + size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + return; + } +#endif // GGML_OPENCL_SOA_Q + + if (tensor->type == GGML_TYPE_BF16) { + GGML_ASSERT(offset % sizeof(ggml_fp16_t) == 0 && size % sizeof(ggml_fp16_t) == 0 + && "Offset and size must be multiples of 2 for bf16 tensors"); + + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; + GGML_ASSERT(extra); + + cl_ulong n_elements = size / sizeof(ggml_fp16_t); + cl_ulong off_src = (extra->offset + tensor->view_offs + offset) / sizeof(ggml_fp16_t); + + cl_int err; + cl_mem data_device = clCreateBuffer(context, CL_MEM_READ_WRITE, size, NULL, &err); + CL_CHECK(err); + + cl_kernel kernel = backend_ctx->repack.kernel_convert_f16_to_bf16; + CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &extra->data_device)); + CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &off_src)); + CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &data_device)); + CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &n_elements)); + + size_t global_work_size[] = { (size_t)CEIL_DIV(n_elements, 64)*64, 1, 1 }; + size_t local_work_size[] = { 64, 1, 1 }; + + cl_event evt; + CL_CHECK(clEnqueueNDRangeKernel(queue, kernel, 3, NULL, global_work_size, local_work_size, 0, NULL, &evt)); + CL_CHECK(clWaitForEvents(1, &evt)); + CL_CHECK(clReleaseEvent(evt)); + + CL_CHECK(clEnqueueReadBuffer( + queue, data_device, CL_TRUE, 0, size, data, 0, NULL, NULL)); + CL_CHECK(clReleaseMemObject(data_device)); + + return; + } + + ggml_tensor_extra_cl * extra = (ggml_tensor_extra_cl *) tensor->extra; + + CL_CHECK(clEnqueueReadBuffer( + queue, extra->data_device, CL_TRUE, extra->offset + tensor->view_offs + offset, + size, data, 0, NULL, NULL)); + + GGML_UNUSED(buffer); +} From c59af87cb91392d754ec61674829e3cd2644682c Mon Sep 17 00:00:00 2001 From: leejet Date: Fri, 4 Dec 2026 16:52:08 +0800 Subject: [PATCH 384/401] cuda : batch contiguous concat slices in one launch (#33463) * cuda : batch contiguous concat slices in one launch * add concat test case --- ggml/src/ggml-cuda/concat.cu | 121 +++++++++++++++++++---------------- tests/test-backend-ops.cpp | 9 +++ 2 files changed, 75 insertions(+), 55 deletions(-) diff --git a/ggml/src/ggml-cuda/concat.cu b/ggml/src/ggml-cuda/concat.cu index 7391f99f89e8..ea15eba03ecb 100644 --- a/ggml/src/ggml-cuda/concat.cu +++ b/ggml/src/ggml-cuda/concat.cu @@ -12,71 +12,93 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE) concat_cont(con int64_t ne02, int64_t ne0, int64_t ne1, - int64_t ne2) { + int64_t ne2, + int64_t ne3, + size_t stride_x, + size_t stride_y, + size_t stride_dst) { static_assert(dim >= 0 && dim <= 2, "dim must be in [0, 2]"); const int64_t n = ne0 * ne1 * ne2; ggml_cuda_pdl_sync(); - for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) blockDim.x * gridDim.x) { - if constexpr (dim == 0) { - const int64_t row = i / ne0; - const int64_t i0 = i - row * ne0; + for (int64_t i3 = blockIdx.y; i3 < ne3; i3 += gridDim.y) { + const T * x_slice = x + i3 * stride_x; + const T * y_slice = y + i3 * stride_y; + T * dst_slice = dst + i3 * stride_dst; - if (i0 < ne00) { - dst[i] = x[row * ne00 + i0]; - } else { - dst[i] = y[row * (ne0 - ne00) + (i0 - ne00)]; - } - } else if constexpr (dim == 1) { - const int64_t dst_plane = ne0 * ne1; - const int64_t src0_plane = ne0 * ne01; - const int64_t src1_plane = dst_plane - src0_plane; - const int64_t i2 = i / dst_plane; - const int64_t i01 = i - i2 * dst_plane; + for (int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x; i < n; i += (int64_t) blockDim.x * gridDim.x) { + if constexpr (dim == 0) { + const int64_t row = i / ne0; + const int64_t i0 = i - row * ne0; - if (i01 < src0_plane) { - dst[i] = x[i2 * src0_plane + i01]; - } else { - dst[i] = y[i2 * src1_plane + (i01 - src0_plane)]; - } - } else { - const int64_t src0_size = ne0 * ne1 * ne02; + if (i0 < ne00) { + dst_slice[i] = x_slice[row * ne00 + i0]; + } else { + dst_slice[i] = y_slice[row * (ne0 - ne00) + (i0 - ne00)]; + } + } else if constexpr (dim == 1) { + const int64_t dst_plane = ne0 * ne1; + const int64_t src0_plane = ne0 * ne01; + const int64_t src1_plane = dst_plane - src0_plane; + const int64_t i2 = i / dst_plane; + const int64_t i01 = i - i2 * dst_plane; - if (i < src0_size) { - dst[i] = x[i]; + if (i01 < src0_plane) { + dst_slice[i] = x_slice[i2 * src0_plane + i01]; + } else { + dst_slice[i] = y_slice[i2 * src1_plane + (i01 - src0_plane)]; + } } else { - dst[i] = y[i - src0_size]; + const int64_t src0_size = ne0 * ne1 * ne02; + + if (i < src0_size) { + dst_slice[i] = x_slice[i]; + } else { + dst_slice[i] = y_slice[i - src0_size]; + } } } } } template -static void concat_cont_cuda(const T * x, - const T * y, - T * dst, - int64_t ne00, - int64_t ne01, - int64_t ne02, - int64_t ne0, - int64_t ne1, - int64_t ne2, - int dim, - cudaStream_t stream) { - const int64_t n = ne0 * ne1 * ne2; - const int num_blocks = (n + CUDA_CONCAT_BLOCK_SIZE - 1) / CUDA_CONCAT_BLOCK_SIZE; +static void concat_cont_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, + int dim, cudaStream_t stream) { + const T * x = (const T *) src0->data; + const T * y = (const T *) src1->data; + T * dst_d = (T *) dst->data; + + const int64_t ne00 = ggml_row_size(src0->type, src0->ne[0]) / sizeof(T); + const int64_t ne01 = src0->ne[1]; + const int64_t ne02 = src0->ne[2]; + const int64_t ne0 = ggml_row_size(dst->type, dst->ne[0]) / sizeof(T); + const int64_t ne1 = dst->ne[1]; + const int64_t ne2 = dst->ne[2]; + const int64_t ne3 = dst->ne[3]; + + const size_t stride_x = src0->nb[3] / sizeof(T); + const size_t stride_y = src1->nb[3] / sizeof(T); + const size_t stride_dst = dst->nb[3] / sizeof(T); + const int64_t n = ne0 * ne1 * ne2; + const int64_t blocks_x = (n + CUDA_CONCAT_BLOCK_SIZE - 1) / CUDA_CONCAT_BLOCK_SIZE; + // Each block strides over additional slices when the outer extent exceeds the grid Y limit. + const dim3 grid(static_cast(std::min(blocks_x, INT32_MAX)), + static_cast(std::min(ne3, 65535))); if (dim == 0) { - const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(num_blocks, CUDA_CONCAT_BLOCK_SIZE, 0, stream); - ggml_cuda_kernel_launch(concat_cont, launch_params, x, y, dst, ne00, ne01, ne02, ne0, ne1, ne2); + const ggml_cuda_kernel_launch_params launch_params(grid, CUDA_CONCAT_BLOCK_SIZE, 0, stream); + ggml_cuda_kernel_launch(concat_cont, launch_params, x, y, dst_d, ne00, ne01, ne02, ne0, ne1, ne2, ne3, + stride_x, stride_y, stride_dst); return; } if (dim == 1) { - concat_cont<<>>(x, y, dst, ne00, ne01, ne02, ne0, ne1, ne2); + concat_cont<<>>(x, y, dst_d, ne00, ne01, ne02, ne0, ne1, ne2, ne3, + stride_x, stride_y, stride_dst); return; } - concat_cont<<>>(x, y, dst, ne00, ne01, ne02, ne0, ne1, ne2); + concat_cont<<>>(x, y, dst_d, ne00, ne01, ne02, ne0, ne1, ne2, ne3, + stride_x, stride_y, stride_dst); } template @@ -232,18 +254,7 @@ static __global__ void __launch_bounds__(CUDA_CONCAT_BLOCK_SIZE) template static void concat_cuda(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst, int dim, cudaStream_t stream) { if (dim != 3 && ggml_is_contiguous_to_3(src0) && ggml_is_contiguous_to_3(src1)) { - const T * src0_d = (const T *) src0->data; - const T * src1_d = (const T *) src1->data; - T * dst_d = (T *) dst->data; - - for (int64_t i3 = 0; i3 < dst->ne[3]; i3++) { - concat_cont_cuda( - src0_d + i3*(src0->nb[3] / sizeof(T)), - src1_d + i3*(src1->nb[3] / sizeof(T)), - dst_d + i3*( dst->nb[3] / sizeof(T)), - ggml_row_size(src0->type, src0->ne[0])/sizeof(T), src0->ne[1], src0->ne[2], - ggml_row_size(dst->type, dst->ne[0])/sizeof(T), dst->ne[1], dst->ne[2], dim, stream); - } + concat_cont_cuda(src0, src1, dst, dim, stream); } else if (dim == 3 && ggml_is_contiguous(src0) && ggml_is_contiguous(src1)) { const size_t size0 = ggml_nbytes(src0); const size_t size1 = ggml_nbytes(src1); diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 520f3147080e..325f727a00c5 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -14874,6 +14874,9 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_concat(GGML_TYPE_Q8_0, {8192, 2, 1, 1}, dim == 0 ? 4096 : 1, dim, 0)); } + // contiguous with ne[3] > 65535 (CUDA grid y limit) + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {4, 2, 1, 70000}, 2, 2, 0)); + // non-contiguous with ne[2] or ne[3] > 65535 (CUDA grid y/z limit) test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {4, 2, 70000, 1}, 4, 0, 1)); test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {4, 2, 40000, 1}, 30000, 2, 1)); @@ -16041,6 +16044,12 @@ static std::vector> make_test_cases_perf() { test_cases.emplace_back(new test_concat(type, {2050, 8, 256, 1}, 255, 0, 0)); } + for (int64_t ne3 : { 1, 128, 1024 }) { + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {32, 18, 2, ne3}, 5, 2, 0)); + } + test_cases.emplace_back(new test_concat(GGML_TYPE_F32, {64, 36, 2, 128}, 5, 2, 0)); + test_cases.emplace_back(new test_concat(GGML_TYPE_Q8_0, {512, 1, 2, 1024}, 5, 2, 0)); + // CONT of a 0<->2 permute at DeepSeek-V4 lightning-indexer shapes: // indexer_kq is [n_kv, n_tokens, n_head=64] and gets ggml_cont(ggml_permute(.., 2,1,0,3)). for (int64_t n_kv : { 1024, 1280, 2048, 2304 }) { From a4e5552dbbb8128d5a3335b7dafba40a45a24eac Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Fri, 4 Dec 2026 11:18:34 +0200 Subject: [PATCH 385/401] metal : support bf16 K/V and fix the FA kv_rows partial chunks (#33608) * metal : accumulate the bf16 flash attention O in bfloat The bf16 prefill kernel kept the O accumulator in half while Q/K/V are bfloat, which mixed the accumulator type with the operands. Accumulate in bfloat and rescale the O matrix in float, since Metal does not allow bfloat4 *= float. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : fix flash attention kv_rows with partial K/V chunks The kv_rows path assumed the row lists are padded to the kernel chunk (256/64/32) and asserted it, so a partial last chunk was mishandled: - the pad kernel copied cache columns instead of the gathered rows, and the pad buffer was sized/indexed per cache stream (ne13) instead of per q slice (ne03), so slices >= 1 read the wrong region - the vec path did not gather the partial chunk through the row list and read V at the wrong pad offset, dropping the last chunk - direct row reads applied the cache stream stride to a shared cache Gather the partial chunk through the row list, size the pad per slice, and zero the stream stride for direct row reads. Also allow BF16 K/V with kv_rows: the non-vec gather converts to F16 and the tensor path uses the f16 kernel over the gathered rows. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : use bfloat shared memory for the bf16 vec FA kernels The bf16 vec instantiations used the half shared-memory type set, so K/V were converted bfloat->half on load. Add FA_TYPES_BF with bfloat Q/K/V in shared memory so the vec kernels read bfloat directly through the direct K/V path, and convert Q from f32 to bfloat as the prefill bf16 kernel does. Add the tuned _q%d_ne%d bf16 variants to match the f16/quantized sets, since the fa_vec tuning selects them, and use a float4 broadcast for the zero-fill casts that bfloat4 does not accept. Add bf16 to the FA vec slice test types to cover the new path. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : gather the kv_rows K/V in their own type The non-vec kv_rows path always gathered the referenced rows into an F16 buffer, so a BF16 cache was converted to F16 and the attention ran the f16 kernels. Replace the use_kv_f16 flag with the type of the buffer that the attention reads: quantized K/V is still dequantized to F16, but the cache type is otherwise kept, so BF16 stays BF16 through the gather and the partial-chunk pad. The gather kernel is now same-type (template on T, no cast), the gather and pad sizes/strides use ggml_type_size(kv_type), and the tensor, half8x8 and vec pipeline selectors take kv_type instead of the boolean. Add BF16 gather tests for the half8x8 path with and without the pad. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : use clearer names for the FA kernel paths Replace the historical half8x8/half4x4 labels with the 8x8 simdgroup kernel and the vec kernel, matching the actual kernel families. Comment only, no functional change. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : trim redundant flash attention comments Update the kv_rows support check that still claimed a contiguous F16 copy with BF16 converted to F16, drop the duplicated kv_type, pad-per-slice, dense-op and column-order explanations, and keep only the comments that explain non-obvious behavior. Comment only, no functional change. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) * metal : simplify the flash attention K/V type helpers Make kv_type the single source of truth for the type the flash attention kernels read, and derive dequant_kv from it (quantized cache and kv_type F16). Remove use_kv_f16 - its heuristic moves into kv_type - and use kv_type in the tensor path check and the is_q flag. This also enables the tensor path for a quantized rows gather whose shape fills the GPU. Remove the stale commented-out use_kv_f16/use_vec lines as well. Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB) --- ggml/src/ggml-metal/ggml-metal-device.cpp | 31 ++- ggml/src/ggml-metal/ggml-metal-device.h | 11 +- ggml/src/ggml-metal/ggml-metal-device.m | 11 +- ggml/src/ggml-metal/ggml-metal-ops.cpp | 188 +++++++++++------- ggml/src/ggml-metal/kernels/fa_aux.metal | 66 ++++-- ggml/src/ggml-metal/kernels/fa_common.metal | 6 +- ggml/src/ggml-metal/kernels/fa_f16.metal | 2 +- .../ggml-metal/kernels/fa_vec_common.metal | 15 +- ggml/src/ggml-metal/kernels/fa_vec_f16.metal | 93 +++++++-- tests/test-backend-ops.cpp | 4 +- 10 files changed, 290 insertions(+), 137 deletions(-) diff --git a/ggml/src/ggml-metal/ggml-metal-device.cpp b/ggml/src/ggml-metal/ggml-metal-device.cpp index 7f3cb70b05c0..6af80a1753b0 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.cpp +++ b/ggml/src/ggml-metal/ggml-metal-device.cpp @@ -1839,6 +1839,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_p ggml_metal_library_t lib, const struct ggml_tensor * op, bool has_mask, + bool has_rows, int32_t ncpsg) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); GGML_UNUSED(op); @@ -1849,9 +1850,10 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_p snprintf(base, 256, "kernel_%s", "flash_attn_ext_pad"); - snprintf(name, 256, "%s_mask=%d_ncpsg=%d", + snprintf(name, 256, "%s_mask=%d_rows=%d_ncpsg=%d", base, has_mask, + has_rows, ncpsg); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name); @@ -1859,6 +1861,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_p ggml_metal_cv_t cv = ggml_metal_cv_init(); ggml_metal_cv_set_bool(cv, has_mask, FC_FLASH_ATTN_EXT_PAD + 0); + ggml_metal_cv_set_bool(cv, has_rows, FC_FLASH_ATTN_EXT_PAD + 1); //ggml_metal_cv_set_bool(cv, has_sinks, FC_FLASH_ATTN_EXT_PAD + 1); //ggml_metal_cv_set_bool(cv, has_bias, FC_FLASH_ATTN_EXT_PAD + 2); //ggml_metal_cv_set_bool(cv, has_scap, FC_FLASH_ATTN_EXT_PAD + 3); @@ -1944,7 +1947,8 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_t bool has_mask, bool has_sinks, bool has_bias, - bool has_scap) { + bool has_scap, + enum ggml_type kv_type) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); char base[256]; @@ -1953,7 +1957,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_t const int32_t dk = (int32_t) op->src[1]->ne[0]; const int32_t dv = (int32_t) op->src[2]->ne[0]; - const char * type = op->src[1]->type == GGML_TYPE_BF16 ? "bf16" : "f16"; + const char * type = ggml_type_name(kv_type); snprintf(base, 256, "kernel_flash_attn_ext_tensor_%s_dk%d_dv%d", type, dk, dv); snprintf(name, 256, "%s_mask=%d_sinks=%d_bias=%d_scap=%d", base, has_mask, has_sinks, has_bias, has_scap); @@ -1984,7 +1988,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( bool has_scap, bool has_kvpad, int32_t nsg, - bool use_kv_f16, + enum ggml_type kv_type, int32_t ns10, int32_t ns20) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); @@ -1995,7 +1999,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( const int32_t dk = (int32_t) op->src[1]->ne[0]; const int32_t dv = (int32_t) op->src[2]->ne[0]; - const char * type = use_kv_f16 ? "f16" : ggml_type_name(op->src[1]->type); + const char * type = ggml_type_name(kv_type); // do bounds checks for the mask? const bool bc_mask = op->src[3] && (op->src[3]->ne[1] % 8 != 0); @@ -2044,18 +2048,23 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_rows( ggml_metal_library_t lib, - const ggml_tensor * op) { + const ggml_tensor * op, + enum ggml_type kv_type) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); - const char * base = "kernel_flash_attn_ext_rows"; + char base[256]; + + const char * type = ggml_type_name(kv_type); + + snprintf(base, 256, "kernel_flash_attn_ext_rows_%s", type); + + GGML_UNUSED(op); ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, base); if (!res.pipeline) { res = ggml_metal_library_compile_pipeline(lib, base, base, nullptr); } - GGML_UNUSED(op); - return res; } @@ -2093,7 +2102,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v int32_t ne, int32_t nsg, int32_t nwg, - bool use_kv_f16, + enum ggml_type kv_type, int32_t ns10, int32_t ns20) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); @@ -2104,7 +2113,7 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_v const int32_t dk = (int32_t) op->src[1]->ne[0]; const int32_t dv = (int32_t) op->src[2]->ne[0]; - const char * type = use_kv_f16 ? "f16" : ggml_type_name(op->src[1]->type); + const char * type = ggml_type_name(kv_type); char qne_suffix[16] = {0}; if (!(nqpsg == 1 && ne == ggml_metal_tuning::fa_vec_baseline_ne(dk, dv))) { diff --git a/ggml/src/ggml-metal/ggml-metal-device.h b/ggml/src/ggml-metal/ggml-metal-device.h index c370ce9a798c..32ac36ee1304 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.h +++ b/ggml/src/ggml-metal/ggml-metal-device.h @@ -189,6 +189,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att ggml_metal_library_t lib, const struct ggml_tensor * op, bool has_mask, + bool has_rows, int32_t ncpsg); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_kv_f16( @@ -207,7 +208,8 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att bool has_mask, bool has_sinks, bool has_bias, - bool has_scap); + bool has_scap, + enum ggml_type kv_type); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext( ggml_metal_library_t lib, @@ -218,13 +220,14 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att bool has_scap, bool has_kvpad, int32_t nsg, - bool use_kv_f16, + enum ggml_type kv_type, int32_t ns10, int32_t ns20); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_rows( ggml_metal_library_t lib, - const struct ggml_tensor * op); + const struct ggml_tensor * op, + enum ggml_type kv_type); struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_attn_ext_vec_idx( ggml_metal_library_t lib, @@ -244,7 +247,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_flash_att int32_t ne, int32_t nsg, int32_t nwg, - bool use_kv_f16, + enum ggml_type kv_type, int32_t ns10, int32_t ns20); diff --git a/ggml/src/ggml-metal/ggml-metal-device.m b/ggml/src/ggml-metal/ggml-metal-device.m index 50e8fd938282..3db087e4a04b 100644 --- a/ggml/src/ggml-metal/ggml-metal-device.m +++ b/ggml/src/ggml-metal/ggml-metal-device.m @@ -1779,8 +1779,8 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te return false; } - // the non-vec kernels attend over a contiguous F16 copy of the referenced rows: - // - F16 K/V is gathered directly + // the non-vec kernels attend over a contiguous copy of the referenced rows: + // - F16/BF16 K/V is gathered directly in the K/V cache type // - quantized K/V is first dequantized with kernel_flash_attn_ext_kv_*_f16 // - other types keep attending to the whole cache (dense mask) switch (op->src[1]->type) { @@ -1791,11 +1791,16 @@ bool ggml_metal_device_supports_op(ggml_metal_device_t dev, const struct ggml_te case GGML_TYPE_Q5_1: case GGML_TYPE_Q8_0: break; + case GGML_TYPE_BF16: + if (!has_bfloat) { + return false; + } + break; default: return false; } - // the row gather copies F16 values in groups of 4 + // the row gather copies 4 values at a time if (op->src[2]->ne[0] % 4 != 0) { return false; } diff --git a/ggml/src/ggml-metal/ggml-metal-ops.cpp b/ggml/src/ggml-metal/ggml-metal-ops.cpp index 8856ef2548a7..ed4a52f9b190 100644 --- a/ggml/src/ggml-metal/ggml-metal-ops.cpp +++ b/ggml/src/ggml-metal/ggml-metal-ops.cpp @@ -3325,31 +3325,7 @@ bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) { return (ne01 < 20) && (ne00 % 32 == 0); } -// ref: https://github.com/ggml-org/llama.cpp/pull/27390 -// dequantize the quantized KV cache to F16 before running the F16 flash attention kernels -static bool ggml_metal_op_flash_attn_ext_use_kv_f16(const ggml_tensor * op) { - assert(op->op == GGML_OP_FLASH_ATTN_EXT); - - // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial - // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767 - // TODO: tune per device - // large heads need the upfront dequant to fit the non-vec threadgroup memory - if (op->src[0]->ne[1] < 32 && - (op->src[0]->ne[0] < 512 || ggml_metal_op_flash_attn_ext_use_vec(op))) { - return false; - } - - switch (op->src[1]->type) { - case GGML_TYPE_Q4_0: - case GGML_TYPE_Q4_1: - case GGML_TYPE_Q5_0: - case GGML_TYPE_Q5_1: - case GGML_TYPE_Q8_0: - return true; - default: - return false; - } -} +static ggml_type ggml_metal_op_flash_attn_ext_kv_type(const ggml_tensor * op); static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool has_tensor) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); @@ -3379,13 +3355,14 @@ static bool ggml_metal_op_flash_attn_ext_use_tensor(const ggml_tensor * op, bool // large heads use fewer queries per threadgroup, so that the queries fit in threadgroup memory const int64_t nqptg = dk >= 512 ? OP_FLASH_ATTN_EXT_TENSOR_NQPSG_LARGE : OP_FLASH_ATTN_EXT_TENSOR_NQPSG; - // few heads and small batches do not fill the GPU - the half8x8 kernel is faster there + // few heads and small batches do not fill the GPU - the 8x8 simdgroup kernel is faster there // TODO: tune per device if (((ne01 + nqptg - 1)/nqptg)*ne02*ne03*dk < 8192) { return false; } - if (op->src[1]->type != GGML_TYPE_F16 && op->src[1]->type != GGML_TYPE_BF16 && !ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { + const ggml_type kv_type = ggml_metal_op_flash_attn_ext_kv_type(op); + if (kv_type != GGML_TYPE_F16 && kv_type != GGML_TYPE_BF16) { return false; } @@ -3473,6 +3450,56 @@ static bool ggml_metal_op_flash_attn_ext_v_is_view_of_k(const ggml_tensor * op) return V->view_src && (V->view_src == K || (V->view_src == K->view_src && V->view_offs == K->view_offs)); } +// the type of the K/V buffer that the flash attention kernels read +static ggml_type ggml_metal_op_flash_attn_ext_kv_type(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + + const ggml_type type = op->src[1]->type; + + if (!ggml_is_quantized(type)) { + return type; + } + + const bool has_rows = op->src[5] != nullptr; + const bool rows_gather = has_rows && !ggml_metal_op_flash_attn_ext_use_vec(op); + + if (rows_gather) { + return GGML_TYPE_F16; + } + + // the sparse path dequantizes the KV inline in the vec kernel + if (ggml_metal_op_flash_attn_ext_n_kv_max_sparse(op) != 0) { + return type; + } + + // depending on compute/bandwidth ratio, dequant to f16 kv is not always beneficial + // ref: https://github.com/ggml-org/llama.cpp/pull/27390#issuecomment-5355152767 + // TODO: tune per device + // large heads need the upfront dequant to fit the non-vec threadgroup memory + if (op->src[0]->ne[1] < 32 && + (op->src[0]->ne[0] < 512 || ggml_metal_op_flash_attn_ext_use_vec(op))) { + return type; + } + + switch (type) { + case GGML_TYPE_Q4_0: + case GGML_TYPE_Q4_1: + case GGML_TYPE_Q5_0: + case GGML_TYPE_Q5_1: + case GGML_TYPE_Q8_0: + return GGML_TYPE_F16; + default: + return type; + } +} + +static bool ggml_metal_op_flash_attn_ext_dequant_kv(const ggml_tensor * op) { + assert(op->op == GGML_OP_FLASH_ATTN_EXT); + + return ggml_is_quantized(op->src[1]->type) && + ggml_metal_op_flash_attn_ext_kv_type(op) == GGML_TYPE_F16; +} + // size of the F16 dequantized K tensor; the dequantized V tensor follows it in the same scratch buffer static size_t ggml_metal_op_flash_attn_ext_kv_f16_k_size(const ggml_tensor * op) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); @@ -3497,19 +3524,25 @@ size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { size_t res = 0; const bool has_mask = op->src[3] != nullptr; - const bool use_kv_f16 = ggml_metal_op_flash_attn_ext_use_kv_f16(op); - // when the KV is dequantized to F16, the pad kernel copies the tail chunk from the F16 scratch buffer - // note: when V is a view of K, the dequantized V is read from the dequantized K with K's row stride - const bool v_is_view_of_k = use_kv_f16 && ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); + // the KV strides below must match the ones used by ggml_metal_op_flash_attn_ext + const bool has_rows = op->src[5] != nullptr; + const bool rows_gather = has_rows && !ggml_metal_op_flash_attn_ext_use_vec(op); + const bool dequant_kv = ggml_metal_op_flash_attn_ext_dequant_kv(op); + const ggml_type kv_type = dequant_kv ? GGML_TYPE_F16 : op->src[1]->type; + + // note: when V is a view of K, the compact V is read from the compact K with K's row stride + const bool v_is_view_of_k = (rows_gather || dequant_kv) && ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); uint64_t nb11_pad = nb11; uint64_t nb21_pad = nb21; - if (use_kv_f16) { - nb11_pad = sizeof(ggml_fp16_t)*ne10; - nb21_pad = sizeof(ggml_fp16_t)*(v_is_view_of_k ? ne10 : ne20); + if (rows_gather || dequant_kv) { + nb11_pad = ggml_type_size(kv_type)*ne10; + nb21_pad = ggml_type_size(kv_type)*(v_is_view_of_k ? ne10 : ne20); } + const int64_t n_kv_pad = has_rows ? ne03 : ne13; + // note: the non-vec kernel requires more extra memory, so always reserve for it GGML_ASSERT(OP_FLASH_ATTN_EXT_NCPSG >= OP_FLASH_ATTN_EXT_VEC_NCPSG); @@ -3521,8 +3554,8 @@ size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { if (has_kvpad) { res += OP_FLASH_ATTN_EXT_VEC_NCPSG*( - nb11_pad*ne12*ne13 + - nb21_pad*ne22*ne23 + + nb11_pad*ne12*n_kv_pad + + nb21_pad*ne22*n_kv_pad + (has_mask ? ggml_type_size(GGML_TYPE_F16)*ne31*ne32*ne33 : 0)); } } else { @@ -3531,8 +3564,8 @@ size_t ggml_metal_op_flash_attn_ext_extra_pad(const ggml_tensor * op) { if (has_kvpad) { res += OP_FLASH_ATTN_EXT_NCPSG*( - nb11_pad*ne12*ne13 + - nb21_pad*ne22*ne23 + + nb11_pad*ne12*n_kv_pad + + nb21_pad*ne22*n_kv_pad + (has_mask ? ggml_type_size(GGML_TYPE_F16)*ne31*ne32*ne33 : 0)); } } @@ -3594,7 +3627,6 @@ size_t ggml_metal_op_flash_attn_ext_extra_tmp(const ggml_tensor * op) { size_t res = 0; // note: always reserve the temp buffer to avoid graph reallocations - //if (ggml_metal_op_flash_attn_ext_use_vec(op)) { if (true) { const int64_t nwg = 32; const int64_t ne01_max = std::min(ne01, 32); @@ -3612,9 +3644,6 @@ size_t ggml_metal_op_flash_attn_ext_extra_kv_f16(const ggml_tensor * op) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); // note: always reserve the temp buffer to avoid graph reallocations - //if (!ggml_metal_op_flash_attn_ext_use_kv_f16(op)) { - // return 0; - //} GGML_TENSOR_LOCALS( int32_t, ne2, op->src[2], ne); @@ -3649,8 +3678,7 @@ size_t ggml_metal_op_flash_attn_ext_extra_idx(const ggml_tensor * op) { return GGML_PAD(sizeof(int32_t)*(size_t) n_kv_max_padded*ne31*ne32*ne33, 16); } -// size of the contiguous F16 buffers holding the K/V rows referenced by the kv_rows lists -// the attention over these buffers is a standard dense op (no per-tile gather in the main kernel) +// size of the contiguous buffers holding the K/V rows referenced by the kv_rows lists size_t ggml_metal_op_flash_attn_ext_extra_rows(const ggml_tensor * op) { assert(op->op == GGML_OP_FLASH_ATTN_EXT); @@ -3669,8 +3697,10 @@ size_t ggml_metal_op_flash_attn_ext_extra_rows(const ggml_tensor * op) { // note: when V is a view of K, the gathered V is read from the gathered K, so only K is gathered const bool v_is_view_of_k = ggml_metal_op_flash_attn_ext_v_is_view_of_k(op); - const size_t k_size = GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne10*n_rows*ne12*n_slices, 16); - const size_t v_size = v_is_view_of_k ? 0 : GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne20*n_rows*ne22*n_slices, 16); + const ggml_type kv_type = ggml_metal_op_flash_attn_ext_kv_type(op); + + const size_t k_size = GGML_PAD(ggml_type_size(kv_type)*(size_t) ne10*n_rows*ne12*n_slices, 16); + const size_t v_size = v_is_view_of_k ? 0 : GGML_PAD(ggml_type_size(kv_type)*(size_t) ne20*n_rows*ne22*n_slices, 16); return k_size + v_size; } @@ -3719,9 +3749,11 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { // the loop bound over the mask columns / K/V row lists const int64_t ne11_attn = has_rows ? kv_rows->ne[0] : ne11; - // the row lists are padded by the KV cache to a multiple of 256, so the pad path never triggers - GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_NCPSG == 0); - GGML_ASSERT(!has_rows || ne11_attn % OP_FLASH_ATTN_EXT_VEC_NCPSG == 0); + // with kv_rows the pad buffer holds one gathered copy per q slice, not one per cache stream + const int64_t ne_12_3_attn = has_rows ? ne03 : ne13; + + // the vec path gathers the rows of the partial last chunk with the pad kernel + const bool pad_gather_rows = has_rows && ggml_metal_op_flash_attn_ext_use_vec(op); float scale; float max_bias; @@ -3777,15 +3809,13 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { const bool use_vec = ggml_metal_op_flash_attn_ext_use_vec(op); - // with kv_rows, the non-vec path gathers the referenced rows into a contiguous F16 buffer and - // attends over it with the F16 kernel - quantized KV is first dequantized with the F16 pass + // with kv_rows, the non-vec path gathers the referenced rows into a contiguous buffer of the + // attention type - quantized KV is first dequantized with the F16 pass const bool rows_gather = has_rows && !use_vec; // the vec kernels dequantize the KV inline; no need for the F16 dequant pass in the sparse path - const bool dequant_kv = !use_sparse && (rows_gather ? - ggml_is_quantized(op->src[1]->type) : ggml_metal_op_flash_attn_ext_use_kv_f16(op)); - - const bool use_kv_f16 = !use_sparse && (rows_gather ? true : dequant_kv); + const bool dequant_kv = ggml_metal_op_flash_attn_ext_dequant_kv(op); + const ggml_type kv_type = dequant_kv ? GGML_TYPE_F16 : op->src[1]->type; ggml_metal_buffer_id bid_idx = bid_kv_f16; bid_idx.offs += ggml_metal_op_flash_attn_ext_extra_kv_f16(op); @@ -3894,8 +3924,6 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { } } - // with kv_rows, gather the cache rows referenced by the lists into contiguous F16 buffers - // the attention then runs as a standard dense op over the gathered rows (tensor or half8x8 kernel) if (rows_gather) { assert(ggml_metal_op_flash_attn_ext_extra_rows(op) != 0); @@ -3903,7 +3931,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { GGML_ASSERT(ne20 % 4 == 0); - const size_t k_size = GGML_PAD(sizeof(ggml_fp16_t)*(size_t) ne10*ne11_attn*ne12*ne03, 16); + const size_t k_size = GGML_PAD(ggml_type_size(kv_type)*(size_t) ne10*ne11_attn*ne12*ne03, 16); ggml_metal_kargs_flash_attn_ext_rows args0 = { /*.ne11 =*/ (int32_t) ne11_attn, @@ -3917,7 +3945,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.nb22 =*/ nb22_attn, }; - auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_rows(lib, op); + auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_rows(lib, op, kv_type); const int nth = std::min(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline0), 64); ggml_metal_encoder_set_pipeline(enc, pipeline0); @@ -3931,10 +3959,10 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_op_concurrency_reset(ctx); - // contiguous F16 layout of the gathered rows: [DK, n_rows, n_head_kv, n_streams] + // compact layout of the gathered rows: [DK, n_rows, n_head_kv, n_streams] bid_k = bid_rows; - nb10_attn = sizeof(ggml_fp16_t); + nb10_attn = ggml_type_size(kv_type); nb11_attn = nb10_attn*ne10; nb12_attn = nb11_attn*ne11_attn; nb13_attn = nb12_attn*ne12; @@ -3951,11 +3979,15 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { bid_v = bid_rows; bid_v.offs += k_size; - nb20_attn = sizeof(ggml_fp16_t); + nb20_attn = ggml_type_size(kv_type); nb21_attn = nb20_attn*ne20; nb22_attn = nb21_attn*ne11_attn; nb23_attn = nb22_attn*ne22; } + } else if (has_rows) { + // the row lists select the rows from the K/V cache shared by all slices + nb13_attn = 0; + nb23_attn = 0; } if (!use_sparse && ggml_metal_op_flash_attn_ext_use_tensor(op, props_dev->has_tensor)) { @@ -4034,7 +4066,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { // shared memory layout: queries (16-bit), scores (float), probabilities (16-bit), row scale (float), rescale flag (int) const size_t smem = GGML_PAD(nqptg*ne00*sizeof(ggml_fp16_t) + nqptg*ncpsg*(sizeof(float) + sizeof(ggml_fp16_t)) + nqptg*sizeof(float) + sizeof(int32_t), 16); - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_tensor(lib, op, has_mask, has_sinks, has_bias, has_scap); + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_tensor(lib, op, has_mask, has_sinks, has_bias, has_scap, kv_type); GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); GGML_ASSERT(smem <= props_dev->max_theadgroup_memory_size); @@ -4053,7 +4085,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nqptg - 1)/nqptg, ne02, ne03, 32, nsg, 1); } else if (!use_sparse && !ggml_metal_op_flash_attn_ext_use_vec(op)) { - // half8x8 kernel + // 8x8 simdgroup kernel const int nqptg = OP_FLASH_ATTN_EXT_NQPSG; // queries per threadgroup const int ncpsg = OP_FLASH_ATTN_EXT_NCPSG; // cache values per simdgroup @@ -4069,9 +4101,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); ggml_metal_kargs_flash_attn_ext_pad args0 = { - /*.ne11 =*/ne11, + /*.ne11 =*/(int32_t) ne11_attn, /*.ne_12_2 =*/ne12, - /*.ne_12_3 =*/ne13, + /*.ne_12_3 =*/(int32_t) ne_12_3_attn, /*.nb11 =*/nb11_attn, /*.nb12 =*/nb12_attn, /*.nb13 =*/nb13_attn, @@ -4086,7 +4118,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.nb33 =*/nb33, }; - auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg); + auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, pad_gather_rows, ncpsg); ggml_metal_encoder_set_pipeline(enc, pipeline0); ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); @@ -4094,11 +4126,12 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_set_buffer (enc, bid_v, 2); ggml_metal_encoder_set_buffer (enc, bid_src3, 3); ggml_metal_encoder_set_buffer (enc, bid_pad, 4); + ggml_metal_encoder_set_buffer (enc, pad_gather_rows ? ggml_metal_get_buffer_id(kv_rows) : bid_src0, 5); assert(ne12 == ne22); assert(ne13 == ne23); - ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne13, ne33), 32, 1, 1); + ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne_12_3_attn, ne33), 32, 1, 1); need_sync = true; } @@ -4136,7 +4169,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_op_concurrency_reset(ctx); } - const int is_q = !use_kv_f16 && ggml_is_quantized(op->src[1]->type) ? 1 : 0; + const int is_q = ggml_is_quantized(kv_type) ? 1 : 0; // shared memory layout (halfs unless noted): // queries/attn/result: Q*(DK + 2*PAD2(DV,64) + 4*C) @@ -4191,7 +4224,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.logit_softcap =*/ logit_softcap, }; - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, nsg, use_kv_f16, ns10, ns20); + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, nsg, kv_type, ns10, ns20); ggml_metal_encoder_set_pipeline(enc, pipeline); ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0); @@ -4210,7 +4243,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_dispatch_threadgroups(enc, (ne01 + nqptg - 1)/nqptg, ne02, ne03, 32, nsg, 1); } else { - // half4x4 kernel + // vec kernel // sparse: the index lists are per query row, so a threadgroup can share KV with Q == 1 only auto cfg = use_sparse ? ggml_metal_tuning::fa_vec_baseline_cfg((int) ne00, (int) ne20) @@ -4269,9 +4302,9 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { assert(ggml_metal_op_flash_attn_ext_extra_pad(op) != 0); ggml_metal_kargs_flash_attn_ext_pad args0 = { - /*.ne11 =*/ne11, + /*.ne11 =*/(int32_t) ne11_attn, /*.ne_12_2 =*/ne12, - /*.ne_12_3 =*/ne13, + /*.ne_12_3 =*/(int32_t) ne_12_3_attn, /*.nb11 =*/nb11_attn, /*.nb12 =*/nb12_attn, /*.nb13 =*/nb13_attn, @@ -4286,7 +4319,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.nb33 =*/nb33, }; - auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, ncpsg); + auto pipeline0 = ggml_metal_library_get_pipeline_flash_attn_ext_pad(lib, op, has_mask, pad_gather_rows, ncpsg); ggml_metal_encoder_set_pipeline(enc, pipeline0); ggml_metal_encoder_set_bytes (enc, &args0, sizeof(args0), 0); @@ -4294,11 +4327,12 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { ggml_metal_encoder_set_buffer (enc, bid_v, 2); ggml_metal_encoder_set_buffer (enc, bid_src3, 3); ggml_metal_encoder_set_buffer (enc, bid_pad, 4); + ggml_metal_encoder_set_buffer (enc, pad_gather_rows ? ggml_metal_get_buffer_id(kv_rows) : bid_src0, 5); assert(ne12 == ne22); assert(ne13 == ne23); - ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne13, ne33), 32, 1, 1); + ggml_metal_encoder_dispatch_threadgroups(enc, ncpsg, std::max(ne12, ne32), std::max(ne_12_3_attn, ne33), 32, 1, 1); need_sync = true; } @@ -4374,7 +4408,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.nb03 =*/ nb03, /*.ne11 =*/ use_sparse ? n_kv_max_padded : (int32_t) ne11_attn, /*.ne_12_2 =*/ ne12, - /*.ne_12_3 =*/ ne13, + /*.ne_12_3 =*/ has_rows ? ne03 : ne13, /*.ns10 =*/ ns10, /*.nb11 =*/ nb11_attn, /*.nb12 =*/ nb12_attn, @@ -4401,7 +4435,7 @@ int ggml_metal_op_flash_attn_ext(ggml_metal_op_t ctx, int idx) { /*.n_kv_max_padded =*/ n_kv_max_padded, }; - auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, nqptg, cfg.NE, nsg, nwg, use_kv_f16, ns10, ns20); + auto pipeline = ggml_metal_library_get_pipeline_flash_attn_ext_vec(lib, op, has_mask, has_sinks, has_bias, has_scap, has_kvpad, use_sparse, has_rows, nqptg, cfg.NE, nsg, nwg, kv_type, ns10, ns20); GGML_ASSERT(nsg*32 <= ggml_metal_pipeline_max_theads_per_threadgroup(pipeline)); diff --git a/ggml/src/ggml-metal/kernels/fa_aux.metal b/ggml/src/ggml-metal/kernels/fa_aux.metal index 6fe47470fb2d..32de8f2f9acc 100644 --- a/ggml/src/ggml-metal/kernels/fa_aux.metal +++ b/ggml/src/ggml-metal/kernels/fa_aux.metal @@ -48,10 +48,12 @@ template [[host_name("kernel_flash_attn_ext_kv_q5_0_f16")]] kernel kernel_flash_ template [[host_name("kernel_flash_attn_ext_kv_q5_1_f16")]] kernel kernel_flash_attn_ext_kv_f16_t kernel_flash_attn_ext_kv_f16; template [[host_name("kernel_flash_attn_ext_kv_q8_0_f16")]] kernel kernel_flash_attn_ext_kv_f16_t kernel_flash_attn_ext_kv_f16; -// gather the K/V cache rows referenced by the kv_rows lists into contiguous F16 buffers +// gather the K/V cache rows referenced by the kv_rows lists into contiguous buffers // - one threadgroup per (row, stream); the attention is then run as a standard dense op over the // gathered rows, which avoids the per-tile K/V gather in the main kernels // - negative rows are padding: filled with zeros, their mask entries are -INF so they contribute nothing +// - T is the K/V cache type, or F16 for the dequantized scratch +template kernel void kernel_flash_attn_ext_rows( constant ggml_metal_kargs_flash_attn_ext_rows & args, device const char * k_src, @@ -61,17 +63,19 @@ kernel void kernel_flash_attn_ext_rows( uint3 tgpig[[threadgroup_position_in_grid]], ushort tiitg[[thread_index_in_threadgroup]], ushort3 ntg[[threads_per_threadgroup]]) { + using T4 = typename value_type_4::type; + const int64_t i1 = tgpig[0]; // row index const int64_t i3 = tgpig[1]; // stream const int64_t row = rows[i1 + i3*args.ne11]; - // gathered layout: [DK, n_rows, n_head_kv, n_streams] and [DV, n_rows, n_head_kv, n_streams] F16 - device half4 * k_dst = (device half4 *) (dst + i3*args.ne_12_2*args.ne11*args.ne10*sizeof(half)); - device half4 * v_dst = (device half4 *) (dst + args.v_off + i3*args.ne_12_2*args.ne11*args.ne20*sizeof(half)); + // gathered layout: [DK, n_rows, n_head_kv, n_streams] and [DV, n_rows, n_head_kv, n_streams] + device T4 * k_dst = (device T4 *) (dst + i3*args.ne_12_2*args.ne11*args.ne10*sizeof(T)); + device T4 * v_dst = (device T4 *) (dst + args.v_off + i3*args.ne_12_2*args.ne11*args.ne20*sizeof(T)); // note: the K/V cache is shared by all streams (ne13 = ne23 = 1), the row list selects the rows - // each thread copies up to 4 half4 values (32 bytes) to keep the memory transactions large + // each thread copies up to 4 T4 values (32 bytes) to keep the memory transactions large // K: all heads of this row { @@ -82,16 +86,16 @@ kernel void kernel_flash_attn_ext_rows( const int64_t i0 = i%per_head; const int n = (int) min((int64_t) 4, per_head - i0); - device half4 * dst4 = k_dst + (i2*args.ne11 + i1)*per_head + i0; + device T4 * dst4 = k_dst + (i2*args.ne11 + i1)*per_head + i0; if (row >= 0) { - device const half4 * src4 = (device const half4 *) (k_src + row*args.nb11 + i2*args.nb12) + i0; + device const T4 * src4 = (device const T4 *) (k_src + row*args.nb11 + i2*args.nb12) + i0; for (int j = 0; j < n; ++j) { dst4[j] = src4[j]; } } else { for (int j = 0; j < n; ++j) { - dst4[j] = half4(0.0h); + dst4[j] = (T4) ((float4) 0.0f); } } } @@ -106,33 +110,43 @@ kernel void kernel_flash_attn_ext_rows( const int64_t i0 = i%per_head; const int n = (int) min((int64_t) 4, per_head - i0); - device half4 * dst4 = v_dst + (i2*args.ne11 + i1)*per_head + i0; + device T4 * dst4 = v_dst + (i2*args.ne11 + i1)*per_head + i0; if (row >= 0) { - device const half4 * src4 = (device const half4 *) (v_src + row*args.nb21 + i2*args.nb22) + i0; + device const T4 * src4 = (device const T4 *) (v_src + row*args.nb21 + i2*args.nb22) + i0; for (int j = 0; j < n; ++j) { dst4[j] = src4[j]; } } else { for (int j = 0; j < n; ++j) { - dst4[j] = half4(0.0h); + dst4[j] = (T4) ((float4) 0.0f); } } } } } +typedef decltype(kernel_flash_attn_ext_rows) kernel_flash_attn_ext_rows_t; + +template [[host_name("kernel_flash_attn_ext_rows_f16")]] kernel kernel_flash_attn_ext_rows_t kernel_flash_attn_ext_rows; +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_flash_attn_ext_rows_bf16")]] kernel kernel_flash_attn_ext_rows_t kernel_flash_attn_ext_rows; +#endif + constant bool FC_flash_attn_ext_pad_has_mask [[function_constant(FC_FLASH_ATTN_EXT_PAD + 0)]]; +constant bool FC_flash_attn_ext_pad_has_rows [[function_constant(FC_FLASH_ATTN_EXT_PAD + 1)]]; constant int32_t FC_flash_attn_ext_pad_ncpsg [[function_constant(FC_FLASH_ATTN_EXT_PAD + 25)]]; // pad the last chunk of C elements of k and v into a an extra pad buffer +// - with kv_rows, the rows of the last chunk are gathered through the row list (the K/V cache is shared by all streams) kernel void kernel_flash_attn_ext_pad( constant ggml_metal_kargs_flash_attn_ext_pad & args, device const char * k, device const char * v, device const char * mask, device char * dst, + device const int * rows, uint3 tgpig[[threadgroup_position_in_grid]], ushort tiitg[[thread_index_in_threadgroup]], ushort3 ntg[[threads_per_threadgroup]]) { @@ -150,25 +164,39 @@ kernel void kernel_flash_attn_ext_pad( const int32_t i3 = tgpig[2]; if (i2 < args.ne_12_2 && i3 < args.ne_12_3) { - device const char * k_src = k + args.nb11*(ic0 + i1) + args.nb12*i2 + args.nb13*i3; - device const char * v_src = v + args.nb21*(ic0 + i1) + args.nb22*i2 + args.nb23*i3; - device char * k_dst = k_pad + args.nb11*i1 + args.nb11*C*i2 + args.nb11*C*args.ne_12_2*i3; device char * v_dst = v_pad + args.nb21*i1 + args.nb21*C*i2 + args.nb21*C*args.ne_12_2*i3; - if (i1 >= icp) { + // the row list of this stream selects the K/V cache rows of the last chunk + // note: the cache rows can span all K/V heads, so only the per-head bytes are copied + const int64_t ic = ic0 + i1; + const int64_t row = FC_flash_attn_ext_pad_has_rows && ic < args.ne11 ? rows[ic + (int64_t) i3*args.ne11] : -1; + + const bool pad = FC_flash_attn_ext_pad_has_rows ? row < 0 : i1 >= icp; + + const uint64_t nb_k = FC_flash_attn_ext_pad_has_rows && args.nb12 < args.nb11 ? args.nb12 : args.nb11; + const uint64_t nb_v = FC_flash_attn_ext_pad_has_rows && args.nb22 < args.nb21 ? args.nb22 : args.nb21; + + if (pad) { // here it is not important the exact value that will be used as we rely on masking out the scores in the attention - for (uint64_t i = tiitg; i < args.nb11; i += ntg.x) { + for (uint64_t i = tiitg; i < nb_k; i += ntg.x) { k_dst[i] = 0; } - for (uint64_t i = tiitg; i < args.nb21; i += ntg.x) { + for (uint64_t i = tiitg; i < nb_v; i += ntg.x) { v_dst[i] = 0; } } else { - for (uint64_t i = tiitg; i < args.nb11; i += ntg.x) { + device const char * k_src = FC_flash_attn_ext_pad_has_rows + ? k + (int64_t) row*args.nb11 + args.nb12*i2 + : k + args.nb11*(ic0 + i1) + args.nb12*i2 + args.nb13*i3; + device const char * v_src = FC_flash_attn_ext_pad_has_rows + ? v + (int64_t) row*args.nb21 + args.nb22*i2 + : v + args.nb21*(ic0 + i1) + args.nb22*i2 + args.nb23*i3; + + for (uint64_t i = tiitg; i < nb_k; i += ntg.x) { k_dst[i] = k_src[i]; } - for (uint64_t i = tiitg; i < args.nb21; i += ntg.x) { + for (uint64_t i = tiitg; i < nb_v; i += ntg.x) { v_dst[i] = v_src[i]; } } diff --git a/ggml/src/ggml-metal/kernels/fa_common.metal b/ggml/src/ggml-metal/kernels/fa_common.metal index 0a2148bda6a5..3a2d539c548e 100644 --- a/ggml/src/ggml-metal/kernels/fa_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_common.metal @@ -449,11 +449,11 @@ void kernel_flash_attn_ext_impl( FOR_UNROLL (short ii = 0; ii < DV4/NW; ++ii) { const short i = ii*NW + tiisg; - so4[j*PV4 + i] *= ms; + so4[j*PV4 + i] = (o4_t) ((float4) so4[j*PV4 + i]*ms); } } else { for (short i = tiisg; i < DV4; i += NW) { - so4[j*PV4 + i] *= ms; + so4[j*PV4 + i] = (o4_t) ((float4) so4[j*PV4 + i]*ms); } } } @@ -625,7 +625,7 @@ void kernel_flash_attn_ext_impl( S[jj] = S[jj]*ms + simd_sum(vs); for (short i = tiisg; i < DV4; i += NW) { - so4[j*PV4 + i] *= ms; + so4[j*PV4 + i] = (o4_t) ((float4) so4[j*PV4 + i]*ms); } } } diff --git a/ggml/src/ggml-metal/kernels/fa_f16.metal b/ggml/src/ggml-metal/kernels/fa_f16.metal index 616b9377acfc..e6820d3d4815 100644 --- a/ggml/src/ggml-metal/kernels/fa_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_f16.metal @@ -19,7 +19,7 @@ bfloat, \ float, \ float, \ - half + bfloat #define FA_TYPES_F32 \ half, \ diff --git a/ggml/src/ggml-metal/kernels/fa_vec_common.metal b/ggml/src/ggml-metal/kernels/fa_vec_common.metal index cf37e492442b..f30ec3f7e4d7 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_common.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_common.metal @@ -124,12 +124,12 @@ kernel void kernel_flash_attn_ext_vec( if (i < DK4) { sq4[qq*PK4 + i] = (q4_t) q4[i]; } else { - sq4[qq*PK4 + i] = (q4_t) 0.0f; + sq4[qq*PK4 + i] = (q4_t) ((float4) 0.0f); } } } else { for (short i = tiisg; i < PK4; i += NW) { - sq4[qq*PK4 + i] = (q4_t) 0.0f; + sq4[qq*PK4 + i] = (q4_t) ((float4) 0.0f); } } } @@ -208,7 +208,9 @@ kernel void kernel_flash_attn_ext_vec( } // the last partial chunk uses the pad buffer as source - if (FC_flash_attn_ext_vec_has_kvpad && ic + C > args.ne11) { + const bool use_pad = FC_flash_attn_ext_vec_has_kvpad && ic + C > args.ne11; + + if (use_pad) { k = pad; v = k + args.nb11*C*args.ne_12_2*args.ne_12_3; mask = v + args.nb21*C*args.ne_12_2*args.ne_12_3; @@ -238,7 +240,8 @@ kernel void kernel_flash_attn_ext_vec( } // load the KV row indices for the current block into shared memory - if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { + // note: with kv_rows the pad buffer holds the gathered rows in column order, so no list is needed + if (FC_flash_attn_ext_vec_has_sparse || (FC_flash_attn_ext_vec_has_rows && !use_pad)) { FOR_UNROLL (short ii = 0; ii < C/NW; ++ii) { const short i = ii*NW + tiisg; @@ -317,7 +320,7 @@ kernel void kernel_flash_attn_ext_vec( FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { // the KV rows are gathered from the index list; -1 entries are padding - const int i11 = spidx[NE*cc + ty]; + const int i11 = (FC_flash_attn_ext_vec_has_rows && use_pad) ? (ic + NE*cc + ty) : spidx[NE*cc + ty]; if (i11 >= 0) { if (is_same::value) { device const k4_t * pk4s = (device const k4_t *) (k + i11*args.nb11) + tx; @@ -461,7 +464,7 @@ kernel void kernel_flash_attn_ext_vec( if (FC_flash_attn_ext_vec_has_sparse || FC_flash_attn_ext_vec_has_rows) { FOR_UNROLL (short cc = 0; cc < C/NE; ++cc) { // the KV rows are gathered from the index list; -1 entries are padding - const int i11 = spidx[NE*cc + ty]; + const int i11 = (FC_flash_attn_ext_vec_has_rows && use_pad) ? (ic + NE*cc + ty) : spidx[NE*cc + ty]; if (i11 >= 0) { if (is_same::value) { device const v4_t * pv4 = (device const v4_t *) (v + i11*args.nb21); diff --git a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal index 94377e39fef5..4431819a5318 100644 --- a/ggml/src/ggml-metal/kernels/fa_vec_f16.metal +++ b/ggml/src/ggml-metal/kernels/fa_vec_f16.metal @@ -10,6 +10,14 @@ float, \ float +#define FA_TYPES_BF \ + bfloat, \ + bfloat, \ + bfloat, \ + float, \ + float, \ + float + #define FA_TYPES_F32 \ half, \ float, \ @@ -24,7 +32,7 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk32_dv32")]] kernel flas template [[host_name("kernel_flash_attn_ext_vec_f16_dk32_dv32_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk32_dv32_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk32_dv32")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk32_dv32")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk64_dv64_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -33,19 +41,19 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk64_dv64_q2_ne4")]] kerne template [[host_name("kernel_flash_attn_ext_vec_f16_dk64_dv64_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk64_dv64_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk64_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk96_dv96")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk96_dv96_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk96_dv96_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv96")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv96")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk96_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk96_dv64_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk96_dv64_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv64")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk128_dv128_q1_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -60,8 +68,8 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk128_dv96")]] kernel fla template [[host_name("kernel_flash_attn_ext_vec_f16_dk128_dv96_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk128_dv96_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv96")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv96")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv192")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv192_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -70,7 +78,7 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv192_q2_ne4")]] kerne template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv192_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv192_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv192")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv192")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv128_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -79,7 +87,7 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv128_q2_ne4")]] kerne template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv128_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk192_dv128_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv128")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk256_dv256")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk256_dv256_q1_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -91,7 +99,7 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk256_dv256_q4_ne1")]] kerne template [[host_name("kernel_flash_attn_ext_vec_f16_dk256_dv256_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk256_dv256_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk320_dv256")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk320_dv256_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -100,7 +108,7 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk320_dv256_q2_ne4")]] kerne template [[host_name("kernel_flash_attn_ext_vec_f16_dk320_dv256_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk320_dv256_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk320_dv256")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk320_dv256")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk512_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk512_dv512_q1_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -112,7 +120,7 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk512_dv512_q4_ne1")]] kerne template [[host_name("kernel_flash_attn_ext_vec_f16_dk512_dv512_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk512_dv512_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif template [[host_name("kernel_flash_attn_ext_vec_f16_dk576_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk576_dv512_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; @@ -121,9 +129,70 @@ template [[host_name("kernel_flash_attn_ext_vec_f16_dk576_dv512_q2_ne4")]] kerne template [[host_name("kernel_flash_attn_ext_vec_f16_dk576_dv512_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; template [[host_name("kernel_flash_attn_ext_vec_f16_dk576_dv512_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #if defined(GGML_METAL_HAS_BF16) -template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +#endif + +#if defined(GGML_METAL_HAS_BF16) +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk32_dv32_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk32_dv32_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk64_dv64_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk64_dv64_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk64_dv64_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk64_dv64_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk64_dv64_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv96_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv96_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv64_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk96_dv64_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q1_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q2_ne1")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q4_ne1")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv128_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv96_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk128_dv96_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv192_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv192_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv192_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv192_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv192_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv128_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv128_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv128_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv128_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk192_dv128_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q1_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q2_ne1")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q4_ne1")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk256_dv256_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk320_dv256_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk320_dv256_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk320_dv256_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk320_dv256_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk320_dv256_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q1_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q2_ne1")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q4_ne1")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk512_dv512_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512_q1_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512_q2_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512_q2_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512_q4_ne2")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; +template [[host_name("kernel_flash_attn_ext_vec_bf16_dk576_dv512_q4_ne4")]] kernel flash_attn_ext_vec_t kernel_flash_attn_ext_vec; #endif #undef FA_TYPES +#undef FA_TYPES_BF #undef FA_TYPES_F32 diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp index 325f727a00c5..ee481f5f37c6 100644 --- a/tests/test-backend-ops.cpp +++ b/tests/test-backend-ops.cpp @@ -15372,6 +15372,8 @@ static std::vector> make_test_cases_eval() { test_cases.emplace_back(new test_flash_attn_ext_kv_rows(64, 2, 1, 1000, 257, 256, 2, GGML_TYPE_F16, true)); test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 1, 1000, 256, 8, 2, GGML_TYPE_BF16)); test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 1, 1000, 256, 256, 2, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_flash_attn_ext_kv_rows(64, 2, 1, 1000, 257, 256, 2, GGML_TYPE_BF16)); + test_cases.emplace_back(new test_flash_attn_ext_kv_rows(96, 2, 1, 1000, 512, 256, 2, GGML_TYPE_BF16)); for (int64_t nb : {1, 3, 8, 64, 512}) { for (int64_t n_slices : {1, 4}) { test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 2, 8, 4096, 1024, nb, n_slices)); @@ -16867,7 +16869,7 @@ static bool run_fa_vec_slice(ggml_backend_t backend, ggml_backend_t backend_cpu, const shape_t shapes[] = { { 128, 128 }, { 576, 512 } }; // mainstream head size + MLA shared K/V view const int ne01_pts[] = { 1, 3 }; // decode, and padded rows for Q=2 and Q=4 const int ne11_pts[] = { 512, 4097 }; // nsg=1, and nsg>=2 together with kvpad - const ggml_type types[] = { GGML_TYPE_F16, GGML_TYPE_Q4_0 }; + const ggml_type types[] = { GGML_TYPE_F16, GGML_TYPE_Q4_0, GGML_TYPE_BF16 }; int n_run = 0; int n_fail = 0; From df636cd876f25b5be76f37db0f40e37a42d5ca5b Mon Sep 17 00:00:00 2001 From: Xuan-Son Nguyen Date: Fri, 4 Dec 2026 12:30:31 +0100 Subject: [PATCH 386/401] server: making signal handler async-signal-safe (#33481) --- tools/server/server-common.cpp | 26 +++++++-- tools/server/server-common.h | 46 ++++++++++------ tools/server/server.cpp | 78 ++++++++++++++++++++------- tools/server/tests/unit/test_basic.py | 22 ++++++++ 4 files changed, 134 insertions(+), 38 deletions(-) diff --git a/tools/server/server-common.cpp b/tools/server/server-common.cpp index af3ecd6cdbcf..19a6b5e03d25 100644 --- a/tools/server/server-common.cpp +++ b/tools/server/server-common.cpp @@ -14,7 +14,9 @@ #include #include +#include #include +#include #include #include #include @@ -2308,7 +2310,7 @@ int server_subproc::read_output(server_subproc_stream stream, char * buf, size_t #endif } -server_subproc::waiter::waiter() { +server_fd_waiter::server_fd_waiter() { #ifndef _WIN32 int fds[2]; GGML_ASSERT(pipe(fds) == 0); @@ -2320,21 +2322,37 @@ server_subproc::waiter::waiter() { #endif } -server_subproc::waiter::~waiter() { +server_fd_waiter::~server_fd_waiter() { #ifndef _WIN32 close((int) wake_fd[0]); close((int) wake_fd[1]); #endif } -void server_subproc::waiter::wake() { +void server_fd_waiter::wake() { #ifndef _WIN32 char c = 1; (void) !write((int) wake_fd[1], &c, 1); #endif } -void server_subproc::waiter::wait(const std::vector & procs, std::vector & ready, int64_t timeout_ms) { +void server_signal_notify(server_fd_waiter & waiter, std::atomic & received, int sig) { + const int saved_errno = errno; // write() in wake() may change it + received.store(sig); + waiter.wake(); + errno = saved_errno; +} + +void server_signal_exit(const char * msg) { +#ifdef _WIN32 + fputs(msg, stderr); +#else + (void) !write(STDERR_FILENO, msg, strlen(msg)); +#endif + std::_Exit(1); +} + +void server_fd_waiter::wait(const std::vector & procs, std::vector & ready, int64_t timeout_ms) { ready.assign(procs.size(), false); #ifdef _WIN32 // no waitable wait exists for anonymous pipes, so poll them in 50 ms steps diff --git a/tools/server/server-common.h b/tools/server/server-common.h index 3d5b3f5ef0d6..a9abcac90c2c 100644 --- a/tools/server/server-common.h +++ b/tools/server/server-common.h @@ -720,6 +720,33 @@ enum server_subproc_stream { // gives the current stdout to the caller as a stream of its own, and sends everything else written to stdout to stderr FILE * server_reserve_stdout(); +struct server_subproc; + +// wait until one of a set of children has output, wake() is called, or a timeout passes +struct server_fd_waiter { + server_fd_waiter(); + ~server_fd_waiter(); + + // thread-safe and async-signal-safe; on Windows this is a no-op, wait() returns within 50 ms anyway + void wake(); + + // timeout_ms < 0 waits until data or wake(); ready[i] is set for each child with data on an open pipe (or a broken pipe) + void wait(const std::vector & procs, std::vector & ready, int64_t timeout_ms); + +private: +#ifndef _WIN32 + intptr_t wake_fd[2] = { -1, -1 }; // POSIX self-pipe +#endif +}; + +// async-signal-safe helpers, to be used inside a signal handler + +// store sig to received, then wake up the waiter +void server_signal_notify(server_fd_waiter & waiter, std::atomic & received, int sig); + +// print msg to stderr, then exit without running the exit handlers +[[noreturn]] void server_signal_exit(const char * msg); + // wrapper around common_subproc to manage a child server process // mainly used by router mode struct server_subproc { @@ -740,24 +767,11 @@ struct server_subproc { // returns the number of bytes read, 0 when nothing is available, -1 when the pipe is closed or broken int read_output(server_subproc_stream stream, char * buf, size_t len); - // wait until one of a set of children has output, wake() is called, or a timeout passes - struct waiter { - waiter(); - ~waiter(); - - // thread-safe; on Windows this is a no-op, wait() returns within 50 ms anyway - void wake(); - - // timeout_ms < 0 waits until data or wake(); ready[i] is set for each child with data on an open pipe (or a broken pipe) - void wait(const std::vector & procs, std::vector & ready, int64_t timeout_ms); - - private: -#ifndef _WIN32 - intptr_t wake_fd[2] = { -1, -1 }; // POSIX self-pipe -#endif - }; + using waiter = server_fd_waiter; private: + friend struct server_fd_waiter; + intptr_t out_handles[SERVER_SUBPROC_STREAMS] = { -1, -1 }; // fd on POSIX, HANDLE on Windows; taken lazily from sproc bool out_closed [SERVER_SUBPROC_STREAMS] = { false, false }; }; diff --git a/tools/server/server.cpp b/tools/server/server.cpp index de5bea8b47bb..1d1774ab5eca 100644 --- a/tools/server/server.cpp +++ b/tools/server/server.cpp @@ -29,15 +29,26 @@ static std::function shutdown_handler; static std::atomic_flag is_terminating = ATOMIC_FLAG_INIT; -static inline void signal_handler(int signal) { +#if !defined (_WIN32) +// shutdown_handler locks mutexes, so it cannot run inside a signal handler +// the signal handler wakes up server_signal_handlers, which calls shutdown_handler +// never freed, so a late signal cannot use a destroyed waiter +static server_fd_waiter * signal_waiter = nullptr; +static std::atomic signal_received{0}; +#endif + +static void signal_handler(int signal) { if (is_terminating.test_and_set()) { // in case it hangs, we can force terminate the server by hitting Ctrl+C twice // this is for better developer experience, we can remove when the server is stable enough - fprintf(stderr, "Received second interrupt, terminating immediately.\n"); - exit(1); + server_signal_exit("Received second interrupt, terminating immediately.\n"); } - +#if defined (_WIN32) + // the console handler runs on its own thread, so it can call shutdown_handler directly shutdown_handler(signal); +#else + server_signal_notify(*signal_waiter, signal_received, signal); +#endif } // how the server is run; everything is on when it is the llama-server binary @@ -342,21 +353,50 @@ static bool server_setup_features( return true; } -static void server_install_signal_handlers() { +// must be declared after the variables used by shutdown_handler, so the thread is joined before they are destroyed +struct server_signal_handlers { + std::thread th; + std::atomic stopping{false}; + + void install() { #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) - struct sigaction sigint_action; - sigint_action.sa_handler = signal_handler; - sigemptyset (&sigint_action.sa_mask); - sigint_action.sa_flags = 0; - sigaction(SIGINT, &sigint_action, NULL); - sigaction(SIGTERM, &sigint_action, NULL); + if (signal_waiter == nullptr) { + signal_waiter = new server_fd_waiter(); + } + th = std::thread([this]() { + std::vector ready; + while (!stopping.load()) { + signal_waiter->wait({}, ready, -1); + const int signal = signal_received.exchange(0); + if (signal != 0) { + shutdown_handler(signal); + } + } + }); + struct sigaction sigint_action; + sigint_action.sa_handler = signal_handler; + sigemptyset (&sigint_action.sa_mask); + sigint_action.sa_flags = 0; + sigaction(SIGINT, &sigint_action, NULL); + sigaction(SIGTERM, &sigint_action, NULL); #elif defined (_WIN32) - auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL { - return (ctrl_type == CTRL_C_EVENT || ctrl_type == CTRL_BREAK_EVENT) ? (signal_handler(SIGINT), true) : false; - }; - SetConsoleCtrlHandler(reinterpret_cast(console_ctrl_handler), true); + auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL { + return (ctrl_type == CTRL_C_EVENT || ctrl_type == CTRL_BREAK_EVENT) ? (signal_handler(SIGINT), true) : false; + }; + SetConsoleCtrlHandler(reinterpret_cast(console_ctrl_handler), true); #endif -} + } + + ~server_signal_handlers() { +#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) + if (th.joinable()) { + stopping.store(true); + signal_waiter->wake(); + th.join(); + } +#endif + } +}; // once the HTTP server listens: log the addresses and spawn llama-connect if asked, so the port is // bound and the child startup health check reaches us. the destructor of connect_proc stops it @@ -611,8 +651,9 @@ static int server_run_router(common_params & params, int argc, char ** argv, con return 1; } + server_signal_handlers sig_handlers; if (opts.install_signal_handlers) { - server_install_signal_handlers(); + sig_handlers.install(); } server_connect connect_proc; @@ -784,8 +825,9 @@ static int server_run_instance(common_params & params, server_role & role, commo ctx_server.terminate(); }; + server_signal_handlers sig_handlers; if (opts.install_signal_handlers) { - server_install_signal_handlers(); + sig_handlers.install(); } server_connect connect_proc; diff --git a/tools/server/tests/unit/test_basic.py b/tools/server/tests/unit/test_basic.py index 4cb21905fb77..c1157b2a07f1 100644 --- a/tools/server/tests/unit/test_basic.py +++ b/tools/server/tests/unit/test_basic.py @@ -3,6 +3,7 @@ import signal import socket import sys +import time from utils import * server = ServerPreset.tinyllama2() @@ -190,3 +191,24 @@ def test_server_sigterm_during_request(): # the client keeps the connection open, so the HTTP thread must not wait for a result forever assert server.process.wait(timeout=10) == 0 stream.close() + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX signal") +def test_server_second_sigterm(): + global server + server.start() + # a client that sends only part of a request holds the shutdown until the read timeout + sock = socket.create_connection((server.server_host, server.server_port)) + sock.sendall(b"POST /completion HTTP/1.1\r\nHost: localhost\r\nContent-Length: 100\r\n\r\n{") + # connections are accepted in order, so the one above is accepted once this one is served + assert server.make_request("GET", "/health").status_code == 200 + server.process.send_signal(signal.SIGTERM) + # signals of the same type are merged if one is still pending, so wait for the listener to stop first + with pytest.raises(requests.exceptions.RequestException): + for _ in range(300): + requests.get(server.make_url("/health"), timeout=1) + time.sleep(0.1) + server.process.send_signal(signal.SIGTERM) + # exit code 1 means the second signal forced the exit + assert server.process.wait(timeout=10) == 1 + sock.close() From d293b7dad189d01344efb3784be2c6021788af67 Mon Sep 17 00:00:00 2001 From: Md Raihanul Haque Rahi <52377279+RaihanulHaque@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:51:27 +0600 Subject: [PATCH 387/401] llama : return an error instead of aborting when a batch exceeds n_batch or n_ubatch (#30523) * llama : return an error instead of aborting when a batch exceeds n_batch or n_ubatch llama_decode documents -1 for an invalid batch, but a batch larger than n_batch (or n_ubatch for non-causal) hit a GGML_ASSERT and aborted the process. A causal context caps n_batch at n_ctx, so a caller that asks for n_batch > n_ctx and submits a full batch crashes. This was found in an application that embeds llama.cpp, where a small context made an audio/image prompt abort the app instead of failing the call. Return -1 with an error message instead, before any state is touched, and add the batch_big case to test-llama-context: it submits n_max + 1 tokens, expects an error and an empty memory, then decodes n_max tokens. * llama : drop the batch_big test and shorten the n_batch error message (review) --- src/llama-context.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 8de28ed38844..54b30f8e29e0 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -2236,7 +2236,11 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { } } - GGML_ASSERT(n_tokens_all <= cparams.n_batch); + if (n_tokens_all > cparams.n_batch) { + LLAMA_LOG_ERROR("%s: n_tokens = %u exceeds n_batch = %u\n", + __func__, n_tokens_all, cparams.n_batch); + return -1; + } if (llm_graph_pools_spans(cparams) && balloc->get_n_spans() > LLAMA_MAX_POOL_SPANS) { LLAMA_LOG_ERROR("%s: too many spans to pool, n_spans = %u > %d\n", __func__, balloc->get_n_spans(), LLAMA_MAX_POOL_SPANS); @@ -2250,7 +2254,11 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { return -1; } - GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens"); + if (!cparams.causal_attn && n_tokens_all > cparams.n_ubatch) { + LLAMA_LOG_ERROR("%s: non-causal attention requires n_ubatch >= n_tokens (n_ubatch = %u, n_tokens = %u)\n", + __func__, cparams.n_ubatch, n_tokens_all); + return -1; + } // TODO: this clear of the buffer can easily be forgotten - need something better // sync first so any in-flight async copies into embd_seq complete before it is freed From 8b42ea7ed04fde8e42620ff2267d817b5a758469 Mon Sep 17 00:00:00 2001 From: Ahmed Mohammed Date: Fri, 4 Dec 2026 07:01:38 -0500 Subject: [PATCH 388/401] model : apply control vectors in hy_v4 and hy_v4_flash (#33644) --- src/models/hy-v4-flash.cpp | 1 + src/models/hy-v4.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/src/models/hy-v4-flash.cpp b/src/models/hy-v4-flash.cpp index ff340a41f4fc..76e950962fed 100644 --- a/src/models/hy-v4-flash.cpp +++ b/src/models/hy-v4-flash.cpp @@ -1049,6 +1049,7 @@ llama_model_hy_v4_flash::graph::graph(const llama_model & model, const llm_graph cb(cur, "ffn_out", il); inpL = build_hc_post(cur, residual, ffn_hc.post, il); + inpL = build_cvec(inpL, il); cb(inpL, "l_out", il); } diff --git a/src/models/hy-v4.cpp b/src/models/hy-v4.cpp index 88465f70fef6..08291d392b41 100644 --- a/src/models/hy-v4.cpp +++ b/src/models/hy-v4.cpp @@ -562,6 +562,7 @@ llama_model_hy_v4::graph::graph(const llm_graph_params & params) : } inpL = build_hc_post(cur, residual, ffn_hc.post, il); + inpL = build_cvec(inpL, il); cb(inpL, "l_out", il); } From 017c3a785bf2118947b3593f5f7696d4225f0306 Mon Sep 17 00:00:00 2001 From: Marin Radic Date: Fri, 4 Dec 2026 13:17:44 +0100 Subject: [PATCH 389/401] ggml-et : fix global barrier shire fan-out and pin counter to .data (#33478) --- ggml/src/ggml-et/et-kernels/src/platform.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/ggml/src/ggml-et/et-kernels/src/platform.h b/ggml/src/ggml-et/et-kernels/src/platform.h index 2ea9592a394c..1baeb0236662 100644 --- a/ggml/src/ggml-et/et-kernels/src/platform.h +++ b/ggml/src/ggml-et/et-kernels/src/platform.h @@ -193,9 +193,8 @@ typedef enum { // The counter lives in a cache-line-aligned global to avoid coherency problems //****************************************************************************** -// Barrier counter cache-line aligned to avoid coherency problems -// Must be zero-initialized (BSS). -static uint32_t __attribute__((aligned(64))) et_global_barrier_count[64 / sizeof(uint32_t)] = { 0 }; +// Cache-line aligned barrier counter pinned to .data because crt.S does not zero .bss (NOLOAD). +static uint32_t __attribute__((aligned(64), section(".data"))) et_global_barrier_count[64 / sizeof(uint32_t)] = { 0 }; // Cross-shire barrier: all harts in num_active_shires shires synchronize. // Returns 1 if this hart was the globally-last to arrive, 0 otherwise. @@ -217,14 +216,15 @@ static inline uint64_t __attribute__((always_inline)) et_barrier_global(uint64_t uint32_t prev = et_global_add_w(et_global_barrier_count, 1); if (prev == num_active_shires - 1) { - // Last shire. reset counter and fan out FCC to all shires + // Last shire: reset counter and fan out FCC 1 to participating shires only. + // Master shire (32) firmware never drains FCC 1, so do not credit it unless included. last_global = 1; et_global_swap_w(et_global_barrier_count, 0); - for (uint64_t sid = 0; sid < 33; sid++) { - // Send FCC 1 credit to all harts (both threads) in each shire - fcc_send(sid, THREAD_0, FCC_1, 0xFFFFFFFF); - fcc_send(sid, THREAD_1, FCC_1, 0xFFFFFFFF); + for (uint64_t sid = 0; sid < num_active_shires; sid++) { + uint32_t mask = (sid == SHIRE_MASTER) ? 0xFFFF0000U : 0xFFFFFFFFU; + fcc_send(sid, THREAD_0, FCC_1, mask); + fcc_send(sid, THREAD_1, FCC_1, mask); } } } From 4694eccda0616206bebfb77c0f64c5b182e459b3 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Fri, 4 Dec 2026 14:12:57 +0100 Subject: [PATCH 390/401] ui: file a conversation away with Archive, from its menus and in bulk (#33328) * ui: file a conversation away with Archive, from its menus and in bulk The "more actions" dropdown and the right-click menu of a conversation gain Archive, next to Pin. A filed-away chat leaves the sidebar's sections - Pinned, the groups and Ungrouped - and rests out of them; the search dialog is where it is found, behind a "Show N archived" toggle under the chats a query matched, its own Archived group among the results. The bulk selection bar gains the same action for a whole selection: Archive over any selection with a chat left in it, Restore once every selected chat rests in the archive. Archiving keeps a chat's pin and group, so restoring puts it back where it was, and a move that gives it a home elsewhere - a pin, a group, a drop on Pinned or on Recent - brings it back too, so such an action on a filed-away chat never reads as doing nothing. Assisted-by: Claude * ui: fix archive selection, restore path and fork families Select all, the selection count and shift or marquee ranges only take the chats the sidebar shows, and archiving drops what left the sidebar from the selection, so a bulk delete never reaches a hidden chat. Writing in an archived chat brings it back, which gives it a way back when conversation tabs are off, the default and the only option on a phone. The bulk Restore path, which no selection could reach, is gone. Archiving and restoring take the whole fork family, like moving into a group, and an archived chat no longer shows twice in search. * ui: count the whole fork family in the archive toast The bulk write takes the family, so the toast reports the family's size rather than the clicked selection, which a single chat with forks would otherwise report as one conversation while several leave the sidebar. Assisted-by: Claude --------- Co-authored-by: Pascal --- .../dialogs/DialogConversationArchive.svelte | 23 ++ .../app/dialogs/DialogSearch.svelte | 91 +++++++- .../src/lib/components/app/dialogs/index.ts | 17 ++ .../app/navigation/ConversationActions.svelte | 18 ++ .../SidebarNavigation.svelte | 52 ++++- .../SidebarNavigationConversationList.svelte | 44 +++- .../SidebarNavigationSelectionBar.svelte | 41 +++- .../lib/components/app/navigation/index.ts | 9 +- .../chat/src/lib/services/database.service.ts | 36 ++- .../chat/src/lib/stores/chat/index.svelte.ts | 4 + .../lib/stores/conversations/index.svelte.ts | 86 ++++++-- ui/apps/chat/src/lib/stores/ui.svelte.ts | 8 + ui/apps/chat/src/lib/types/database.d.ts | 2 + ui/apps/chat/src/routes/search/+page.svelte | 5 +- ...idebar-conversation-archive.svelte.test.ts | 162 ++++++++++++++ .../SidebarNavigation.stories.svelte | 27 +++ .../tests/unit/conversation-archive.test.ts | 207 ++++++++++++++++++ 17 files changed, 788 insertions(+), 44 deletions(-) create mode 100644 ui/apps/chat/src/lib/components/app/dialogs/DialogConversationArchive.svelte create mode 100644 ui/apps/chat/tests/client/sidebar-conversation-archive.svelte.test.ts create mode 100644 ui/apps/chat/tests/unit/conversation-archive.test.ts diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogConversationArchive.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogConversationArchive.svelte new file mode 100644 index 000000000000..6400a716f2cb --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogConversationArchive.svelte @@ -0,0 +1,23 @@ + + + diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte index a952faeb5ed0..3dd87437377f 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte +++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte @@ -1,6 +1,7 @@ @@ -228,6 +246,7 @@ import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox'; - import { Download, Pin, PinOff, Trash2, X } from '@lucide/svelte'; - import { ActionIcon, DialogConfirmation } from '#lib/components/app/index.ts'; + import { Archive, Download, Pin, PinOff, Trash2, X } from '@lucide/svelte'; + import { + ActionIcon, + DialogConfirmation, + DialogConversationArchive + } from '#lib/components/app/index.ts'; import { TooltipSide } from '#lib/enums/index.ts'; interface Props { @@ -13,6 +17,7 @@ someSelectedPinned: boolean; pinStateIsMixed: boolean; onSelectAllToggle: () => void; + onBulkArchive: () => void; onBulkPinToggle: () => void; onBulkExport: () => void; onBulkDelete: () => void; @@ -22,6 +27,7 @@ let { allVisibleSelected, class: className = '', + onBulkArchive, onBulkDelete, onBulkExport, onBulkPinToggle, @@ -35,11 +41,17 @@ }: Props = $props(); let showDeleteDialog = $state(false); + let showArchiveDialog = $state(false); function handleDeleteClick() { showDeleteDialog = true; } + // filing a selection away takes it out of the sidebar, so it asks first + function handleArchiveClick() { + showArchiveDialog = true; + } + function handleDeleteConfirm() { showDeleteDialog = false; onBulkDelete(); @@ -68,6 +80,8 @@ ); const pinDisabled = $derived(!hasSelection || pinStateIsMixed); + + const archiveTooltip = $derived(selectedCount > 1 ? 'Archive all' : 'Archive');
+ + { + const cleanIds = ids.filter((id): id is string => typeof id === 'string' && id.length > 0); + + if (cleanIds.length === 0) return; + + await db.transaction('rw', db[IDXDB_TABLES.conversations], async () => { + const convs = await db[IDXDB_TABLES.conversations].bulkGet(cleanIds); + const updates = convs + .filter((conv): conv is DatabaseConversation => !!conv) + .map((conv) => ({ ...conv, archived })); + + if (updates.length === 0) return; + + await db[IDXDB_TABLES.conversations].bulkPut(updates); + }); + } + /** * Toggles the pinned status of each conversation in `ids` inside a single * transaction. Treats `pinned === undefined` as `false`, matching the @@ -120,8 +145,12 @@ export class DatabaseService { if (!conv) continue; const newPinned = !conv.pinned; + const updated: DatabaseConversation = { ...conv, pinned: newPinned }; - updates.push({ ...conv, pinned: newPinned }); + // a pinned chat shows under Pinned, which files no archived chat away + if (newPinned) delete updated.archived; + + updates.push(updated); result.set(cleanIds[i], newPinned); } @@ -639,7 +668,8 @@ export class DatabaseService { /** * Puts conversations into a group, or out of any group when `groupId` is null. - * A conversation that joins a group is unpinned. + * A conversation that joins a group is unpinned and no longer archived, since a + * group section shows neither. * * @param ids - Conversation IDs * @param groupId - Target group, null to take them out of their group @@ -653,6 +683,8 @@ export class DatabaseService { conversation.groupId = groupId; if (conversation.pinned) conversation.pinned = false; + + if (conversation.archived) conversation.archived = false; } else { delete conversation.groupId; } diff --git a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts index dfbdadd06d17..9cbf913729f5 100644 --- a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts @@ -783,6 +783,10 @@ class ChatStore implements ChatStreamHost, ChatFlowsHost { const activeConv = conversationsStore.activeConversation; + // writing in a filed-away chat brings it back to the sidebar, with or without its tab + if (activeConv?.archived) + await conversationsStore.setConversationArchived(activeConv.id, false); + // If agentic loop is running, inject as a steering message instead of starting a new flow if (activeConv && agenticStore.isRunning(activeConv.id)) { agenticStore.injectSteeringMessage(activeConv.id, content, extras); diff --git a/ui/apps/chat/src/lib/stores/conversations/index.svelte.ts b/ui/apps/chat/src/lib/stores/conversations/index.svelte.ts index 18636bab8413..e66913584a8a 100644 --- a/ui/apps/chat/src/lib/stores/conversations/index.svelte.ts +++ b/ui/apps/chat/src/lib/stores/conversations/index.svelte.ts @@ -227,7 +227,42 @@ class ConversationsStore implements ConversationsPreferencesHost { } /** - * Toggles the pinned state of each conversation individually. + * Sets the archived state of each conversation, filing them away out of the + * sidebar's sections or bringing them back. A chat's pin and group are kept + * as they are, so restoring one puts it back where it was. + * + * @param convIds - Conversation IDs to set + * @param archived - True to file them away, false to bring them back + */ + async bulkSetConversationsArchived(convIds: string[], archived: boolean): Promise { + if (convIds.length === 0) return; + + const ids = [...new Set(convIds.flatMap((id) => collectForkFamily(this.conversations, id)))]; + + try { + await DatabaseService.bulkSetConversationsArchived(ids, archived); + + for (const id of ids) this.applyConversationUpdate(id, { archived }); + + // the toast counts the whole family the write took, not just the clicked chats + if (ids.length === 1) { + toast.success(archived ? 'Conversation archived' : 'Conversation restored'); + + return; + } + + toast.success( + archived ? `Archived ${ids.length} conversations` : `Restored ${ids.length} conversations` + ); + } catch (error) { + console.error('Failed to bulk set archived state:', error); + toast.error(archived ? 'Failed to archive conversations' : 'Failed to restore conversations'); + } + } + + /** + * Toggles the pinned state of each conversation individually. A chat that + * becomes pinned is brought back from the archive, as Pinned shows none. * Mixed-pin selections are intentionally not normalised here; the bulk * action UI surfaces them as a disabled mixed-state instead. * @param convIds - Conversation IDs to toggle @@ -237,16 +272,13 @@ class ConversationsStore implements ConversationsPreferencesHost { try { const updates = await DatabaseService.bulkToggleConversationPins(convIds); - const activeId = this.activeConversation?.id; - - if (this.activeConversation && activeId && updates.has(activeId)) { - this.activeConversation.pinned = updates.get(activeId)!; - } - - for (let i = 0; i < this.conversations.length; i++) { - const newPinned = updates.get(this.conversations[i].id); - if (newPinned !== undefined) this.conversations[i].pinned = newPinned; + for (const [convId, newPinned] of updates) { + // a pinned chat shows under Pinned, which files no archived chat away + this.applyConversationUpdate( + convId, + newPinned ? { archived: false, pinned: true } : { pinned: false } + ); } toast.success( @@ -704,10 +736,32 @@ class ConversationsStore implements ConversationsPreferencesHost { return undefined; } + /** + * Files a conversation away out of the sidebar's sections, or brings it back, with its + * whole fork family so a family never splits across the archive. Archiving keeps the + * chats' pin and group, so restoring puts them back where they were; a chat's menu, or + * writing in it again, is what restores it. + * + * @param convId - The conversation to file away or bring back + * @param archived - True to archive, false to restore + */ + async setConversationArchived(convId: string, archived: boolean): Promise { + const ids = collectForkFamily(this.conversations, convId); + + try { + await DatabaseService.bulkSetConversationsArchived(ids, archived); + + for (const id of ids) this.applyConversationUpdate(id, { archived }); + } catch (error) { + console.error('Failed to archive conversation:', error); + } + } + /** * Moves a conversation with its whole fork family into a group, or out of one * when `groupId` is null: a family never splits across sections. A pinned chat - * that joins a group leaves Pinned, since group sections do not show pinned chats. + * that joins a group leaves Pinned, since group sections do not show pinned chats, + * and an archived one comes back, since they do not show archived chats either. * * @param convId - Conversation to move * @param groupId - Target group, null to take the conversations out of their group @@ -723,7 +777,8 @@ class ConversationsStore implements ConversationsPreferencesHost { this.applyConversationUpdate(conversation.id, { groupId: groupId ?? undefined, - ...(groupId && conversation.pinned ? { pinned: false } : {}) + ...(groupId && conversation.pinned ? { pinned: false } : {}), + ...(groupId && conversation.archived ? { archived: false } : {}) }); } } catch (error) { @@ -739,7 +794,9 @@ class ConversationsStore implements ConversationsPreferencesHost { } /** - * Toggles the pinned status of a conversation. + * Toggles the pinned status of a conversation. Pinning one that is archived + * brings it back, since the Pinned section is where a pinned chat shows. + * * @param convId - The conversation ID to toggle * @returns The new pinned status */ @@ -747,6 +804,9 @@ class ConversationsStore implements ConversationsPreferencesHost { try { const newPinnedState = await DatabaseService.toggleConversationPin(convId); + if (newPinnedState && this.conversations.find((c) => c.id === convId)?.archived) + await this.setConversationArchived(convId, false); + this.applyConversationUpdate(convId, { pinned: newPinnedState }); return newPinnedState; diff --git a/ui/apps/chat/src/lib/stores/ui.svelte.ts b/ui/apps/chat/src/lib/stores/ui.svelte.ts index 23b1e36bfb12..6e92d856b2dc 100644 --- a/ui/apps/chat/src/lib/stores/ui.svelte.ts +++ b/ui/apps/chat/src/lib/stores/ui.svelte.ts @@ -81,6 +81,9 @@ class UiStore { /** Set when a flow outside the chat wants the composer focused once it can take it. */ composerFocusRequested = $state(false); + /** Conversation the archive dialog asks about, `null` while closed. */ + conversationArchiveId = $state(null); + /** Conversation the delete dialog asks about, `null` while closed. */ conversationDeleteId = $state(null); @@ -208,6 +211,11 @@ class UiStore { return !this.collapsedSidebarSections.has(id); } + /** Ask to file a conversation away, from any of its menus. */ + openConversationArchive(conversationId: string): void { + this.conversationArchiveId = conversationId; + } + /** Ask to delete a conversation, from any of its menus. */ openConversationDelete(conversationId: string): void { this.conversationDeleteId = conversationId; diff --git a/ui/apps/chat/src/lib/types/database.d.ts b/ui/apps/chat/src/lib/types/database.d.ts index e47d60fffb7c..827c3897e093 100644 --- a/ui/apps/chat/src/lib/types/database.d.ts +++ b/ui/apps/chat/src/lib/types/database.d.ts @@ -27,6 +27,8 @@ export interface DatabaseConversation { /** Tool categories disabled for this conversation */ disabledToolCategories?: ToolSource[]; forkedFromConversationId?: string; + /** Out of every sidebar section, found through the search dialog, its pin and group kept. */ + archived?: boolean; /** Sidebar group the conversation is sorted into. */ groupId?: string; pinned?: boolean; diff --git a/ui/apps/chat/src/routes/search/+page.svelte b/ui/apps/chat/src/routes/search/+page.svelte index c442b2f1404f..98ca2816a642 100644 --- a/ui/apps/chat/src/routes/search/+page.svelte +++ b/ui/apps/chat/src/routes/search/+page.svelte @@ -21,7 +21,10 @@ if (query.length === 0) return []; - return conversationsStore.conversations.filter((c) => c.name.toLowerCase().includes(query)); + // a filed-away chat rests out of the results; the search dialog is where it is found + return conversationsStore.conversations.filter( + (c) => !c.archived && c.name.toLowerCase().includes(query) + ); }); // Search page is intended for mobile; on desktop the sidebar already exposes diff --git a/ui/apps/chat/tests/client/sidebar-conversation-archive.svelte.test.ts b/ui/apps/chat/tests/client/sidebar-conversation-archive.svelte.test.ts new file mode 100644 index 000000000000..35c504f4306d --- /dev/null +++ b/ui/apps/chat/tests/client/sidebar-conversation-archive.svelte.test.ts @@ -0,0 +1,162 @@ +// A conversation filed away from its menu leaves the sidebar's sections entirely: it +// shows in no section, pinned or otherwise, and the search dialog is where it is found +// and brought back. Its menu reads "Restore" on any row that still shows it. + +import '../../src/app.css'; +import SidebarNavigationHarness from './components/SidebarNavigationHarness.svelte'; +import { SIDEBAR_SECTION_IDS, UI_DATA_ATTRS } from '#lib/constants/index.ts'; +import { conversationsStore, uiStore } from '#lib/stores/index.ts'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { page } from 'vitest/browser'; +import { render } from 'vitest-browser-svelte'; + +const DESKTOP = { height: 900, width: 1280 }; +const TRIGGER_NAME = 'More actions'; +const LOOSE = 'loose'; +const AWAY = 'archived'; +const AWAY_PINNED = 'pinned-away'; + +/** A loose chat, one filed away, and one that is both filed away and pinned. */ +function conversations(): DatabaseConversation[] { + return [ + { currNode: null, id: LOOSE, lastModified: 3000, name: 'A chat left in the list' }, + { archived: true, currNode: null, id: AWAY, lastModified: 2000, name: 'A chat filed away' }, + { + archived: true, + currNode: null, + id: AWAY_PINNED, + lastModified: 1000, + name: 'A pinned chat filed away', + pinned: true + } + ]; +} + +/** The sidebar rows of one chat; a row mid-slide belongs to two sections at once. */ +function rowsOf(convId: string): HTMLElement[] { + return [ + ...document.querySelectorAll(`[${UI_DATA_ATTRS.CONVERSATION_ROW}="${convId}"]`) + ]; +} + +/** Whether the sidebar shows that chat inside that section. */ +function holds(sectionId: string, convId: string): boolean { + const rows = rowsOf(convId); + const [row] = rows; + + return rows.length === 1 && Boolean(row?.closest(`[data-sidebar-section="${sectionId}"]`)); +} + +/** The one row the sidebar shows for that chat. */ +async function rowOf(convId: string): Promise { + await expect.poll(() => rowsOf(convId).length).toBe(1); + + const [row] = rowsOf(convId); + + if (!row) throw new Error(`the sidebar shows no row for ${convId}`); + + return row; +} + +/** + * Open a row's "more actions" dropdown. Its trigger renders with the hover, and the pointer + * never lands on a sidebar row in the tester's frame, so the hover is dispatched by hand - + * as is the click, since a menu opened this way is not under the pointer. + */ +async function openRowDropdown(convId: string): Promise { + const row = await rowOf(convId); + const trigger = () => row.querySelector('.actions button'); + + row.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + + await expect.poll(() => trigger()?.textContent?.trim()).toBe(TRIGGER_NAME); + + trigger()?.click(); +} + +/** The named action of the menu that is open. */ +async function clickMenuItem(label: string): Promise { + const item = page.getByRole('menuitem', { name: label }); + + await expect.element(item).toBeVisible(); + + const element = item.element(); + + if (!(element instanceof HTMLElement)) throw new Error(`${label} is not a menu item`); + + element.click(); +} + +describe('archived conversation in the sidebar', () => { + beforeEach(async () => { + await page.viewport(DESKTOP.width, DESKTOP.height); + + uiStore.isSidebarExpanded = true; + conversationsStore.activeConversation = null; + conversationsStore.conversations = conversations(); + }); + + it('shows no row for the chats filed away, in any section', async () => { + render(SidebarNavigationHarness); + + await expect.poll(() => holds(SIDEBAR_SECTION_IDS.RECENT, LOOSE)).toBe(true); + + // the filed-away chats rest out of the list entirely, pinned one included + expect(rowsOf(AWAY)).toHaveLength(0); + expect(rowsOf(AWAY_PINNED)).toHaveLength(0); + + // Pinned shows no filed-away chat, so with only those it is not a section at all + const pinned = document.querySelector(`[data-sidebar-section="${SIDEBAR_SECTION_IDS.PINNED}"]`); + + expect(pinned).toBeNull(); + }); + + it('files a chat away from its dropdown, out of every section', async () => { + render(SidebarNavigationHarness); + + await expect.poll(() => holds(SIDEBAR_SECTION_IDS.RECENT, LOOSE)).toBe(true); + + await openRowDropdown(LOOSE); + await clickMenuItem('Archive'); + + // filing away asks first: the confirmation is what takes the chat out + const confirm = page.getByRole('button', { name: 'Archive' }); + + await expect.element(confirm).toBeVisible(); + + const element = confirm.element(); + + if (!(element instanceof HTMLElement)) throw new Error('Archive is not a button'); + + element.click(); + + await expect.poll(() => rowsOf(LOOSE)).toHaveLength(0); + expect(conversationsStore.conversations.find((c) => c.id === LOOSE)?.archived).toBe(true); + }); + + it('leaves the chats filed away out of the selection', async () => { + render(SidebarNavigationHarness); + + const row = await rowOf(LOOSE); + + row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })); + + await clickMenuItem('Select'); + + // the one chat the sidebar shows is the whole selection, so Select all has nothing to add + await expect + .element(page.getByRole('toolbar', { name: 'Bulk actions for selected conversations' })) + .toHaveTextContent('1 / 1 selected'); + await expect.element(page.getByRole('checkbox', { name: 'Deselect all' })).toBeVisible(); + }); + + it('offers the same action in the row context menu', async () => { + render(SidebarNavigationHarness); + + const row = await rowOf(LOOSE); + + row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true })); + + await expect.element(page.getByRole('menuitem', { name: 'Archive' })).toBeVisible(); + }); +}); diff --git a/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte b/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte index 8c4f05ca8098..ad06bf7befaa 100644 --- a/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte +++ b/ui/apps/chat/tests/stories/navigation/SidebarNavigation.stories.svelte @@ -46,6 +46,15 @@ name: 'Math Problem Solving' } ]; + + // the same chats, the two oldest filed away: they leave the sidebar entirely, + // and the search dialog is the one place that still finds them + const mockArchivedConversations: DatabaseConversation[] = mockConversations.map( + (conversation, index) => ({ + ...conversation, + ...(index >= 3 ? { archived: true } : {}) + }) + );
+ + { + const { conversationsStore } = await import('#lib/stores/conversations/index.svelte.ts'); + + waitFor(() => + setTimeout(() => { + conversationsStore.conversations = mockArchivedConversations; + }, 0) + ); + }} +> +
+ +
+
diff --git a/ui/apps/chat/tests/unit/conversation-archive.test.ts b/ui/apps/chat/tests/unit/conversation-archive.test.ts new file mode 100644 index 000000000000..1b2a82b01dfb --- /dev/null +++ b/ui/apps/chat/tests/unit/conversation-archive.test.ts @@ -0,0 +1,207 @@ +// Archiving files a conversation away with its fork family, out of the Pinned, group +// and Ungrouped sections, and keeps its pin and group so a restore puts +// it back where it was. A chat given a home elsewhere instead - pinned, or moved into a +// group - comes back on its own, so such an action on a filed-away chat never reads as +// doing nothing. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: { + bulkSetConversationsArchived: vi.fn(), + bulkToggleConversationPins: vi.fn(), + setConversationsGroup: vi.fn(), + toggleConversationPin: vi.fn() + } +})); + +import { DatabaseService } from '#lib/services/database.service.ts'; +import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts'; +import type { DatabaseConversation } from '#lib/types/database.js'; + +const bulkSetConversationsArchivedMock = vi.mocked(DatabaseService.bulkSetConversationsArchived); +const bulkToggleConversationPinsMock = vi.mocked(DatabaseService.bulkToggleConversationPins); +const setConversationsGroupMock = vi.mocked(DatabaseService.setConversationsGroup); +const toggleConversationPinMock = vi.mocked(DatabaseService.toggleConversationPin); + +function makeConversation(overrides: Partial = {}): DatabaseConversation { + return { + currNode: null, + id: 'conv-1', + lastModified: 1000, + name: 'conversation', + ...overrides + }; +} + +/** One row in the list, and the same object as the active conversation. */ +function showConversation(overrides: Partial = {}) { + const conversation = makeConversation(overrides); + + conversationsStore.conversations = [conversation]; + conversationsStore.activeConversation = conversation; + + return conversation; +} + +beforeEach(() => { + bulkSetConversationsArchivedMock.mockReset(); + bulkSetConversationsArchivedMock.mockResolvedValue(undefined); + + bulkToggleConversationPinsMock.mockReset(); + bulkToggleConversationPinsMock.mockResolvedValue(new Map()); + + setConversationsGroupMock.mockReset(); + setConversationsGroupMock.mockResolvedValue(undefined); + + toggleConversationPinMock.mockReset(); + toggleConversationPinMock.mockResolvedValue(false); + + conversationsStore.conversations = []; + conversationsStore.activeConversation = null; +}); + +describe('setConversationArchived', () => { + it('writes the flag through and mirrors it into the row', async () => { + showConversation(); + + await conversationsStore.setConversationArchived('conv-1', true); + + expect(bulkSetConversationsArchivedMock).toHaveBeenCalledWith(['conv-1'], true); + expect(conversationsStore.conversations[0]?.archived).toBe(true); + }); + + it('mirrors the flag into the active conversation as well', async () => { + showConversation(); + + await conversationsStore.setConversationArchived('conv-1', true); + + expect(conversationsStore.activeConversation?.archived).toBe(true); + }); + + it('brings the chat back with false', async () => { + showConversation({ archived: true }); + + await conversationsStore.setConversationArchived('conv-1', false); + + expect(bulkSetConversationsArchivedMock).toHaveBeenCalledWith(['conv-1'], false); + expect(conversationsStore.conversations[0]?.archived).toBe(false); + }); + + it('files the whole fork family away together', async () => { + conversationsStore.conversations = [ + makeConversation(), + makeConversation({ forkedFromConversationId: 'conv-1', id: 'conv-2' }) + ]; + + await conversationsStore.setConversationArchived('conv-2', true); + + expect(bulkSetConversationsArchivedMock).toHaveBeenCalledWith(['conv-1', 'conv-2'], true); + expect(conversationsStore.conversations.every((c) => c.archived)).toBe(true); + }); + + it('keeps the row as it is when the write fails', async () => { + showConversation(); + bulkSetConversationsArchivedMock.mockRejectedValue(new Error('IndexedDB is closed')); + + await conversationsStore.setConversationArchived('conv-1', true); + + expect(conversationsStore.conversations[0]?.archived).toBeUndefined(); + }); +}); + +describe('bulkSetConversationsArchived', () => { + it('writes the flag through for the whole selection and mirrors it into the rows', async () => { + const first = makeConversation({ id: 'conv-1' }); + const second = makeConversation({ archived: true, id: 'conv-2' }); + + conversationsStore.conversations = [first, second]; + conversationsStore.activeConversation = first; + + await conversationsStore.bulkSetConversationsArchived(['conv-1', 'conv-2'], true); + + expect(bulkSetConversationsArchivedMock).toHaveBeenCalledWith(['conv-1', 'conv-2'], true); + expect(first.archived).toBe(true); + expect(second.archived).toBe(true); + expect(conversationsStore.activeConversation?.archived).toBe(true); + }); + + it('brings the selection back with false', async () => { + showConversation({ archived: true }); + + await conversationsStore.bulkSetConversationsArchived(['conv-1'], false); + + expect(bulkSetConversationsArchivedMock).toHaveBeenCalledWith(['conv-1'], false); + expect(conversationsStore.conversations[0]?.archived).toBe(false); + }); + + it('does nothing for an empty selection', async () => { + showConversation(); + + await conversationsStore.bulkSetConversationsArchived([], true); + + expect(bulkSetConversationsArchivedMock).not.toHaveBeenCalled(); + expect(conversationsStore.conversations[0]?.archived).toBeUndefined(); + }); + + it('keeps the rows as they are when the write fails', async () => { + showConversation(); + bulkSetConversationsArchivedMock.mockRejectedValue(new Error('IndexedDB is closed')); + + await conversationsStore.bulkSetConversationsArchived(['conv-1'], true); + + expect(conversationsStore.conversations[0]?.archived).toBeUndefined(); + }); +}); + +describe('a filed-away chat given a home elsewhere', () => { + it('comes back when it is pinned, which files it under Pinned', async () => { + showConversation({ archived: true }); + toggleConversationPinMock.mockResolvedValue(true); + + await conversationsStore.toggleConversationPin('conv-1'); + + expect(bulkSetConversationsArchivedMock).toHaveBeenCalledWith(['conv-1'], false); + expect(conversationsStore.conversations[0]?.archived).toBe(false); + expect(conversationsStore.conversations[0]?.pinned).toBe(true); + }); + + it('stays filed away when its pin is taken off it', async () => { + showConversation({ archived: true, pinned: true }); + toggleConversationPinMock.mockResolvedValue(false); + + await conversationsStore.toggleConversationPin('conv-1'); + + expect(bulkSetConversationsArchivedMock).not.toHaveBeenCalled(); + expect(conversationsStore.conversations[0]?.archived).toBe(true); + }); + + it('comes back when a selection pins it too', async () => { + showConversation({ archived: true }); + bulkToggleConversationPinsMock.mockResolvedValue(new Map([['conv-1', true]])); + + await conversationsStore.bulkToggleConversationPin(['conv-1']); + + expect(conversationsStore.conversations[0]?.archived).toBe(false); + expect(conversationsStore.conversations[0]?.pinned).toBe(true); + expect(conversationsStore.activeConversation?.archived).toBe(false); + }); + + it('comes back when it joins a group, which shows no archived chat either', async () => { + showConversation({ archived: true }); + + await conversationsStore.setConversationGroup('conv-1', 'group-1'); + + expect(setConversationsGroupMock).toHaveBeenCalledWith(['conv-1'], 'group-1'); + expect(conversationsStore.conversations[0]?.archived).toBe(false); + }); + + it('stays filed away when it only leaves its group', async () => { + showConversation({ archived: true, groupId: 'group-1' }); + + await conversationsStore.setConversationGroup('conv-1', null); + + expect(conversationsStore.conversations[0]?.archived).toBe(true); + expect(conversationsStore.conversations[0]?.groupId).toBeUndefined(); + }); +}); From 78ab1ed222410777bc1431254de47f2fae04428f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigbj=C3=B8rn=20Skj=C3=A6ret?= Date: Fri, 4 Dec 2026 14:16:18 +0100 Subject: [PATCH 391/401] opencl : fix build (#33691) --- ggml/src/ggml-opencl/ops/flash_attn.cpp | 2 ++ ggml/src/ggml-opencl/ops/mul_mat.cpp | 2 ++ ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp | 2 ++ ggml/src/ggml-opencl/ops/mul_mat_id.cpp | 1 + 4 files changed, 7 insertions(+) diff --git a/ggml/src/ggml-opencl/ops/flash_attn.cpp b/ggml/src/ggml-opencl/ops/flash_attn.cpp index ac533f776ec5..f25882667e35 100644 --- a/ggml/src/ggml-opencl/ops/flash_attn.cpp +++ b/ggml/src/ggml-opencl/ops/flash_attn.cpp @@ -1,6 +1,8 @@ #include "../cl-common.h" #include "../ops.h" +#include + struct ggml_cl_flash_attn_temp_buffer { cl_mem data = nullptr; diff --git a/ggml/src/ggml-opencl/ops/mul_mat.cpp b/ggml/src/ggml-opencl/ops/mul_mat.cpp index 412d4a8f8033..dbbd9ba9e4ac 100644 --- a/ggml/src/ggml-opencl/ops/mul_mat.cpp +++ b/ggml/src/ggml-opencl/ops/mul_mat.cpp @@ -1,6 +1,8 @@ #include "../cl-common.h" #include "../ops.h" +#include + static std::string ggml_cl_q2_k_mm_options(const ggml_backend_opencl_context * backend_ctx) { const bool x2 = backend_ctx->gpu_family == ADRENO && (backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X || backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E); diff --git a/ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp b/ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp index 653db979a04e..55997ab1560b 100644 --- a/ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp +++ b/ggml/src/ggml-opencl/ops/mul_mat_adreno.cpp @@ -1,6 +1,8 @@ #include "../cl-common.h" #include "../ops.h" +#include + #ifdef GGML_OPENCL_USE_ADRENO_KERNELS static bool ggml_cl_coopk_dp4a_enabled(const ggml_backend_opencl_context * backend_ctx) { static const char * const env = getenv("GGML_OPENCL_COOPK_DP4A"); diff --git a/ggml/src/ggml-opencl/ops/mul_mat_id.cpp b/ggml/src/ggml-opencl/ops/mul_mat_id.cpp index 8d7755661ad5..57e30fd4cdc7 100644 --- a/ggml/src/ggml-opencl/ops/mul_mat_id.cpp +++ b/ggml/src/ggml-opencl/ops/mul_mat_id.cpp @@ -1,6 +1,7 @@ #include "../cl-common.h" #include "../ops.h" +#include #include void ggml_cl_moe_combine_fused(ggml_backend_t backend, const ggml_tensor * mul, const ggml_tensor * dst) { From ef708d40d279b64536dc80cbdcd039ae28bbafda Mon Sep 17 00:00:00 2001 From: Georgi Gerganov Date: Fri, 4 Dec 2026 15:41:23 +0200 Subject: [PATCH 392/401] common : recognize Q4_K in the -hf default quant preference (#33686) Repos shipping a bare Q4_K quant next to Q8_0 fell through to Q8_0 by default, since only Q4_K_M and Q8_0 were in the preference list. Try Q4_K between the two; the tag still matches as a full token, so Q4_K never picks a Q4_K_M file and vice versa. Assisted-by: dsh:llama.cpp/ggml-org/Qwen3.8-Flash-Next-GGUF (RTX 5090 32GB, DDR5 128GB) --- common/download.cpp | 2 +- tests/test-model-resolution.cpp | 41 +++++++++++++++++++++++++++++---- 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/common/download.cpp b/common/download.cpp index 4dabaedb5466..c2841b2640f0 100644 --- a/common/download.cpp +++ b/common/download.cpp @@ -774,7 +774,7 @@ static hf_cache::hf_file find_best_model(const hf_cache::hf_files & files, if (!tag.empty()) { tags.push_back(tag); } else { - tags = {"Q4_K_M", "Q8_0"}; + tags = {"Q4_K_M", "Q4_K", "Q8_0"}; } for (const auto & t : tags) { diff --git a/tests/test-model-resolution.cpp b/tests/test-model-resolution.cpp index e2576a1c9514..b2d8a0135dc1 100644 --- a/tests/test-model-resolution.cpp +++ b/tests/test-model-resolution.cpp @@ -161,6 +161,19 @@ static const std::vector twins = { "model-Q4_XS.gguf", }; +// a repo shipping Q4_K next to Q8_0, in the style of ggml-org/GLM-4.7-Flash-GGUF +static const std::vector q4k = { + "model-BF16.gguf", + "model-Q4_K.gguf", + "model-Q8_0.gguf", +}; + +// Q4_K and Q4_K_M side by side, the tag must not cross the token +static const std::vector kq = { + "model-Q4_K.gguf", + "model-Q4_K_M.gguf", +}; + // every speculative sidecar type at the same quant static const std::vector quad = { "model-Q8_0.gguf", @@ -295,6 +308,26 @@ static const plan_case plan_cases[] = { "model-IQ4_XS.gguf", {"model-IQ4_XS.gguf"}, "", "", "", "", ""}, + // the default preference falls to Q4_K when the repo ships no Q4_K_M + {"q4k default", q4k, "test/repo", "", false, false, + "model-Q4_K.gguf", {"model-Q4_K.gguf"}, + "", "", "", "", ""}, + + // the Q4_K tag picks the Q4_K file + {"q4k tag", q4k, "test/repo:Q4_K", "", false, false, + "model-Q4_K.gguf", {"model-Q4_K.gguf"}, + "", "", "", "", ""}, + + // Q4_K_M keeps the default over a Q4_K file of the same repo + {"kq default", kq, "test/repo", "", false, false, + "model-Q4_K_M.gguf", {"model-Q4_K_M.gguf"}, + "", "", "", "", ""}, + + // the Q4_K tag matches the full token, never the Q4_K_M file + {"kq q4_k tag", kq, "test/repo:Q4_K", "", false, false, + "model-Q4_K.gguf", {"model-Q4_K.gguf"}, + "", "", "", "", ""}, + // every sidecar type resolves at the tag {"quad exact tag", quad, "test/repo:Q8_0", "", true, false, "model-Q8_0.gguf", {"model-Q8_0.gguf"}, @@ -665,7 +698,7 @@ static const real_repo real_repos[] = { {"audio-flamingo-next-q4_k.gguf"}, {"audio-flamingo-next-q8_0.gguf"}}, { - {"", "audio-flamingo-3-q8_0.gguf", 1, "", "", "", "", ""}, + {"", "audio-flamingo-3-q4_k.gguf", 1, "", "", "", "", ""}, {"Q8_0", "audio-flamingo-3-q8_0.gguf", 1, "", "", "", "", ""}, {"BF16", "audio-flamingo-3-bf16.gguf", 1, "", "", "", "", ""}}, {"Q8_0", "Q4_K", "BF16"}}, @@ -1198,7 +1231,7 @@ static const real_repo real_repos[] = { {{"GLM-4.7-Flash-Q4_K.gguf"}, {"GLM-4.7-Flash-Q8_0.gguf"}}, { - {"", "GLM-4.7-Flash-Q8_0.gguf", 1, "", "", "", "", ""}, + {"", "GLM-4.7-Flash-Q4_K.gguf", 1, "", "", "", "", ""}, {"Q8_0", "GLM-4.7-Flash-Q8_0.gguf", 1, "", "", "", "", ""}, {"Q4_K", "GLM-4.7-Flash-Q4_K.gguf", 1, "", "", "", "", ""}}, {"Q8_0", "Q4_K"}}, @@ -1506,7 +1539,7 @@ static const real_repo real_repos[] = { {"Agents-A1-abliterated-bf16.gguf"}, {"mmproj-model-bf16.gguf"}}, { - {"", "Agents-A1-abliterated-Q8_0.gguf", 1, "mmproj-model-bf16.gguf", "", "", "", ""}, + {"", "Agents-A1-abliterated-Q4_K.gguf", 1, "mmproj-model-bf16.gguf", "", "", "", ""}, {"Q8_0", "Agents-A1-abliterated-Q8_0.gguf", 1, "mmproj-model-bf16.gguf", "", "", "", ""}, {"Q4_K", "Agents-A1-abliterated-Q4_K.gguf", 1, "mmproj-model-bf16.gguf", "", "", "", ""}, {"BF16", "Agents-A1-abliterated-bf16.gguf", 1, "mmproj-model-bf16.gguf", "", "", "", ""}}, @@ -2182,7 +2215,7 @@ static const real_repo real_repos[] = { {"Spark-X2.5-4B-abliterated-FIT-COMPACT-2.43GiB-Q4_K.gguf"}, {"Spark-X2.5-4B-abliterated-FIT-QUALITY-3.15GiB-Q6_K.gguf"}}, { - {"", "Spark-X2.5-4B-abliterated-BF16.gguf", 1, "", "", "", "", ""}, + {"", "Spark-X2.5-4B-abliterated-FIT-COMPACT-2.43GiB-Q4_K.gguf", 1, "", "", "", "", ""}, {"BF16", "Spark-X2.5-4B-abliterated-BF16.gguf", 1, "", "", "", "", ""}, {"Q6_K", "Spark-X2.5-4B-abliterated-FIT-QUALITY-3.15GiB-Q6_K.gguf", 1, "", "", "", "", ""}}, {"Q6_K", "Q4_K", "BF16"}}, From 34bb65674c44746c9278fa25d79c97b26ca015b0 Mon Sep 17 00:00:00 2001 From: Aaron Teo Date: Fri, 4 Dec 2026 21:43:55 +0800 Subject: [PATCH 393/401] ggml-cpu(s390x): use optimized kernels (#33260) Signed-off-by: Aaron Teo --- ggml/src/ggml-cpu/arch/s390/quants.c | 7 ++++++- ggml/src/ggml-cpu/llamafile/sgemm.cpp | 10 ++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-cpu/arch/s390/quants.c b/ggml/src/ggml-cpu/arch/s390/quants.c index 53a3d14ec824..5c6a57436be9 100644 --- a/ggml/src/ggml-cpu/arch/s390/quants.c +++ b/ggml/src/ggml-cpu/arch/s390/quants.c @@ -1390,6 +1390,8 @@ void ggml_vec_dot_iq4_nl_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const v const int8x16_t v_k = vec_xl(0, kvalues_iq4nl); const uint8x16_t v_m = vec_splat_u8(0x0F); + float32x4_t acc = vec_splats(0.0f); + for (; ib < nb; ++ib) { const block_iq4_nl * GGML_RESTRICT x0 = &x[ib]; const block_q8_0 * GGML_RESTRICT y0 = &y[ib]; @@ -1404,10 +1406,13 @@ void ggml_vec_dot_iq4_nl_q8_0(int n, float * GGML_RESTRICT s, size_t bs, const v const int8x16_t v_yl = vec_xl(0 , y0->qs); const int8x16_t v_yh = vec_xl(QK8_0/2, y0->qs); const int32x4_t v_xy = ggml_vec_dot_s32(ggml_vec_dot_s32(vec_splats(0), v_xl, v_yl), v_xh, v_yh); + const float32x4_t v_d = vec_splats(GGML_CPU_FP16_TO_FP32(x0->d) * GGML_CPU_FP16_TO_FP32(y0->d)); - sumf += GGML_CPU_FP16_TO_FP32(x0->d) * GGML_CPU_FP16_TO_FP32(y0->d) * vec_hsum_i32x4(v_xy); + acc = vec_madd(vec_float(v_xy), v_d, acc); } + sumf = vec_hsum_f32x4(acc); + *s = sumf; #else UNUSED(x); diff --git a/ggml/src/ggml-cpu/llamafile/sgemm.cpp b/ggml/src/ggml-cpu/llamafile/sgemm.cpp index 5ddb850fa952..256ffa4519ab 100644 --- a/ggml/src/ggml-cpu/llamafile/sgemm.cpp +++ b/ggml/src/ggml-cpu/llamafile/sgemm.cpp @@ -1529,10 +1529,13 @@ class tinyBLAS_QK_VXE { // the columns are in the inner loop, so that their sums do not wait for each other int32x4_t v_dot[RN] = {}; - for (int32_t g = 0; g < n_group; ++g) { + for (int32_t g = 0; g < n_group; g += group_step) { for (int32_t j = 0; j < RN; ++j) { const int8x16_t v_y = vec_xl(0, y_qs[j] + 16 * g); - const int16x8_t v_xy = vec_meadd(v_x[g], v_y, vec_mulo(v_x[g], v_y)); + int16x8_t v_xy = vec_meadd(v_x[g], v_y, vec_mulo(v_x[g], v_y)); + if (group_step == 2) { + v_xy = ggml_vec_dot_s16(v_xy, v_x[g + 1], vec_xl(0, y_qs[j] + 16 * (g + 1))); + } v_dot[j] = vec_meadd(v_xy, v_scale[g], vec_moadd(v_xy, v_scale[g], v_dot[j])); } } @@ -1572,6 +1575,9 @@ class tinyBLAS_QK_VXE { // Q3_K and Q6_K have no minimum, their weights are loaded as signed values. static constexpr bool has_min = !std::is_same::value && !std::is_same::value; + // Q4_K and Q5_K sum 2 groups with the same scale in 16 bits, 4 products of at most 31 * 127 fit + static constexpr int32_t group_step = std::is_same::value || std::is_same::value ? 2 : 1; + static float dmin(const block_q2_K & x) { return unhalf(x.dmin); } static float dmin(const block_q4_K & x) { return unhalf(x.dmin); } static float dmin(const block_q5_K & x) { return unhalf(x.dmin); } From 9cc2807ba29e14abc8acf966c0b4976820e5eb2d Mon Sep 17 00:00:00 2001 From: HeZzz <142383180+HeZ2z@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:48:28 +0800 Subject: [PATCH 394/401] convert: fix GPT-2 and StableLM conversion after generator migration (#33677) * convert: fix GPT-2 and StableLM conversion after generator migration * convert : drop the regression test * tests : drop the removed conversion test --- conversion/gpt2.py | 1 - conversion/stablelm.py | 10 ++++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/conversion/gpt2.py b/conversion/gpt2.py index 06dff9e4c7f6..4ec8f0544a9a 100644 --- a/conversion/gpt2.py +++ b/conversion/gpt2.py @@ -27,7 +27,6 @@ def set_gguf_parameters(self): def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]: # we don't need these if name.endswith((".attn.bias", ".attn.masked_bias")): - yield from super().modify_tensors(data_torch, name, bid) return if name.endswith((".c_attn.weight", ".c_proj.weight", ".c_fc.weight", ".c_proj.weight")): diff --git a/conversion/stablelm.py b/conversion/stablelm.py index ac3a1ca9e1f1..11900ea5fcd5 100644 --- a/conversion/stablelm.py +++ b/conversion/stablelm.py @@ -53,9 +53,8 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter self._q_norms[bid][name] = data_torch if len(self._q_norms[bid]) >= n_head: - return self._stack_qk_norm(bid, n_head, self._q_norms[bid], "q_layernorm") - else: - return + yield from self._stack_qk_norm(bid, n_head, self._q_norms[bid], "q_layernorm") + return if name.find("k_layernorm.norms") != -1: assert bid is not None @@ -66,9 +65,8 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter self._k_norms[bid][name] = data_torch if len(self._k_norms[bid]) >= n_kv_head: - return self._stack_qk_norm(bid, n_kv_head, self._k_norms[bid], "k_layernorm") - else: - return + yield from self._stack_qk_norm(bid, n_kv_head, self._k_norms[bid], "k_layernorm") + return yield from super().modify_tensors(data_torch, name, bid) From 15dd330d5529f7fbb158f2b0a9e93cec5fbcf548 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sigbj=C3=B8rn=20Skj=C3=A6ret?= Date: Fri, 4 Dec 2026 15:03:59 +0100 Subject: [PATCH 395/401] models : workaround for misplaced layernorm_rms_eps metadata (#33693) [no ci] --- src/models/exaone.cpp | 4 +++- src/models/qwen.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/models/exaone.cpp b/src/models/exaone.cpp index 9f30e342188a..768d12dbcb75 100644 --- a/src/models/exaone.cpp +++ b/src/models/exaone.cpp @@ -1,7 +1,9 @@ #include "models.h" void llama_model_exaone::load_arch_hparams(llama_model_loader & ml) { - ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + if (!ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps, false)) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_rms_eps); + } switch (hparams.n_layer()) { case 32: type = LLM_TYPE_8B; break; diff --git a/src/models/qwen.cpp b/src/models/qwen.cpp index 0e6325bb9aea..72edb6aade71 100644 --- a/src/models/qwen.cpp +++ b/src/models/qwen.cpp @@ -1,7 +1,9 @@ #include "models.h" void llama_model_qwen::load_arch_hparams(llama_model_loader & ml) { - ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps); + if (!ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps, false)) { + ml.get_key(LLM_KV_ATTENTION_LAYERNORM_EPS, hparams.f_norm_rms_eps); + } switch (hparams.n_layer()) { case 32: type = LLM_TYPE_7B; break; From 7a7142b20f012d06e9a351e3ab0bc9b6553b9475 Mon Sep 17 00:00:00 2001 From: shamnadxyz <155352697+shamnadxyz@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:39:59 +0530 Subject: [PATCH 396/401] server: remove legacy mmproj_model loading event (#33676) --- tools/server/server-context.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index d6be6561b03d..038cf3d38ef4 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -1400,10 +1400,6 @@ struct server_context_impl { } if (has_mmproj) { - if (callback_state) { - callback_state(SERVER_STATE_LOADING, {{"stage", "mmproj_model"}}); - } - if (!is_resume) { mtmd_helper_log_set(common_log_default_callback, nullptr); } From a274a3948fa5c917d54a3f28fe8af74bca513688 Mon Sep 17 00:00:00 2001 From: Yamini Nimmagadda Date: Fri, 4 Dec 2026 07:30:31 -0800 Subject: [PATCH 397/401] openvino: CI fixes, new models, improve NPU, Q2_0 support (#33652) * ggml-openvino : add Q2_0 and Bonsai 2 support * openvino: enable text inference for Nemotron Lightning and LFM3 Assisted-by: Codex * openvino: enable NPU host gather by default * docs : host gather is on by default * openvino: compute ELU with an accurate expm1 * ggml-openvino: compute NPU RoPE cos/sin on the host for long contexts Assisted-by: Claude Opus 5.5 * openvino: review fixes for the NPU RoPE table * openvino: replace the RoPE flags with GGML_OPENVINO_ROPE_SINCOS * docs : reorganize OpenVINO docs and add a cookbook * openvino: preserve token dimensions in Gemma 3n reductions Assisted-by: Codex * openvino: keep the compiled-model cache revision at 14 Assisted-by: Codex * openvino: reject sequence-major SSM_SCAN inputs * ggml-openvino : drop code that the ggml core does not need * openvino: add GGML_OPENVINO_SPILL_RESIDENT to cap the spilled weights kept in RAM Assisted-by: Claude Opus 5.5 * openvino: review fixes for GGML_OPENVINO_SPILL_RESIDENT * openvino: take GGML_OPENVINO_SPILL_RESIDENT as a fraction * openvino: add GGML_OPENVINO_SPILL and simplify the spill limiter * openvino: add GGML_OPENVINO_COMPILE_MEM_SPILL * openvino: clang-format fixes * openvino: unwrap comments and docs per AGENTS.md Assisted-by: Claude Code --------- Co-authored-by: Mustafa Cavus Co-authored-by: Yu, Zijun Co-authored-by: Xuejun Co-authored-by: ravi9 Co-authored-by: Anisha Kulkarni --- docs/backend/OPENVINO.md | 917 +++--------------- ggml/src/ggml-openvino/dev_doc/COOKBOOK.md | 806 +++++++++++++++ .../dev_doc/MTP-SAMPLING-GRAPH.md | 36 +- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 89 +- .../dev_doc/OpenVINO-ENV-VARS.md | 183 +--- ggml/src/ggml-openvino/dev_doc/README.md | 228 +++-- ggml/src/ggml-openvino/ggml-decoder.cpp | 50 +- ggml/src/ggml-openvino/ggml-decoder.h | 2 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 62 +- ggml/src/ggml-openvino/ggml-openvino-extra.h | 23 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 361 ++++++- ggml/src/ggml-openvino/ggml-quants.cpp | 126 ++- ggml/src/ggml-openvino/model-cache.cpp | 12 +- ggml/src/ggml-openvino/openvino/decoder.h | 3 + .../src/ggml-openvino/openvino/node_context.h | 2 + ggml/src/ggml-openvino/openvino/op/cont.cpp | 10 +- .../ggml-openvino/openvino/op/get_rows.cpp | 5 +- ggml/src/ggml-openvino/openvino/op/mul.cpp | 39 + ggml/src/ggml-openvino/openvino/op/rope.cpp | 103 +- ggml/src/ggml-openvino/openvino/op/unary.cpp | 33 +- ggml/src/ggml-openvino/openvino/op_table.cpp | 3 +- ggml/src/ggml-openvino/openvino/op_table.h | 1 + ggml/src/ggml-openvino/openvino/utils.cpp | 58 +- ggml/src/ggml-openvino/openvino/utils.h | 8 +- ggml/src/ggml-openvino/utils.cpp | 15 +- 25 files changed, 1927 insertions(+), 1248 deletions(-) create mode 100644 ggml/src/ggml-openvino/dev_doc/COOKBOOK.md create mode 100644 ggml/src/ggml-openvino/openvino/op/mul.cpp diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 0449a5d3a2bd..c6468a21898c 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -1,18 +1,10 @@ # OpenVINO Backend for llama.cpp -> [!NOTE] -> Performance and memory optimizations, accuracy validation, broader quantization coverage, broader operator and model support are work in progress. +[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying AI inference on Intel hardware. The [OpenVINO backend](../../ggml/src/ggml-openvino) runs the same GGUF model files on **Intel(R) CPUs, GPUs and NPUs**, without changes to the model or the rest of llama.cpp. -[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying high-performance AI inference, specifically designed for Intel hardware, including CPUs, GPUs (integrated and discrete), and NPUs, in the cloud, on-premises, and on the edge. The [OpenVINO backend](../../ggml/src/ggml-openvino) runs the same GGUF model files on **Intel® CPUs, GPUs and NPUs**, without changes to the model or the rest of llama.cpp. - -When a `ggml_cgraph` is dispatched to the OpenVINO backend, it: - -- Walks the GGML graph and identifies inputs, outputs, weights, and KV cache tensors. -- Translates the GGML operations into an `ov::Model` using OpenVINO's frontend API. -- Compiles and caches the model for the target device. -- Binds GGML tensor memory to OpenVINO inference tensors and runs inference. - -For guidance on contributing to the OpenVINO backend, see the [OpenVINO Backend Contributing Guide](https://github.com/ravi9/llamacpp-ov-dev-guide/blob/main/contributing-llamacpp-ov.md). +- Recipes for each task: [llama.cpp OpenVINO backend cookbook](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md). +- Internals and developer options: [developer documentation](../../ggml/src/ggml-openvino/dev_doc/README.md). +- Contributing: [OpenVINO Backend Contributing Guide](https://github.com/ravi9/llamacpp-ov-dev-guide/blob/main/contributing-llamacpp-ov.md). ## Contents @@ -21,30 +13,24 @@ For guidance on contributing to the OpenVINO backend, see the [OpenVINO Backend - [Supported Model Precisions](#supported-model-precisions) - [Supported llama.cpp Tools](#supported-llamacpp-tools) - [Validated Models](#validated-models) -- [Build Instructions](#build-instructions) - - [0. Prerequisites](#0-prerequisites) - - [1. Install OpenVINO Runtime](#1-install-openvino-runtime) - - [2. Build llama.cpp with OpenVINO Backend](#2-build-llamacpp-with-openvino-backend) - - [Ubuntu Build Script](#ubuntu-build-script) - - [Windows Build Script](#windows-build-script) - - [3. Download Sample Model](#3-download-sample-model) - - [4. Run Inference with OpenVINO Backend](#4-run-inference-with-openvino-backend) - - [5. Docker Build](#5-docker-build) -- [Runtime Configuration](#runtime-configuration) +- [Build](#build) + - [Prerequisites](#prerequisites) + - [Install OpenVINO Runtime](#install-openvino-runtime) + - [Build llama.cpp](#build-llamacpp) +- [Docker](#docker) +- [Configuration](#configuration) - [Basic](#basic) - [Plugin properties](#plugin-properties) - [Advanced tuning](#advanced-tuning) - [Compiled model cache](#compiled-model-cache) - [Deprecated](#deprecated) - - [Debugging and development](#debugging-and-development) - - [Example Usage](#example-usage) - - [GPU Inference with Profiling](#gpu-inference-with-profiling) + - [Developer variables](#developer-variables) - [Known Limitations](#known-limitations) - [Work in Progress](#work-in-progress) ## Quick Start -On Ubuntu, with the [prerequisites](#0-prerequisites) and the [OpenVINO Runtime](#1-install-openvino-runtime) installed: +On Ubuntu, with the [prerequisites](#prerequisites) and the [OpenVINO Runtime](#install-openvino-runtime) installed: ```bash # 1. Build @@ -59,24 +45,31 @@ mkdir -p ~/models/ wget https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ -O ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -# 3. Run on CPU, GPU or NPU -export GGML_OPENVINO_DEVICE=GPU -./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +# 3. Run on CPU, GPU or NPU. -c sets the context size. The default is the training context of the model. +GGML_OPENVINO_DEVICE=CPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +GGML_OPENVINO_DEVICE=NPU ./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 ``` -The [Ubuntu Build Script](#ubuntu-build-script) and the [Windows Build Script](#windows-build-script) do the setup in one step: they install the build prerequisites and the OpenVINO Runtime, and build llama.cpp with the OpenVINO backend. They do not install the GPU and NPU drivers (the Ubuntu script installs only the `intel-opencl-icd` package of the distribution); see [Prerequisites](#0-prerequisites). - -See [Build Instructions](#build-instructions) for Windows and Docker, and [Runtime Configuration](#runtime-configuration) for the environment variables. +- The first run of a model compiles it for the device. On the NPU, this can take minutes for a large model. +- Windows, llama-server, llama-bench and NPU tuning: [Run on each device](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#run-on-each-device). +- One-step build scripts for Ubuntu and Windows: [Build from source](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#build-from-source). ## Supported Devices -OpenVINO backend supports the following hardware: - - Intel CPUs - Intel GPUs (integrated and discrete) - Intel NPUs -Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), the llama.cpp OpenVINO backend has been validated specifically on AI PCs such as the Intel® Core™ Ultra Series 2 (Lunar Lake) and Series 3 (Panther Lake). +The backend is validated on AI PCs with Intel(R) Core(TM) Ultra Series 2 (Lunar Lake) and Series 3 (Panther Lake). OpenVINO supports a wider range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html). + +Device selection: + +- Select the OpenVINO device with `GGML_OPENVINO_DEVICE`, not with `-dev`. The default is the CPU. +- With several GPUs, OpenVINO names them `GPU.0`, `GPU.1`, and so on. Set one of these names. `GPU` alone is then not available. +- A device that is not available is an error. There is no fallback to the CPU. The error lists the available devices. +- `llama-cli --list-devices` shows the `GGML_OPENVINO_DEVICE=` of each OpenVINO device. `(selected)` marks the active one. +- To split a model across GPUs, see [Multiple GPUs](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#multiple-gpus). GPU details: [OpenVINO GPU Device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html). ## Supported Model Precisions @@ -110,7 +103,8 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin **NPU:** - All other quantized tensors are requantized to `Q4_0_128`, or to `Q4_0_C` when the row width is not a multiple of 128. -- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding. +- With `GGML_OPENVINO_NPU_HOST_GATHER` (on by default), the host reads the rows of an embedding table of 64 MiB or more from the GGUF file. A table used only for these lookups is not converted. +- For a `Q6_K` token embedding in the NPU graph (a tied output weight, a table under 64 MiB, or with host gather off), `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding. - The validated models use `Q4_K_M` files. **Layout names:** @@ -119,21 +113,17 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin - `Q4_0_C`: 4-bit, symmetric, one scale per row. - `Q4_1_64`: 4-bit, asymmetric, one scale and one zero point per 64 weights. -**Additional Notes:** -- `Q4_0` and `Q4_1` models use `Q6_K` for the output weight, and for the token embedding only when it is the same tensor as the output weight. -- `Q4_0` models may produce some `Q4_1` tensors if an imatrix is provided during quantization using `llama-quantize`. -- `Q4_K_M` models may include both `Q6_K` and `Q5_K` tensors (observed in Phi-3). - ## Supported llama.cpp Tools -The OpenVINO backend works with the standard llama.cpp tools listed below. Tool coverage is not uniform across devices. +The OpenVINO backend works with the standard llama.cpp tools below. Tool coverage is not uniform across devices. - llama-bench - llama-cli - llama-completion - llama-embedding +- llama-mtmd-cli (image input on CPU and GPU, experimental) - llama-perplexity - llama-server - llama-simple @@ -145,7 +135,7 @@ The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® C **Legend & Test Configuration:** - **Status:** ✓ = Passed | ~ = Accuracy issues | ✗ = Failed or Unsupported - **Execution mode:** stateless (`GGML_OPENVINO_STATEFUL_EXECUTION=0`) on every device. -- **Validation system:** Intel® Core™ Ultra X7 358H (Panther Lake) | 64 GB RAM | Ubuntu 26.04.1 | Intel Graphics Compiler 2.43.9 | Intel OpenCL GPU Driver 26.44.40734.8-0 | Intel NPU Driver 1.39.1. +- **Validation system:** Intel(R) Core(TM) Ultra X7 358H (Panther Lake) | 64 GB RAM | Ubuntu 26.04.1 | OpenVINO 2026.5.0 | Intel Graphics Compiler 2.43.9 | Intel OpenCL GPU Driver 26.44.40734.8-0 | Intel NPU Driver 1.39.1. - See [Known Limitations](#known-limitations) for context on observed failures.
@@ -208,27 +198,26 @@ The embedding models were tested with `llama-embedding` and `Q8_0` files.
-## Build Instructions +## Build + +- Prebuilt binaries: each llama.cpp [release](https://github.com/ggml-org/llama.cpp/releases) has OpenVINO builds for Ubuntu and Windows. They include the OpenVINO runtime. Install the GPU and NPU drivers separately. +- One-step build scripts for Ubuntu and Windows: [Build from source](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#build-from-source). -### 0. Prerequisites +### Prerequisites -- Linux or Windows system with Intel hardware (CPU, GPU, or NPU) -- **For Intel GPU or NPU Usage**: Install the appropriate hardware drivers for your Intel GPU or NPU. For detailed instructions, see: [Additional Configurations for Hardware Acceleration](https://docs.openvino.ai/2026/get-started/install-openvino/configurations.html). +- Linux or Windows, with an Intel CPU, GPU or NPU. +- OpenVINO Runtime 2026.5 or later. See [Install OpenVINO Runtime](#install-openvino-runtime). +- GPU or NPU: the device drivers. See [Additional Configurations for Hardware Acceleration](https://docs.openvino.ai/2026/get-started/install-openvino/configurations.html).
Linux -Build tools (Git, CMake, Ninja): - ```bash +# Build tools (Git, CMake, Ninja) sudo apt-get update -sudo apt-get install -y build-essential libcurl4-openssl-dev libssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar git -``` - -OpenCL: - -```bash -sudo apt install ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd +sudo apt-get install -y build-essential libssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar git +# OpenCL +sudo apt-get install -y ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd ```
@@ -236,606 +225,77 @@ sudo apt install ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-op
Windows -1. Download and install [Microsoft Visual Studio 2022 Build Tools](https://aka.ms/vs/17/release/vs_BuildTools.exe). During installation, select the **"Desktop development with C++"** workload. -2. Install the required tools: +1. Install [Microsoft Visual Studio 2022 Build Tools](https://aka.ms/vs/17/release/vs_BuildTools.exe) with the **Desktop development with C++** workload. +2. Install Git, Ninja and OpenCL: ```powershell # Windows PowerShell winget install Git.Git - winget install GNU.Wget winget install Ninja-build.Ninja - ``` - -3. Install **OpenCL** using **vcpkg**: - - ```powershell - # Windows PowerShell + # OpenCL with vcpkg, in C:\vcpkg cd C:\ git clone https://github.com/microsoft/vcpkg cd vcpkg .\bootstrap-vcpkg.bat .\vcpkg install opencl - # Optional but recommended: Integrate vcpkg with Visual Studio / CMake: + # Optional: integrate vcpkg with Visual Studio and CMake .\vcpkg integrate install ```
-### 1. Install OpenVINO Runtime - -- Follow the guide to install OpenVINO Runtime from an archive file: [Linux](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-linux.html) | [Windows](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-windows.html) - -- Verify OpenVINO is initialized properly: - ```bash - echo $OpenVINO_DIR - ``` - -### 2. Build llama.cpp with OpenVINO Backend +### Install OpenVINO Runtime -Clone the llama.cpp repository: +Install OpenVINO Runtime 2026.5 from an archive file: [Linux](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-linux.html) | [Windows](https://docs.openvino.ai/2026/get-started/install-openvino/install-openvino-archive-windows.html). The CI and the cookbook build scripts use this version. ```bash -git clone https://github.com/ggml-org/llama.cpp -cd llama.cpp +# Check the setup: setupvars sets OpenVINO_DIR +source /opt/intel/openvino/setupvars.sh +echo $OpenVINO_DIR ``` -Build on Linux: +### Build llama.cpp ```bash +# Linux. Adjust the setupvars.sh path to the OpenVINO install directory. +git clone https://github.com/ggml-org/llama.cpp +cd llama.cpp source /opt/intel/openvino/setupvars.sh cmake -B build/ReleaseOV -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_OPENVINO=ON cmake --build build/ReleaseOV --parallel ``` -Adjust the `setupvars.sh` path to the directory where OpenVINO Runtime is installed. The Ubuntu build script below installs it to `/opt/intel/openvino`. - -
-Build on Windows - -Open **x64 Native Tools Command Prompt for VS** (so the MSVC toolchain is on `PATH`), then run: - ```cmd +REM Windows: x64 Native Tools Command Prompt for VS, so that the MSVC toolchain is on PATH +git clone https://github.com/ggml-org/llama.cpp +cd llama.cpp C:\Intel\openvino\setupvars.bat cmake -B build\ReleaseOV -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_OPENVINO=ON -DCMAKE_TOOLCHAIN_FILE=C:\vcpkg\scripts\buildsystems\vcpkg.cmake cmake --build build\ReleaseOV --parallel ``` -> [!NOTE] -> The Windows install path is `C:\Intel\openvino` (no spaces) to avoid quoting problems some CMake/Ninja toolchains have with `C:\Program Files (x86)\...`. Adjust to wherever you installed OpenVINO Runtime. From `cmd`, run `C:\Intel\openvino\setupvars.bat`; from PowerShell, run `& "C:\Intel\openvino\setupvars.ps1"` instead. Once the build is finished you can launch the binaries from any `cmd` or `PowerShell` window after sourcing the matching `setupvars` script for that shell. - -
- -#### Ubuntu Build Script - -For Ubuntu users, the following shell script automates the prerequisite installs (build tools, OpenCL ICD), the OpenVINO Runtime download/extract/setup, and the Ninja-based llama.cpp build. -Save the following as `build-llamacpp-ov.sh` next to where you want the `llama.cpp` folder to land, then run it: - -```bash -chmod +x build-llamacpp-ov.sh -./build-llamacpp-ov.sh -``` - -
-Click to expand build-llamacpp-ov.sh - -```bash -#!/usr/bin/env bash -# ============================================ -# llama.cpp OpenVINO Build Script (Ninja) -# ============================================ -set -euo pipefail - -OPENVINO_VERSION_MAJOR="2026.5" -OPENVINO_VERSION_FULL="2026.5.0.23836.73088206582" - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -OPENVINO_INSTALL_DIR="/opt/intel/openvino_${OPENVINO_VERSION_MAJOR}" -OPENVINO_LINK_DIR="/opt/intel/openvino" -OPENVINO_TGZ="${SCRIPT_DIR}/openvino.tgz" -UBUNTU_MAJOR="$(. /etc/os-release && echo "${VERSION_ID%%.*}")" # 22, 24 or 26 -OPENVINO_URL="https://storage.openvinotoolkit.org/repositories/openvino/packages/${OPENVINO_VERSION_MAJOR}/linux/openvino_toolkit_ubuntu${UBUNTU_MAJOR}_${OPENVINO_VERSION_FULL}_x86_64.tgz" - -case "${UBUNTU_MAJOR}" in - 22|24|26) ;; - *) echo "Unsupported Ubuntu version ${UBUNTU_MAJOR}: OpenVINO archives exist for Ubuntu 22, 24 and 26." >&2; exit 1 ;; -esac - -echo "============================================" -echo "Installing prerequisites (apt)..." -echo "============================================" -sudo apt-get update -sudo apt-get install -y \ - build-essential libcurl4-openssl-dev libssl-dev libtbb12 \ - cmake ninja-build python3-pip \ - curl wget tar git - -echo "============================================" -echo "Installing OpenCL runtime + headers..." -echo "============================================" -sudo apt-get install -y \ - ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd - -cd "${SCRIPT_DIR}" - -# ============================================ -# Clone llama.cpp if missing -# ============================================ -if [[ ! -f "llama.cpp/CMakeLists.txt" ]]; then - echo "Cloning llama.cpp..." - git clone https://github.com/ggml-org/llama.cpp -fi - -# ============================================ -# Setup OpenVINO: download & extract to /opt/intel/openvino_${OPENVINO_VERSION_MAJOR}, -# then point /opt/intel/openvino at it via symlink so the active version is swappable. -# ============================================ -if [[ -f "${OPENVINO_INSTALL_DIR}/setupvars.sh" ]]; then - echo "OpenVINO ${OPENVINO_VERSION_MAJOR} already installed at ${OPENVINO_INSTALL_DIR}. Skipping download." -else - echo "OpenVINO not found at ${OPENVINO_INSTALL_DIR}. Starting download..." - curl -fL -o "${OPENVINO_TGZ}" "${OPENVINO_URL}" - - echo "Extracting OpenVINO to ${OPENVINO_INSTALL_DIR}..." - sudo mkdir -p "${OPENVINO_INSTALL_DIR}" - sudo tar -xzf "${OPENVINO_TGZ}" -C "${OPENVINO_INSTALL_DIR}" --strip-components=1 - rm -f "${OPENVINO_TGZ}" -fi - -# Refresh symlink: /opt/intel/openvino -> /opt/intel/openvino_${OPENVINO_VERSION_MAJOR} -sudo ln -sfn "${OPENVINO_INSTALL_DIR}" "${OPENVINO_LINK_DIR}" - -OPENVINO_ROOT="${OPENVINO_LINK_DIR}" -echo "OpenVINO Ready: ${OPENVINO_ROOT} -> ${OPENVINO_INSTALL_DIR}" - -# Install OpenVINO's own runtime dependencies (one-time per system). -if [[ -x "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh" ]]; then - echo "============================================" - echo "Installing OpenVINO runtime dependencies..." - echo "============================================" - echo "Y" | sudo -E "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh" -fi - -# ============================================ -# Clean old build cache -# ============================================ -cd "${SCRIPT_DIR}/llama.cpp" -if [[ -d "build/ReleaseOV" ]]; then - echo "Removing old build directory..." - rm -rf "build/ReleaseOV" -fi - -echo "============================================" -echo "Configuring with CMake..." -echo "============================================" -set +u -source "${OPENVINO_ROOT}/setupvars.sh" -set -u - -cmake -B build/ReleaseOV -G Ninja \ - -DCMAKE_BUILD_TYPE=Release \ - -DGGML_OPENVINO=ON - -cmake --build build/ReleaseOV --parallel - -echo "============================================" -echo "Build completed successfully!" -echo "============================================" -echo "Binaries: $(pwd)/build/ReleaseOV/bin" -echo -echo "NOTE: To run, source setupvars.sh and pick a device:" -echo " source /opt/intel/openvino/setupvars.sh" -echo " export GGML_OPENVINO_DEVICE=CPU # or GPU / NPU" -echo " ./build/ReleaseOV/bin/llama-cli -m model.gguf" -``` - -> [!NOTE] -> The script pins OpenVINO `2026.5` via the `OPENVINO_VERSION_MAJOR` / `OPENVINO_VERSION_FULL` variables at the top — edit them to track a different release. - -
- -#### Windows Build Script - -For Windows users, the following `.bat` script automates the prerequisite installs (Git, Ninja, CMake, Visual Studio 2022 Build Tools, vcpkg + OpenCL), the OpenVINO Runtime download/extract, and the Ninja-based llama.cpp build. -Save the following as `build-llamacpp-ov.bat` next to where you want the `llama.cpp` folder to land, then run it from either **Command Prompt** or **PowerShell**: - -```cmd -:: Command Prompt -build-llamacpp-ov.bat -``` - -```powershell -# PowerShell -.\build-llamacpp-ov.bat -``` - -
-Click to expand build-llamacpp-ov.bat - -```bat -@echo off -setlocal enabledelayedexpansion - -REM ============================================ -REM llama.cpp OpenVINO Build Script (Ninja) -REM ============================================ - -set "OPENVINO_VERSION_MAJOR=2026.5" -set "OPENVINO_VERSION_FULL=2026.5.0.23836.73088206582" - -set "SCRIPT_DIR=%~dp0" -set "VCPKG_DIR=C:\vcpkg" -set "OPENVINO_INSTALL_DIR=C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%" -set "OPENVINO_LINK_DIR=C:\Intel\openvino" -set "OPENVINO_ZIP=%SCRIPT_DIR%openvino.zip" -set "OPENVINO_EXTRACT_TMP=%SCRIPT_DIR%openvino_extract_tmp" -set "OPENVINO_URL=https://storage.openvinotoolkit.org/repositories/openvino/packages/%OPENVINO_VERSION_MAJOR%/windows/openvino_toolkit_windows_%OPENVINO_VERSION_FULL%_x86_64.zip" - -echo ============================================ -echo Installing prerequisites... -echo ============================================ -winget install --id Git.Git -e --accept-source-agreements --accept-package-agreements 2>nul -winget install --id Ninja-build.Ninja -e --accept-source-agreements --accept-package-agreements 2>nul -winget install --id Kitware.CMake -e --accept-source-agreements --accept-package-agreements 2>nul - -REM Ensure Visual Studio Build Tools are installed. -echo Checking for Visual Studio Build Tools... -set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -set "VS_INSTALLED=" -if exist "%VSWHERE%" ( - for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2^>nul`) do ( - set "VS_INSTALLED=%%i" - ) -) -if defined VS_INSTALLED ( - echo Visual Studio with VC++ x86/x64 tools already present at "!VS_INSTALLED!". Skipping winget install. -) else ( - winget install --id Microsoft.VisualStudio.2022.BuildTools -e --override "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" --accept-source-agreements --accept-package-agreements - if errorlevel 1 ( - echo WARNING: winget could not install Visual Studio Build Tools automatically. - echo Install manually from https://aka.ms/vs/17/release/vs_BuildTools.exe ^(select the "Desktop development with C++" workload^) - echo and re-run this script from a "Developer Command Prompt for VS 2022". - ) -) - -echo ============================================ -echo Installing OpenCL via vcpkg... -echo ============================================ -if not exist "%VCPKG_DIR%" ( - git clone https://github.com/microsoft/vcpkg "%VCPKG_DIR%" - cd /d "%VCPKG_DIR%" - call bootstrap-vcpkg.bat - call vcpkg integrate install -) -cd /d "%VCPKG_DIR%" -call vcpkg install opencl - -cd /d "%SCRIPT_DIR%" - -REM ============================================ -REM Clone llama.cpp if missing -REM ============================================ -if not exist "llama.cpp\CMakeLists.txt" ( - echo Cloning llama.cpp... - git clone https://github.com/ggml-org/llama.cpp -) - -cd /d "llama.cpp" -set "SCRIPT_DIR=%CD%" - -REM ============================================ -REM Setup OpenVINO: download & extract to C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%, -REM then point C:\Intel\openvino at it via a directory junction (mklink /J). -REM ============================================ - -if exist "%OPENVINO_INSTALL_DIR%\setupvars.bat" ( - echo OpenVINO %OPENVINO_VERSION_MAJOR% already installed at "%OPENVINO_INSTALL_DIR%". Skipping download. -) else ( - echo OpenVINO not found at "%OPENVINO_INSTALL_DIR%". Starting download... - - curl -L -o "%OPENVINO_ZIP%" "%OPENVINO_URL%" - if errorlevel 1 ( - echo ERROR: Download failed. - exit /b 1 - ) - - echo Extracting OpenVINO... - if exist "%OPENVINO_EXTRACT_TMP%" rmdir /s /q "%OPENVINO_EXTRACT_TMP%" - mkdir "%OPENVINO_EXTRACT_TMP%" - tar -xf "%OPENVINO_ZIP%" -C "%OPENVINO_EXTRACT_TMP%" - if errorlevel 1 ( - echo ERROR: Extraction failed. - exit /b 1 - ) - - REM Move the single top-level folder contents into the versioned install dir. - set "OPENVINO_EXTRACTED=" - for /d %%i in ("%OPENVINO_EXTRACT_TMP%\*") do set "OPENVINO_EXTRACTED=%%i" - if not defined OPENVINO_EXTRACTED ( - echo ERROR: Could not locate extracted OpenVINO folder under "%OPENVINO_EXTRACT_TMP%". - exit /b 1 - ) - if not exist "%OPENVINO_INSTALL_DIR%" mkdir "%OPENVINO_INSTALL_DIR%" - xcopy /e /i /y /q "!OPENVINO_EXTRACTED!\*" "%OPENVINO_INSTALL_DIR%\" >nul - if errorlevel 1 ( - echo ERROR: Failed to copy OpenVINO from "!OPENVINO_EXTRACTED!" to "%OPENVINO_INSTALL_DIR%". - echo Re-run this script from an elevated Command Prompt ^(Run as administrator^) if access is denied. - exit /b 1 - ) - - rmdir /s /q "%OPENVINO_EXTRACT_TMP%" - del "%OPENVINO_ZIP%" -) - -REM Refresh junction: C:\Intel\openvino -> C:\Intel\openvino_. -REM `mklink /J` creates a directory junction (no admin / Developer Mode required). -if exist "%OPENVINO_LINK_DIR%" rmdir "%OPENVINO_LINK_DIR%" -mklink /J "%OPENVINO_LINK_DIR%" "%OPENVINO_INSTALL_DIR%" >nul -if errorlevel 1 ( - echo ERROR: Failed to create junction "%OPENVINO_LINK_DIR%" -^> "%OPENVINO_INSTALL_DIR%". - echo If "%OPENVINO_LINK_DIR%" already exists as a regular non-empty folder, remove it manually and re-run. - exit /b 1 -) - -set "OPENVINO_ROOT=%OPENVINO_LINK_DIR%" -echo OpenVINO Ready: %OPENVINO_ROOT% -^> %OPENVINO_INSTALL_DIR% - - -echo ============================================ -echo Setting up compiler environment... -echo ============================================ -REM Locate Visual Studio Build Tools vcvars64.bat -set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -if exist "%VSWHERE%" ( - for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do ( - set "VS_PATH=%%i" - ) -) -if defined VS_PATH ( - call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" >nul -) else ( - echo WARNING: Visual Studio Build Tools not found. Compiler may be missing. -) - -REM ============================================ -REM Clean old build cache -REM ============================================ -if exist "build\ReleaseOV" ( - echo Removing old build directory ... - rmdir /s /q "build\ReleaseOV" -) - -echo ============================================ -echo Configuring with CMake... -echo ============================================ -call "%OPENVINO_ROOT%\setupvars.bat" >nul 2>nul - -cmake -B build\ReleaseOV -G Ninja ^ - -DCMAKE_BUILD_TYPE=Release ^ - -DGGML_OPENVINO=ON ^ - -DCMAKE_TOOLCHAIN_FILE="%VCPKG_DIR%\scripts\buildsystems\vcpkg.cmake" - -if errorlevel 1 ( - echo If you continue to face CMAKE errors, make sure to install: - echo winget install Microsoft.VisualStudio.2022.BuildTools - echo Then run the "Developer Command Prompt for VS 2022" and launch this script from there. - exit /b 1 -) - -cmake --build build\ReleaseOV --config Release -if errorlevel 1 exit /b 1 - -echo ============================================ -echo Build completed successfully! -echo ============================================ -echo Binaries: %CD%\build\ReleaseOV\bin -echo. -echo NOTE: To run, source setupvars.bat and pick a device: -echo call "C:\Intel\openvino\setupvars.bat" -echo set GGML_OPENVINO_DEVICE=CPU^&^& REM or GPU / NPU -echo build\ReleaseOV\bin\llama-cli.exe -m model.gguf -echo. - -endlocal -``` - -> [!NOTE] -> The script pins OpenVINO `2026.5` via the `OPENVINO_VERSION_MAJOR` / `OPENVINO_VERSION_FULL` variables at the top — edit them to track a different release. From any new shell, source the matching `setupvars` script via the junction — `call "C:\Intel\openvino\setupvars.bat"` from `cmd`, or `& "C:\Intel\openvino\setupvars.ps1"` from PowerShell. If `winget` cannot register Visual Studio Build Tools on first run, install them once manually and re-run the script from an elevated **Developer Command Prompt for VS 2022**. - -
- -### 3. Download Sample Model - -Download a sample model for testing. - -```bash -mkdir -p ~/models/ -wget https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf \ - -O ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -``` - -
-Windows - -```powershell -# Windows PowerShell -mkdir C:\models -Invoke-WebRequest -Uri https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -OutFile C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf -``` - -```cmd -REM Windows Command Prompt -mkdir C:\models -curl -L https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -o C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf -``` - -
+- Windows: install OpenVINO in a path without spaces, such as `C:\Intel\openvino`. Some CMake and Ninja toolchains have quoting problems with `C:\Program Files (x86)\...`. +- Run the setupvars script of your shell in each new shell, also before you start the binaries: `setupvars.sh` in bash, `setupvars.bat` in cmd, `& "C:\Intel\openvino\setupvars.ps1"` in PowerShell. -### 4. Run Inference with OpenVINO Backend - -The first run of a model converts and compiles it for the device. This takes seconds on CPU and GPU, and can take minutes on the NPU for large models. Later tokens are faster, and the [compiled model cache](#compiled-model-cache) makes later runs start faster. - -> [!NOTE] -> Default context size is set to the model training context, which may be very large. For example, 131072 for Llama 3.2 1B, which may result in lower performance, especially on edge/laptop devices. Use `-c` to limit context size in supported llama.cpp tools for better performance: -> - CPU and GPU: for example `-c 1024`. -> - NPU: keep the context small, for example `-c 512`, or `-c 256` for larger models. Decode may slow down as the context grows. +## Docker ```bash -# If the device is unset, the CPU is used. -export GGML_OPENVINO_DEVICE=GPU -# To run llama-simple: -./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is " -# To run in chat mode: -./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -# To run llama-bench: -./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf - -# NPU: keep context small to avoid failures from very large model context windows. -export GGML_OPENVINO_DEVICE=NPU -./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 -``` - -
-Windows - -```cmd -REM Windows Command Prompt -set GGML_OPENVINO_DEVICE=GPU -REM To run llama-simple: -build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is " -REM To run in chat mode: -build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024 -REM To run llama-bench: -build\ReleaseOV\bin\llama-bench.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" - -REM NPU: keep the context small. -set GGML_OPENVINO_DEVICE=NPU -build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512 -``` - -```powershell -# Windows PowerShell -$env:GGML_OPENVINO_DEVICE = "GPU" -build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024 - -# NPU: keep the context small. -$env:GGML_OPENVINO_DEVICE = "NPU" -build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512 -``` - -
- -> [!NOTE] -> - Select the OpenVINO device with `GGML_OPENVINO_DEVICE`, not with `-dev`. -> - On systems with multiple GPUs, use `GPU.0` or `GPU.1` to target a specific GPU. -> - To split a model across several GPUs, set a comma-separated list, e.g. `GPU.0,GPU.1`, and use `-sm layer`. -> - A device that is not available is an error (no fallback to CPU). The error message lists the available OpenVINO devices with their names. -> - Run `llama-cli --list-devices` to see the valid values: each OpenVINO device shows the `GGML_OPENVINO_DEVICE=` to set, and `(selected)` marks the active one. -> - See [OpenVINO GPU Device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html) for more details. - -### 5. Docker Build - -You can build and run llama.cpp with OpenVINO backend using Docker. - -
-Build the images - -```bash -# Build the base runtime image with compiled shared libraries and minimal dependencies. -docker build --target=base -t llama-openvino:base -f .devops/openvino.Dockerfile . - -# Build the complete image with all binaries, Python tools, gguf-py library, and model conversion utilities. -docker build --target=full -t llama-openvino:full -f .devops/openvino.Dockerfile . - -# Build a minimal CLI image with the llama, llama-cli and llama-completion executables. +# Build the light image (llama-cli) and run it on the CPU, with the models in ~/models docker build --target=light -t llama-openvino:light -f .devops/openvino.Dockerfile . - -# Build a server-only image with llama-server executable, health check endpoint, and REST API support. -docker build --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile . - -# If you are behind a proxy: -docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile . -``` - -
- -
-Run a container (CPU, GPU, NPU) - -Run llama.cpp with OpenVINO backend Docker container. Save sample models in `~/models` as [shown above](#3-download-sample-model). It will be mounted to the container in the examples below. - -```bash -# Run Docker container docker run --rm -it -v ~/models:/models llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf - -# With Intel GPU access (iGPU or dGPU) -docker run --rm -it -v ~/models:/models \ ---device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \ ---env=GGML_OPENVINO_DEVICE=GPU \ -llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf - -# With Intel NPU access -docker run --rm -it -v ~/models:/models \ ---device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \ ---env=GGML_OPENVINO_DEVICE=NPU \ -llama-openvino:light --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -``` - -
- -
-Run llama-server (container or local build) and test it - -```bash -# Run the llama-openvino:server Docker container (CPU) -docker run --rm -it -p 8080:8080 -v ~/models:/models llama-openvino:server --no-warmup -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 --host 0.0.0.0 - -# Run the llama-openvino:server Docker container with Intel GPU access (iGPU or dGPU) -docker run --rm -it -v ~/models:/models \ ---device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \ --p 8080:8080 --env=GGML_OPENVINO_DEVICE=GPU \ -llama-openvino:server --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --host 0.0.0.0 - -# Run the llama-openvino:server Docker container with Intel NPU access -docker run --rm -it -v ~/models:/models \ ---device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \ --p 8080:8080 --env=GGML_OPENVINO_DEVICE=NPU \ -llama-openvino:server --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --host 0.0.0.0 - -# Or Using llama-server executable -./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024 - -# Option 1: Open your browser to http://localhost:8080 to open Llama Chat, the built-in chat app of the llama.cpp server. -# Option 2: In a NEW terminal, test the server with curl - -# If you are behind a proxy, make sure to set NO_PROXY to avoid proxy for localhost -export NO_PROXY=localhost,127.0.0.1 - -# Test health endpoint -curl -f http://localhost:8080/health - -# Test with a simple prompt -curl -X POST "http://localhost:8080/v1/chat/completions" -H "Content-Type: application/json" \ - -d '{"messages":[{"role":"user","content":"Write a poem about OpenVINO"}],"max_tokens":100}' | jq . ``` -
+Prebuilt images, the other targets, GPU and NPU access, and llama-server: [Docker](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#docker). -## Runtime Configuration +## Configuration -The backend needs no environment variable: it runs on the CPU with its defaults. Set `GGML_OPENVINO_DEVICE` to use the GPU or the NPU. All other variables are optional. - -```bash -export GGML_OPENVINO_DEVICE=GPU # String -export GGML_OPENVINO_PROFILING=1 # Integer -export GGML_OPENVINO_EXACT_ZERO_POINT=1 # Boolean: 1 (on) or 0 (off) - -# Show the variables in effect (log verbosity 4) -./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4 2>&1 | grep "settings from the environment" -``` +The backend needs no environment variable. It runs on the CPU with its defaults. Set `GGML_OPENVINO_DEVICE` to use the GPU or the NPU. All other variables are optional. - The backend reads the variables once, at start. Unset or empty means the default. -- To lower the memory a model needs, see [Memory optimization](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#memory-optimization). -- A value that is not valid stops the backend. A `GGML_OPENVINO_*` name that the backend does not know gives a warning: +- Boolean values are `1` (on) and `0` (off). +- A value that is not valid stops the backend. A `GGML_OPENVINO_*` name that the backend does not know gives a warning. +- `-lv 4` logs the variables in effect, on the `settings from the environment` line. +- To lower the memory that a model needs, see [Lower memory use](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#lower-memory-use). ```text ggml-openvino: GGML_OPENVINO_EXACT_ZERO_POINT=yes is not valid, use 1 (on) or 0 (off) @@ -846,46 +306,24 @@ ggml-openvino: unknown environment variable GGML_OPENVINO_DEVCE is ignored | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_DEVICE` | all | String | `CPU` | Target device: `CPU`, `GPU` or `NPU`. For several GPUs, see the [device notes](#4-run-inference-with-openvino-backend). Examples: `GGML_OPENVINO_DEVICE=NPU`, `GGML_OPENVINO_DEVICE=GPU.0,GPU.1`. | -| `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` | all | String | `not set` | Directory for the backend's cache of compiled models. A later start with the same model and settings loads faster. See [Compiled model cache](#compiled-model-cache). Example: `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache`. | -| `GGML_OPENVINO_NPU_CONFIG` | NPU | String | `not set` | OpenVINO properties for the NPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN"`. | -| `GGML_OPENVINO_GPU_CONFIG` | GPU | String | `not set` | OpenVINO properties for the GPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_GPU_CONFIG="INFERENCE_PRECISION_HINT=f16"`. | -| `GGML_OPENVINO_CPU_CONFIG` | CPU | String | `not set` | OpenVINO properties for the CPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16"`. | -| `GGML_OPENVINO_PROFILING` | all | Integer | `0` | `1` logs execution timing. `2` or higher also turns on OpenVINO and OpenCL profiling. Example: `GGML_OPENVINO_PROFILING=1`. | +| `GGML_OPENVINO_DEVICE` | all | String | `CPU` | Target device: `CPU`, `GPU`, `NPU`, or `GPU.0`, `GPU.1` with several GPUs. A list such as `GPU.0,GPU.1` with `-sm layer` splits a model across GPUs. See [device selection](#supported-devices). | +| `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` | all | String | `not set` | Directory for the cache of compiled models. Later starts with the same model and settings load faster. See [Compiled model cache](#compiled-model-cache). | +| `GGML_OPENVINO_NPU_CONFIG` | NPU | String | `not set` | OpenVINO properties for the NPU plugin. See [Plugin properties](#plugin-properties). | +| `GGML_OPENVINO_GPU_CONFIG` | GPU | String | `not set` | OpenVINO properties for the GPU plugin. See [Plugin properties](#plugin-properties). | +| `GGML_OPENVINO_CPU_CONFIG` | CPU | String | `not set` | OpenVINO properties for the CPU plugin. See [Plugin properties](#plugin-properties). | +| `GGML_OPENVINO_PROFILING` | all | Integer | `0` | `1` logs execution timing. `2` or higher also turns on OpenVINO and OpenCL profiling. See [Profiling](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#profiling-and-debug-dumps). | ### Plugin properties -`GGML_OPENVINO_NPU_CONFIG`, `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG` pass OpenVINO plugin properties to the device in their name. - -```bash -# Format: comma-separated KEY=VALUE pairs. The backend uses the variable of the selected device only. -export GGML_OPENVINO_DEVICE=NPU -export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=4" - -# CPU: compute in FP16, as the GPU and the NPU do. This helps to debug the accuracy of a quantized model. -export GGML_OPENVINO_DEVICE=CPU -export GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16" -``` +`GGML_OPENVINO_NPU_CONFIG`, `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG` pass OpenVINO plugin properties to the device in their name. The backend uses the variable of the selected device only. +- Format: comma-separated `KEY=VALUE` pairs, for example `GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=4"`. - Property names and values are those of OpenVINO, for example `YES` and `NO`. They are not the `1` and `0` of the `GGML_OPENVINO_*` variables. -- The backend applies the variable last, so it overrides the properties that the backend sets. Exception: `CACHE_DIR` and `CACHE_MODE` with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. +- The backend applies the variable last, so it overrides the properties that the backend sets. Exceptions: with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the backend sets `CACHE_DIR` and `CACHE_MODE` itself, and on the NPU also `NPUW_WEIGHTS_BANK`. - OpenVINO checks the properties when the model loads. If it rejects one, the load fails and the error names the variable. -- All properties and their values are in the OpenVINO documentation: [NPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/npu-device.html), [GPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html), [CPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.html). -- NPU: the backend sets several properties by default. They are listed in the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties). -- GPU and CPU: the backend sets no property, except: - - `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set. - - With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`: no `CACHE_DIR`, and `CACHE_MODE=OPTIMIZE_SPEED`. This overrides the same properties in `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG`. - - `ENABLE_PROFILING` with `GGML_OPENVINO_PROFILING=2` or higher. - - `EXECUTION_MODE_HINT` on the small graphs of op tests. - -`NPU_COMPILER_TYPE` selects the NPU compiler. Both forms below work; use the first one. If both are set, `GGML_OPENVINO_NPU_CONFIG` takes precedence. - -```bash -# Values: DRIVER (the compiler in the NPU driver; backend default), PLUGIN (the compiler in OpenVINO), -# PREFER_PLUGIN (OpenVINO default: PLUGIN when it is available, DRIVER if not). -export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN" # recommended form -export GGML_OPENVINO_NPU_COMPILER_TYPE=PLUGIN # older name, still works -``` +- `NPU_COMPILER_TYPE` selects the NPU compiler: `DRIVER` (in the NPU driver; backend default), `PLUGIN` (in OpenVINO) or `PREFER_PLUGIN` (`PLUGIN` when it is available, `DRIVER` if not). +- The properties that the backend sets: [NPU](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties), [GPU and CPU](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#gpu-and-cpu-plugin-properties). +- All properties and their values: [NPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/npu-device.html), [GPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html), [CPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.html). ### Advanced tuning @@ -896,195 +334,88 @@ The defaults fit most models. The variables below trade one property for another | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Number of tokens that the NPU processes in one prefill step. A larger value can make long prompts faster, and makes the first load longer. Zero or a negative value means the default. Example: `GGML_OPENVINO_PREFILL_CHUNK_SIZE=512`. | -| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | For models whose last layers reuse the KV cache of an earlier layer (Gemma 3n and Gemma 4 E2B/E4B): compile the prefill with only the KV-cache writes as outputs, which drops those layers and the output layer from it, and compute the output token of a batch with one decode step. Takes effect only without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state; with decode KV windows (`GGML_OPENVINO_NPU_BLOB_PREBUILD=1`) the output step runs the decode graph of the window that covers the output token. A batch that needs more than one output token switches to the full prefill. `0` turns it off. | -| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. When set, it also applies to a `Q4_K` or `Q5_K` `token_embd.weight`, which is otherwise stored as `q8_0_c`; with a tied output layer (Gemma 4 E2B) `q4_0_128` stores it in about half the memory. On the Panther Lake NPU, `f16` and `q4_0_128` can give wrong output. | -| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `0` | Look up the rows of large embedding tables (64 MiB or more) on the host, from the GGUF data, and pass them to the NPU graph as an input, instead of binding the whole table to the NPU. A table used only for such lookups, such as the per-layer embedding table of Gemma 3n and Gemma 4 E2B/E4B, is then not converted for the NPU at all. Lowers memory and decode time for such models. | -| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on. It takes effect only on the static path (NPU, or `GGML_OPENVINO_FORCE_STATIC=1`). Try `1` for Qwen3.5 on the Panther Lake NPU. | -| `GGML_OPENVINO_MANUAL_GQA_ATTN` | all | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. | -| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`, `Q8_0`, `Q5_1` and `Q5_0`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. | -| `GGML_OPENVINO_EXACT_ZERO_POINT` | CPU, GPU | Boolean | `0` | Keep the exact zero point of asymmetric weights (`Q4_1`, `Q4_K`, `Q5_1`, and `Q5_K` with `GGML_OPENVINO_REQUANT_KQUANT=native`) instead of rounding it to an integer. Requantized tensors keep an integer zero point; MoE expert weights always use the exact zero point. This improves accuracy and lowers speed. Use it when accuracy matters more than speed. | +| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Tokens in one NPU prefill step. A larger value can make long prompts faster and makes the first load longer. Zero or less means the default. | +| `GGML_OPENVINO_KV_ONLY_PREFILL` | NPU | Boolean | `1` | Gemma 3n and Gemma 4 E2B/E4B: the prefill graph only writes the KV cache, and one decode step computes the output token. Not for models with recurrent state. `0` turns it off. See [KV-only prefill](../../ggml/src/ggml-openvino/dev_doc/README.md#kv-only-prefill). | +| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | Layout of a `Q6_K` `token_embd.weight` on the NPU: `q8_0_c`, `f16`, `q4_0_128` or `q4_0_c`. When set, it also applies to `Q4_K` and `Q5_K`. The 4-bit layouts use less memory and can lower accuracy. With host gather on, a table of 64 MiB or more is not converted, so only a tied output layer changes. | +| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `1` | Read the rows of embedding tables of 64 MiB or more on the host, from the GGUF data. Such a table is then not converted for the NPU. Lowers memory use. `0` turns it off. See [NPU host gather](../../ggml/src/ggml-openvino/dev_doc/README.md#npu-host-gather). | +| `GGML_OPENVINO_ROPE_SINCOS` | all | String | `auto` | Where RoPE computes cos/sin. f16 angles lose accuracy at long positions. `host`: f32 tables on the host; static graphs (NPU), normal and NeoX RoPE only. `device`: on the device. `device_f32`: on the device with the angle in f32, for long prompts on the GPU. `auto`: `host` on the NPU, `device` elsewhere. | +| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations. Static path only (NPU). Unset: on for the Lunar Lake NPU, off elsewhere. Try `1` for Qwen3.5 on the Panther Lake NPU. | +| `GGML_OPENVINO_MANUAL_GQA_ATTN` | all | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. Try `1` on the CPU for faster decode. | +| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to 4 bits instead of `Q8_0_C`: `q4_asym64`, `q4_asym64_all` (also `Q4_K`, `Q8_0`, `Q5_1`, `Q5_0`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`), or `native` (none). GPU with `Q4_K_M`: use `q4_asym64_all`, `q4_asym64` does not compile there. | +| `GGML_OPENVINO_EXACT_ZERO_POINT` | CPU, GPU | Boolean | `0` | Keep the exact zero point of asymmetric weights (`Q4_1`, `Q4_K`, `Q5_1`, and `Q5_K` with `native`) instead of an integer one. Higher accuracy, lower speed. MoE expert weights always use it. | ### Compiled model cache -The cache keeps compiled models on disk, so later starts of the same model load faster. Use the same model and the same settings in every run. - -```bash -# CPU or GPU: the first run compiles the model and writes the cache. Later runs read it. -export GGML_OPENVINO_DEVICE=GPU -export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache -./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 - -# CPU or GPU, later runs (optional): require the cached model and skip the weight upload and the compilation. -export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 - -# NPU: valid cached models are imported. Otherwise the run compiles them, writes them without weights plus one -# shared weights file, and logs a warning. -export GGML_OPENVINO_DEVICE=NPU -export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache -./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 - -# NPU, later runs (optional): use less memory. The run fails if a cached model is missing. -export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 -``` - -
-Cache variables +The cache keeps compiled models on disk, so later starts of the same model load faster. Use the same model and the same settings in every run. Recipes: [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#compiled-model-cache). Internals and restrictions: [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/README.md#compiled-model-cache). | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. Does not work for MoE models on CPU, which are not written to the cache. | -| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` with an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing, for example after a change of the model, `-c` or another setting; run once without it to build the cache. | +| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require the cached model and skip the weight upload and the compilation. Needs mmap loading and a model that runs fully on OpenVINO. Not for MoE models on CPU. | +| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing. | | `GGML_OPENVINO_CACHE_DIR` | all | String | `not set` | Directory for the cache of the OpenVINO plugin itself. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache. | -- One directory can hold the cached models of different models and settings. -- NPU, with the default settings: the first prompt writes the prefill model of every KV window up to `-c`, so later runs with the same `-c` find a cached model for any prompt length. -- See [Compiled model cache](../../ggml/src/ggml-openvino/dev_doc/README.md#compiled-model-cache) for the workflow and the restrictions. - -
- ### Deprecated | Variable | Device | Type | Default | Description | |---|---|---|---|---| | `GGML_OPENVINO_STATEFUL_EXECUTION` | CPU, GPU | Boolean | `0` | **Deprecated**, to be removed. Keep the KV cache inside the OpenVINO model. Use the default, stateless execution (`0`). | -
-Limits of stateful execution +### Developer variables -- CPU and GPU only; it has no effect on the NPU. -- One slot only (`-np 1`). -- State save and restore, sequence rewind, context shift and recurrent rollback are not supported. -- Models with recurrent state (for example Qwen3.5) need a graph that runs fully on OpenVINO, with the in-process cache on (`GGML_OPENVINO_DISABLE_CACHE` unset). -- A prompt that starts at position 0 resets all states. - -
- -### Debugging and development - -Debug output, switches that turn a default optimization off, experimental options and older variable names are in the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md). - -### Example Usage - -#### GPU Inference with Profiling - -```bash -export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache -export GGML_OPENVINO_PROFILING=1 -export GGML_OPENVINO_DEVICE=GPU - -./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is " -``` - -
-Windows - -```cmd -REM Windows Command Prompt -set GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=C:\tmp\ov_cache -set GGML_OPENVINO_PROFILING=1 -set GGML_OPENVINO_DEVICE=GPU -build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is " -``` - -```powershell -# Windows PowerShell -$env:GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR = "C:\tmp\ov_cache" -$env:GGML_OPENVINO_PROFILING = "1" -$env:GGML_OPENVINO_DEVICE = "GPU" -build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is " -``` - -
+Debug output, switches that turn a default optimization off, experimental options, memory options and older variable names are in [OpenVINO-ENV-VARS.md](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md). ## Known Limitations **General (all devices)** -- Llama.cpp OpenVINO backend currently supports a subset of GGML ops. Unsupported ops or unsupported op shapes/cases fail during OpenVINO translation. -- Image input is experimental: Qwen3.5 and Gemma 4 E2B image input runs on CPU and GPU. NPU: work in progress, image input fails because of dynamic shapes. See [Multimodal](../../ggml/src/ggml-openvino/dev_doc/README.md#multimodal). Audio input is a work in progress. -- Qwen3-VL image input ([Multimodal](../../ggml/src/ggml-openvino/dev_doc/README.md#multimodal)): +- The backend supports a subset of GGML ops. An unsupported op, or an unsupported shape or case of an op, fails during OpenVINO translation. +- Image input is experimental. Qwen3.5 and Gemma 4 E2B image input runs on CPU and GPU. NPU: work in progress; image input fails because of dynamic shapes. Audio input is a work in progress. See [Image input](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#image-input) and [Multimodal](../../ggml/src/ggml-openvino/dev_doc/README.md#multimodal). +- Qwen3-VL image input: - CPU: needs a 32 GB system (peak about 14 GB of RAM). - GPU on a 16 GB system: the default `-ub 512` runs out of memory. - - **Workaround:** `-ub 128` or `--image-max-tokens 256`. + - **Workaround:** `--image-max-tokens 256`. With `-ub 128` alone, a large image can still run out of memory. - NPU: work in progress. - Embedding models: reranking models are not validated. -- Llama.cpp tool coverage across CPU/GPU/NPU is not uniform. -- Mamba-based models (e.g. Falcon-H1): `llama-perplexity` with several sequences per batch fails; set `-b` to the same value as `-c`. On CPU and GPU, the perplexity is slightly higher than with the ggml CPU backend. +- llama.cpp tool coverage is not uniform across CPU, GPU and NPU. +- Mamba-based models (for example Falcon-H1): on CPU and GPU, the perplexity is slightly higher than with the ggml CPU backend. **GPU-specific** -- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM): - - ```bash - export GGML_OPENVINO_DEVICE=GPU - export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs - export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts - mkdir -p $GGML_OPENVINO_SPILL_DIR - ./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md .gguf \ - --spec-type draft-dflash --spec-draft-n-max 4 - ``` +- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM). See [Muse-Glimmer-30B](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu). - Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`): - - `-sm tensor` is not supported. + - `-sm tensor` is not supported. Context creation fails with `Context was not initialized using remote implementation`. - Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy. - Only GPUs can be combined. A list with several NPUs, or with a GPU and the CPU or the NPU, is rejected. -- MoE models use the GPU plugin's fused MoE op, which runs in f16 only: - - granitemoe models (e.g. `granite-3.1-1b-a400m`) give wrong output. - - **Workaround:** `GGML_OPENVINO_MOE_OP=0`. Output is correct, but prompt processing is much slower. +- MoE models run in f16 only on the GPU, with or without the fused MoE op (`GGML_OPENVINO_MOE_OP`): + - granitemoe models (for example `granite-3.1-1b-a400m`) can give wrong output (one repeated token) after a short prompt. + - **Workaround:** `GGML_OPENVINO_MOE_OP=0`. The output is correct, but prompt processing is much slower. - `GGML_OPENVINO_GPU_CONFIG="INFERENCE_PRECISION_HINT=f32"` fails to compile. -- `llama-perplexity` with MoE models: set `-b` to the same value as `-c`, so that each batch holds one sequence. +- `llama-perplexity` with MoE models: set `-b` to the `-c` value, so that each batch holds one sequence. **NPU-specific** -- Default context resolves to the model's training context (e.g. 131072 for Llama 3.2 1B), which can OOM or fail or degrade performance on NPU. Inspect the resolved value with `-lv 3`. - - **Workaround:** Pass an explicit `-c `, e.g. `-c 512`. -- NPU device uses a static graph with a fixed prefill chunk size (defaults to 256), configurable with `GGML_OPENVINO_PREFILL_CHUNK_SIZE`. Large prefill/batch settings may need tuning. -- `llama-server -np > 1` (multiple parallel sequences) is not supported. -- `llama-perplexity`: requires `-b 512` or smaller. -- Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU. -- `llama-embedding` fails on the NPU. -- Mamba-based models (e.g. Falcon-H1) fail on the NPU with `Failed to set tensor` (element type mismatch). +- The default context is the training context of the model (for example 131072 for Llama 3.2 1B). On the NPU, this can run out of memory, fail or lower performance. `-lv 3` shows the value in use. + - **Workaround:** pass `-c `, for example `-c 512`. See [NPU context and prefill chunk](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#npu-context-and-prefill-chunk). +- The NPU uses a static graph with a fixed prefill chunk size (default 256), set with `GGML_OPENVINO_PREFILL_CHUNK_SIZE`. Large prefill or batch settings can need tuning. +- `llama-server -np N` with N greater than 1 needs the unified KV cache (`-kvu`). Without it, requests fail with `n_seq > 1 is not supported on NPU`. Without `-np`, llama-server uses 4 slots with the unified KV cache. See [llama-server](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#llama-server). +- `llama-perplexity`: set `-b` to at most `-c`, so that each batch holds one sequence, and `-ub` to the prefill chunk size (default 256). With the default `-ub 512`, the result at `-c 1024` and above is wrong. See [Embeddings and perplexity](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#embeddings-and-perplexity). +- Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU. llama-server with the unified KV cache turns flash attention off by itself, and that case runs. +- Embedding models do not work on the NPU. BERT models (bge-m3, nomic-embed-text) fail. Qwen3-Embedding runs, but its embeddings differ from the CPU ones. +- Mamba-based models (for example Falcon-H1) do not run on the NPU. The process stops with a floating-point exception (SIGFPE) during the NPU compilation. - Lunar Lake NPU: decode slows down sharply when the context is large. The context size at which this starts depends on the model. - - **Workaround:** Pass the smallest context that fits the use, e.g. `-c 512`, or `-c 256` for larger models. -- Panther Lake NPU: `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=f16` and `q4_0_128` can give wrong output. Keep the default. + - **Workaround:** pass the smallest context that fits the use, for example `-c 512`, or `-c 256` for larger models. - Lunar Lake NPU: `granite-4.0-1b` gives wrong output. The activations of the model exceed the FP16 range, and the NPU computes in FP16. The model runs correctly on CPU and GPU. -- Lunar Lake NPU: `gemma-4-12B` does not run. The first inference fails with `ZE_RESULT_ERROR_UNINITIALIZED` from the NPU driver. The model runs on CPU and GPU. -- Lunar Lake NPU with NPU driver 1.39.1: `gemma-4-E2B` and `gemma-4-E4B` do not run. The compilation in the NPU driver fails with `ZE_RESULT_ERROR_INVALID_ARGUMENT`. NPU driver 1.38.0 runs them, and the models run on CPU and GPU. The Docker image installs NPU driver 1.39.1. - - **Workaround:** Use NPU driver 1.38.0. -- The first load of a model on the NPU compiles it for the device, which can take minutes for large models. - - **Workaround:** Use the [compiled model cache](#compiled-model-cache). +- Lunar Lake NPU with NPU driver 1.39.1: with `GGML_OPENVINO_NPU_HOST_GATHER=0`, `gemma-4-E2B` and `gemma-4-E4B` fail to compile (`ZE_RESULT_ERROR_INVALID_ARGUMENT`). Keep the default (`1`). +- The first load of a model on the NPU compiles it for the device. This can take minutes for large models. + - **Workaround:** use the [compiled model cache](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#npu-gemma-4-e2b-example). - `Ling-mini-2.0` (MoE with a sigmoid router) does not run on the NPU. The compilation in the NPU driver fails with `Cannot create GatherMatmul layer ... from unsupported opset`. The model runs on CPU and GPU. - MoE models with a softmax router and SwiGLU experts (for example Qwen3.6-35B-A3B) run on the NPU through the MoE support of NPUW: only the routed experts run for each token, with the router on the host. Tested with `Qwen3.6-35B-A3B-Q4_0` on Panther Lake (Windows) and Lunar Lake (Windows, Ubuntu) systems with 32 GB. - - Requires OpenVINO 2026.5 or later. These models depend on two NPUW changes that 2026.4.1 does not have, [#38123](https://github.com/openvinotoolkit/openvino/pull/38123) (MoE mixing scores) and [#38124](https://github.com/openvinotoolkit/openvino/pull/38124) (batched MoE matching). With 2026.4.1 the model runs without an error, but the output is wrong. - - A 35B MoE model needs nearly all of a 32 GB system: the backend and NPUW each hold a copy of the weights (about 18 GB each), and the NPU can address 18 GB of the shared memory. Use a small context and these settings: - - ```bash - export GGML_OPENVINO_DEVICE=NPU - export GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 - export GGML_OPENVINO_NPU_CONFIG="NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1" - ./build/ReleaseOV/bin/llama-cli -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256 - ``` - - ```bat - REM Windows - set GGML_OPENVINO_DEVICE=NPU - set GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 - set GGML_OPENVINO_NPU_CONFIG=NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1 - build\ReleaseOV\bin\llama-cli.exe -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256 - ``` - - - `NPUW_WEIGHTS_BANK_ALLOC=CPU` keeps the NPUW copy of the weights in host memory instead of the NPU-addressable memory, at some cost in speed. - - `NPUW_FUNCALL_ASYNC=NO` and `COMPILATION_NUM_THREADS=1` lower the memory peak. `GGML_OPENVINO_COMPILATION_NUM_THREADS=1` is an older name for the second one. - - The backend sets `NPUW_MOE_POOL_SIZE=0` and `NPUW_MOE_TOKEN_CHUNK_SIZE=16` itself for MoE models (see the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties)). Without them the load can hang on a 32 GB system. - - The NPU compiler type can stay unset: models with `GATED_DELTA_NET` layers, such as Qwen3.6, then compile with the compiler in OpenVINO. `NPU_COMPILER_TYPE=PREFER_PLUGIN` gives the same result. - - Linux: the NPU reports almost all of the system memory, so `--fit` keeps every weight in the backend, and a 32 GB system swaps heavily. Pass `--fit-target 16384`: `--fit` then leaves part of the expert weights in the memory-mapped model file, as it does on Windows, where the NPU reports 16 GB. The graph still runs on the NPU alone. + - Requires OpenVINO 2026.5 or later. + - A 35B MoE model needs nearly all of a 32 GB system. Use a small context and the settings in [Qwen3.6-35B-A3B on the NPU](../../ggml/src/ggml-openvino/dev_doc/COOKBOOK.md#qwen36-35b-a3b-on-the-npu). - `llama-perplexity` with these models: use a `-c` of at most twice `GGML_OPENVINO_PREFILL_CHUNK_SIZE` (for example `-c 256` with a chunk size of 128). The output rows of the last layer must not exceed the chunk size. -> [!NOTE] -> The OpenVINO backend is actively under development. Fixes and improvements are underway, and this document will continue to be updated. - ## Work in Progress - Performance and memory optimizations diff --git a/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md new file mode 100644 index 000000000000..09a45d74a3eb --- /dev/null +++ b/ggml/src/ggml-openvino/dev_doc/COOKBOOK.md @@ -0,0 +1,806 @@ +# llama.cpp OpenVINO backend cookbook + +Recipes for the OpenVINO backend, one section per task. + +- Quick Start, supported devices, build basics and the user environment variables: [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md). +- Internals: [developer documentation](README.md). Developer variables: [OpenVINO-ENV-VARS.md](OpenVINO-ENV-VARS.md). + +```bash +# The examples assume a Linux build in build/ReleaseOV, models in ~/models, and OpenVINO set up in the shell +source /opt/intel/openvino/setupvars.sh +``` + +## Contents + +- [Build from source](#build-from-source) + - [Ubuntu build script](#ubuntu-build-script) + - [Windows build script](#windows-build-script) +- [Docker](#docker) +- [Run on each device](#run-on-each-device) + - [Linux](#linux) + - [Windows](#windows) + - [llama-server](#llama-server) + - [NPU context and prefill chunk](#npu-context-and-prefill-chunk) + - [Multiple GPUs](#multiple-gpus) +- [Compiled model cache](#compiled-model-cache) + - [CPU and GPU](#cpu-and-gpu) + - [NPU: gemma-4 E2B example](#npu-gemma-4-e2b-example) +- [Lower memory use](#lower-memory-use) +- [Large MoE models](#large-moe-models) + - [Qwen3.6-35B-A3B on the NPU](#qwen36-35b-a3b-on-the-npu) + - [Muse-Glimmer-30B with a DFlash draft on the GPU](#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu) +- [Speculative decoding](#speculative-decoding) +- [Image input](#image-input) +- [Embeddings and perplexity](#embeddings-and-perplexity) +- [Profiling and debug dumps](#profiling-and-debug-dumps) + +## Build from source + +The scripts install the build prerequisites and OpenVINO Runtime 2026.5. Then they build llama.cpp with the OpenVINO backend in `llama.cpp/build/ReleaseOV`. + +- The scripts do not install the GPU and NPU drivers. The Ubuntu script installs only the `intel-opencl-icd` package of the distribution. See [Prerequisites](../../../../docs/backend/OPENVINO.md#prerequisites). +- The scripts pin OpenVINO 2026.5 in `OPENVINO_VERSION_MAJOR` and `OPENVINO_VERSION_FULL`. Edit them to use another release. + +### Ubuntu build script + +The script installs the build tools and the OpenCL ICD, downloads and sets up OpenVINO Runtime, and builds llama.cpp with Ninja. Save it as `build-llamacpp-ov.sh` in the folder where the `llama.cpp` folder goes, then run it: + +```bash +chmod +x build-llamacpp-ov.sh +./build-llamacpp-ov.sh +``` + +```bash +#!/usr/bin/env bash +# ============================================ +# llama.cpp OpenVINO Build Script (Ninja) +# ============================================ +set -euo pipefail + +OPENVINO_VERSION_MAJOR="2026.5" +OPENVINO_VERSION_FULL="2026.5.0.23836.73088206582" + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +OPENVINO_INSTALL_DIR="/opt/intel/openvino_${OPENVINO_VERSION_MAJOR}" +OPENVINO_LINK_DIR="/opt/intel/openvino" +OPENVINO_TGZ="${SCRIPT_DIR}/openvino.tgz" +UBUNTU_MAJOR="$(. /etc/os-release && echo "${VERSION_ID%%.*}")" # 22, 24 or 26 +OPENVINO_URL="https://storage.openvinotoolkit.org/repositories/openvino/packages/${OPENVINO_VERSION_MAJOR}/linux/openvino_toolkit_ubuntu${UBUNTU_MAJOR}_${OPENVINO_VERSION_FULL}_x86_64.tgz" + +case "${UBUNTU_MAJOR}" in + 22|24|26) ;; + *) echo "Unsupported Ubuntu version ${UBUNTU_MAJOR}: OpenVINO archives exist for Ubuntu 22, 24 and 26." >&2; exit 1 ;; +esac + +echo "============================================" +echo "Installing prerequisites (apt)..." +echo "============================================" +sudo apt-get update +sudo apt-get install -y \ + build-essential libssl-dev libtbb12 \ + cmake ninja-build python3-pip \ + curl wget tar git + +echo "============================================" +echo "Installing OpenCL runtime + headers..." +echo "============================================" +sudo apt-get install -y \ + ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd + +cd "${SCRIPT_DIR}" + +# ============================================ +# Clone llama.cpp if missing +# ============================================ +if [[ ! -f "llama.cpp/CMakeLists.txt" ]]; then + echo "Cloning llama.cpp..." + git clone https://github.com/ggml-org/llama.cpp +fi + +# ============================================ +# Setup OpenVINO: download & extract to /opt/intel/openvino_${OPENVINO_VERSION_MAJOR}, then point /opt/intel/openvino at it via symlink so the active version is swappable. +# ============================================ +if [[ -f "${OPENVINO_INSTALL_DIR}/setupvars.sh" ]]; then + echo "OpenVINO ${OPENVINO_VERSION_MAJOR} already installed at ${OPENVINO_INSTALL_DIR}. Skipping download." +else + echo "OpenVINO not found at ${OPENVINO_INSTALL_DIR}. Starting download..." + curl -fL -o "${OPENVINO_TGZ}" "${OPENVINO_URL}" + + echo "Extracting OpenVINO to ${OPENVINO_INSTALL_DIR}..." + sudo mkdir -p "${OPENVINO_INSTALL_DIR}" + sudo tar -xzf "${OPENVINO_TGZ}" -C "${OPENVINO_INSTALL_DIR}" --strip-components=1 + rm -f "${OPENVINO_TGZ}" +fi + +# Refresh symlink: /opt/intel/openvino -> /opt/intel/openvino_${OPENVINO_VERSION_MAJOR} +sudo ln -sfn "${OPENVINO_INSTALL_DIR}" "${OPENVINO_LINK_DIR}" + +OPENVINO_ROOT="${OPENVINO_LINK_DIR}" +echo "OpenVINO Ready: ${OPENVINO_ROOT} -> ${OPENVINO_INSTALL_DIR}" + +# Install OpenVINO's own runtime dependencies (one-time per system). +if [[ -x "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh" ]]; then + echo "============================================" + echo "Installing OpenVINO runtime dependencies..." + echo "============================================" + echo "Y" | sudo -E "${OPENVINO_ROOT}/install_dependencies/install_openvino_dependencies.sh" +fi + +# ============================================ +# Clean old build cache +# ============================================ +cd "${SCRIPT_DIR}/llama.cpp" +if [[ -d "build/ReleaseOV" ]]; then + echo "Removing old build directory..." + rm -rf "build/ReleaseOV" +fi + +echo "============================================" +echo "Configuring with CMake..." +echo "============================================" +set +u +source "${OPENVINO_ROOT}/setupvars.sh" +set -u + +cmake -B build/ReleaseOV -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DGGML_OPENVINO=ON + +cmake --build build/ReleaseOV --parallel + +echo "============================================" +echo "Build completed successfully!" +echo "============================================" +echo "Binaries: $(pwd)/build/ReleaseOV/bin" +echo +echo "NOTE: To run, source setupvars.sh and pick a device:" +echo " source /opt/intel/openvino/setupvars.sh" +echo " export GGML_OPENVINO_DEVICE=CPU # or GPU / NPU" +echo " ./build/ReleaseOV/bin/llama-cli -m model.gguf" +``` + +### Windows build script + +The script installs Git, Ninja, CMake, Visual Studio 2022 Build Tools and OpenCL (with vcpkg). Then it downloads OpenVINO Runtime and builds llama.cpp with Ninja. Save it as `build-llamacpp-ov.bat` in the folder where the `llama.cpp` folder goes, then run it from Command Prompt or PowerShell: + +```cmd +:: Command Prompt +build-llamacpp-ov.bat +``` + +```powershell +# PowerShell +.\build-llamacpp-ov.bat +``` + +```bat +@echo off +setlocal enabledelayedexpansion + +REM ============================================ +REM llama.cpp OpenVINO Build Script (Ninja) +REM ============================================ + +set "OPENVINO_VERSION_MAJOR=2026.5" +set "OPENVINO_VERSION_FULL=2026.5.0.23836.73088206582" + +set "SCRIPT_DIR=%~dp0" +set "VCPKG_DIR=C:\vcpkg" +set "OPENVINO_INSTALL_DIR=C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%" +set "OPENVINO_LINK_DIR=C:\Intel\openvino" +set "OPENVINO_ZIP=%SCRIPT_DIR%openvino.zip" +set "OPENVINO_EXTRACT_TMP=%SCRIPT_DIR%openvino_extract_tmp" +set "OPENVINO_URL=https://storage.openvinotoolkit.org/repositories/openvino/packages/%OPENVINO_VERSION_MAJOR%/windows/openvino_toolkit_windows_%OPENVINO_VERSION_FULL%_x86_64.zip" + +echo ============================================ +echo Installing prerequisites... +echo ============================================ +winget install --id Git.Git -e --accept-source-agreements --accept-package-agreements 2>nul +winget install --id Ninja-build.Ninja -e --accept-source-agreements --accept-package-agreements 2>nul +winget install --id Kitware.CMake -e --accept-source-agreements --accept-package-agreements 2>nul + +REM Ensure Visual Studio Build Tools are installed. +echo Checking for Visual Studio Build Tools... +set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +set "VS_INSTALLED=" +if exist "%VSWHERE%" ( + for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2^>nul`) do ( + set "VS_INSTALLED=%%i" + ) +) +if defined VS_INSTALLED ( + echo Visual Studio with VC++ x86/x64 tools already present at "!VS_INSTALLED!". Skipping winget install. +) else ( + winget install --id Microsoft.VisualStudio.2022.BuildTools -e --override "--wait --passive --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended" --accept-source-agreements --accept-package-agreements + if errorlevel 1 ( + echo WARNING: winget could not install Visual Studio Build Tools automatically. + echo Install manually from https://aka.ms/vs/17/release/vs_BuildTools.exe ^(select the "Desktop development with C++" workload^) + echo and re-run this script from a "Developer Command Prompt for VS 2022". + ) +) + +echo ============================================ +echo Installing OpenCL via vcpkg... +echo ============================================ +if not exist "%VCPKG_DIR%" ( + git clone https://github.com/microsoft/vcpkg "%VCPKG_DIR%" + cd /d "%VCPKG_DIR%" + call bootstrap-vcpkg.bat + call vcpkg integrate install +) +cd /d "%VCPKG_DIR%" +call vcpkg install opencl + +cd /d "%SCRIPT_DIR%" + +REM ============================================ +REM Clone llama.cpp if missing +REM ============================================ +if not exist "llama.cpp\CMakeLists.txt" ( + echo Cloning llama.cpp... + git clone https://github.com/ggml-org/llama.cpp +) + +cd /d "llama.cpp" +set "SCRIPT_DIR=%CD%" + +REM ============================================ +REM Setup OpenVINO: download & extract to C:\Intel\openvino_%OPENVINO_VERSION_MAJOR%, then point C:\Intel\openvino at it via a directory junction (mklink /J). +REM ============================================ + +if exist "%OPENVINO_INSTALL_DIR%\setupvars.bat" ( + echo OpenVINO %OPENVINO_VERSION_MAJOR% already installed at "%OPENVINO_INSTALL_DIR%". Skipping download. +) else ( + echo OpenVINO not found at "%OPENVINO_INSTALL_DIR%". Starting download... + + curl -L -o "%OPENVINO_ZIP%" "%OPENVINO_URL%" + if errorlevel 1 ( + echo ERROR: Download failed. + exit /b 1 + ) + + echo Extracting OpenVINO... + if exist "%OPENVINO_EXTRACT_TMP%" rmdir /s /q "%OPENVINO_EXTRACT_TMP%" + mkdir "%OPENVINO_EXTRACT_TMP%" + tar -xf "%OPENVINO_ZIP%" -C "%OPENVINO_EXTRACT_TMP%" + if errorlevel 1 ( + echo ERROR: Extraction failed. + exit /b 1 + ) + + REM Move the single top-level folder contents into the versioned install dir. + set "OPENVINO_EXTRACTED=" + for /d %%i in ("%OPENVINO_EXTRACT_TMP%\*") do set "OPENVINO_EXTRACTED=%%i" + if not defined OPENVINO_EXTRACTED ( + echo ERROR: Could not locate extracted OpenVINO folder under "%OPENVINO_EXTRACT_TMP%". + exit /b 1 + ) + if not exist "%OPENVINO_INSTALL_DIR%" mkdir "%OPENVINO_INSTALL_DIR%" + xcopy /e /i /y /q "!OPENVINO_EXTRACTED!\*" "%OPENVINO_INSTALL_DIR%\" >nul + if errorlevel 1 ( + echo ERROR: Failed to copy OpenVINO from "!OPENVINO_EXTRACTED!" to "%OPENVINO_INSTALL_DIR%". + echo Re-run this script from an elevated Command Prompt ^(Run as administrator^) if access is denied. + exit /b 1 + ) + + rmdir /s /q "%OPENVINO_EXTRACT_TMP%" + del "%OPENVINO_ZIP%" +) + +REM Refresh junction: C:\Intel\openvino -> C:\Intel\openvino_. +REM `mklink /J` creates a directory junction (no admin / Developer Mode required). +if exist "%OPENVINO_LINK_DIR%" rmdir "%OPENVINO_LINK_DIR%" +mklink /J "%OPENVINO_LINK_DIR%" "%OPENVINO_INSTALL_DIR%" >nul +if errorlevel 1 ( + echo ERROR: Failed to create junction "%OPENVINO_LINK_DIR%" -^> "%OPENVINO_INSTALL_DIR%". + echo If "%OPENVINO_LINK_DIR%" already exists as a regular non-empty folder, remove it manually and re-run. + exit /b 1 +) + +set "OPENVINO_ROOT=%OPENVINO_LINK_DIR%" +echo OpenVINO Ready: %OPENVINO_ROOT% -^> %OPENVINO_INSTALL_DIR% + + +echo ============================================ +echo Setting up compiler environment... +echo ============================================ +REM Locate Visual Studio Build Tools vcvars64.bat +set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +if exist "%VSWHERE%" ( + for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do ( + set "VS_PATH=%%i" + ) +) +if defined VS_PATH ( + call "%VS_PATH%\VC\Auxiliary\Build\vcvars64.bat" >nul +) else ( + echo WARNING: Visual Studio Build Tools not found. Compiler may be missing. +) + +REM ============================================ +REM Clean old build cache +REM ============================================ +if exist "build\ReleaseOV" ( + echo Removing old build directory ... + rmdir /s /q "build\ReleaseOV" +) + +echo ============================================ +echo Configuring with CMake... +echo ============================================ +call "%OPENVINO_ROOT%\setupvars.bat" >nul 2>nul + +cmake -B build\ReleaseOV -G Ninja ^ + -DCMAKE_BUILD_TYPE=Release ^ + -DGGML_OPENVINO=ON ^ + -DCMAKE_TOOLCHAIN_FILE="%VCPKG_DIR%\scripts\buildsystems\vcpkg.cmake" + +if errorlevel 1 ( + echo If you continue to face CMAKE errors, make sure to install: + echo winget install Microsoft.VisualStudio.2022.BuildTools + echo Then run the "Developer Command Prompt for VS 2022" and launch this script from there. + exit /b 1 +) + +cmake --build build\ReleaseOV --config Release +if errorlevel 1 exit /b 1 + +echo ============================================ +echo Build completed successfully! +echo ============================================ +echo Binaries: %CD%\build\ReleaseOV\bin +echo. +echo NOTE: To run, source setupvars.bat and pick a device: +echo call "C:\Intel\openvino\setupvars.bat" +echo set GGML_OPENVINO_DEVICE=CPU^&^& REM or GPU / NPU +echo build\ReleaseOV\bin\llama-cli.exe -m model.gguf +echo. + +endlocal +``` + +- In a new shell, run the setupvars script through the junction: `call "C:\Intel\openvino\setupvars.bat"` in cmd, or `& "C:\Intel\openvino\setupvars.ps1"` in PowerShell. +- If winget cannot register Visual Studio Build Tools on the first run, install them once by hand. Then run the script again from an elevated **Developer Command Prompt for VS 2022**. + +## Docker + +The images come from [.devops/openvino.Dockerfile](../../../../.devops/openvino.Dockerfile). Prebuilt images for `linux/amd64` are on the GitHub Container Registry: + +```bash +# full: all binaries and the Python tools; light: llama-cli and llama-completion; server: llama-server +docker pull ghcr.io/ggml-org/llama.cpp:full-openvino +docker pull ghcr.io/ggml-org/llama.cpp:light-openvino +docker pull ghcr.io/ggml-org/llama.cpp:server-openvino +``` + +Build the images locally: + +```bash +# Build the base runtime image with compiled shared libraries and minimal dependencies. +docker build --target=base -t llama-openvino:base -f .devops/openvino.Dockerfile . + +# Build the complete image with all binaries, Python tools, gguf-py library, and model conversion utilities. +docker build --target=full -t llama-openvino:full -f .devops/openvino.Dockerfile . + +# Build a minimal CLI image with the llama, llama-cli and llama-completion executables. +docker build --target=light -t llama-openvino:light -f .devops/openvino.Dockerfile . + +# Build a server-only image with llama-server executable, health check endpoint, and REST API support. +docker build --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile . + +# If you are behind a proxy: +docker build --build-arg http_proxy=$http_proxy --build-arg https_proxy=$https_proxy --target=server -t llama-openvino:server -f .devops/openvino.Dockerfile . +``` + +Run a container on the CPU, GPU or NPU. The examples mount the models in `~/models`. For a prebuilt image, use `ghcr.io/ggml-org/llama.cpp:light-openvino` instead of `llama-openvino:light`. + +```bash +# Run the container on the CPU +docker run --rm -it -v ~/models:/models llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf + +# With Intel GPU access (iGPU or dGPU) +docker run --rm -it -v ~/models:/models \ +--device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \ +--env=GGML_OPENVINO_DEVICE=GPU \ +llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf + +# With Intel NPU access +docker run --rm -it -v ~/models:/models \ +--device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \ +--env=GGML_OPENVINO_DEVICE=NPU \ +llama-openvino:light --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf +``` + +Run llama-server in a container. The server image listens on `0.0.0.0:8080`. Test it as in [llama-server](#llama-server). + +```bash +# Run the llama-openvino:server Docker container (CPU) +docker run --rm -it -p 8080:8080 -v ~/models:/models llama-openvino:server --no-warmup -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 + +# Run the llama-openvino:server Docker container with Intel GPU access (iGPU or dGPU) +docker run --rm -it -v ~/models:/models \ +--device=/dev/dri --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \ +-p 8080:8080 --env=GGML_OPENVINO_DEVICE=GPU \ +llama-openvino:server --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf + +# Run the llama-openvino:server Docker container with Intel NPU access +docker run --rm -it -v ~/models:/models \ +--device=/dev/accel --group-add=$(stat -c "%g" /dev/accel/accel* | head -n 1) -u $(id -u):$(id -g) \ +-p 8080:8080 --env=GGML_OPENVINO_DEVICE=NPU \ +llama-openvino:server --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf +``` + +## Run on each device + +### Linux + +```bash +# If the device is unset, the CPU is used. +export GGML_OPENVINO_DEVICE=GPU +# To run llama-simple: +./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is " +# To run in chat mode: +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +# To run llama-bench: +./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf + +# NPU +export GGML_OPENVINO_DEVICE=NPU +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 +``` + +### Windows + +Download a model: + +```powershell +# Windows PowerShell +mkdir C:\models +Invoke-WebRequest -Uri https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -OutFile C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf +``` + +```cmd +REM Windows Command Prompt +mkdir C:\models +curl -L https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -o C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf +``` + +Run it: + +```cmd +REM Windows Command Prompt +set GGML_OPENVINO_DEVICE=GPU +REM To run llama-simple: +build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is " +REM To run in chat mode: +build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024 +REM To run llama-bench: +build\ReleaseOV\bin\llama-bench.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" + +REM NPU +set GGML_OPENVINO_DEVICE=NPU +build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512 +``` + +```powershell +# Windows PowerShell +$env:GGML_OPENVINO_DEVICE = "GPU" +build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024 + +# NPU +$env:GGML_OPENVINO_DEVICE = "NPU" +build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512 +``` + +### llama-server + +```bash +export GGML_OPENVINO_DEVICE=GPU +./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024 + +# Option 1: open http://localhost:8080 in a browser for Llama Chat, the built-in chat app of llama-server. +# Option 2: test the server with curl, from a new terminal. + +# Behind a proxy, keep localhost off the proxy +export NO_PROXY=localhost,127.0.0.1 + +# Health endpoint +curl -f http://localhost:8080/health + +# A simple prompt +curl -X POST "http://localhost:8080/v1/chat/completions" -H "Content-Type: application/json" \ + -d '{"messages":[{"role":"user","content":"Write a poem about OpenVINO"}],"max_tokens":100}' | jq . + +# NPU: several slots need the unified KV cache (-kvu). Without -np, llama-server uses 4 slots with it. +export GGML_OPENVINO_DEVICE=NPU +./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024 -np 2 -kvu +``` + +### NPU context and prefill chunk + +```bash +export GGML_OPENVINO_DEVICE=NPU + +# Set -c. The default is the training context of the model, for example 131072 for Llama 3.2 1B. +# Keep it small on the NPU: -c 512, or -c 256 for larger models. Decode can slow down as the context grows. +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512 + +# Tokens in one NPU prefill step (default 256). +# A larger value can make long prompts faster. It also makes the first load longer. +export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 + +# NPU plugin properties: the compiler in OpenVINO, one compiler thread (lower memory peak), more plugin logs +export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO" +``` + +### Multiple GPUs + +```bash +# List the devices. Each OpenVINO device shows its GGML_OPENVINO_DEVICE value; (selected) marks the active one. +./build/ReleaseOV/bin/llama-cli --list-devices + +# With several GPUs, select one by name. GPU alone is not available then. +export GGML_OPENVINO_DEVICE=GPU.1 +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 + +# Split a model across two GPUs by layer +export GGML_OPENVINO_DEVICE=GPU.0,GPU.1 +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -sm layer +``` + +## Compiled model cache + +The cache keeps compiled models on disk, so later starts of the same model load faster. + +- One directory can hold the cached models of different models and settings. +- Use the same model and the same settings in every run. A changed setting selects another cache entry. The settings: [Compiled model cache](README.md#compiled-model-cache). + +### CPU and GPU + +```bash +# First run: compile the model and write the cache. +# -lv 4 logs "model cache WROTE" (llama-bench: -v). Wait for it before you stop the run: an interrupted export is not cached. +export GGML_OPENVINO_DEVICE=GPU # or CPU +export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4 + +# Later runs (optional): cache-only mode. It requires the cached model and skips the weight upload and the compilation. +export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 +``` + +- Cache-only mode needs mmap loading (the default) and a model that runs fully on OpenVINO. +- MoE models are not written to the cache on CPU, so cache-only mode does not work for them on CPU. +- A cache hit without cache-only mode shortens the load, but it uses about as much memory as a run without the cache. + +### NPU: gemma-4 E2B example + +On the NPU, the cache holds the compiled models without weights, plus one shared weights file. Only the first start compiles the model. + +1. Run once to compile and save the model: + + ```bash + # This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory. + # The log shows the warning "no usable cached blobs ... compiling and exporting". + # Use the model as usual, then exit with /exit. + export GGML_OPENVINO_DEVICE=NPU + export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache + # Host gather is on by default. GGML_OPENVINO_NPU_HOST_GATHER=0 turns it off. + export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy + export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer + ./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096 + ``` + +2. On every later start, load the model from the cache: + + ```bash + # Use the same exports as in step 1 (repeat them in a new shell) and the same command. + # The backend loads the compiled model instead of compiling it. With -lv 4, the log shows "model cache HIT". + # A changed setting or -c value compiles and saves again, or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set. + export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: use the memory-mapped GGUF file as the model buffer; fails without the cache of step 1 + ./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096 + ``` + +- With the default settings, the first prompt writes the prefill model of every KV window up to `-c`. Later runs with the same `-c` find a cached model for any prompt length. + +## Lower memory use + +With the default settings, the GPU and CPU plugins keep their own copy of the weights next to the copy of the backend while a model compiles. On integrated GPUs, both copies are in system RAM. The settings below lower that peak. They do not change the output. + +```bash +# GPU or CPU, large model, Linux: keep at most 10% of the weights in RAM while the model loads and compiles. +# This lowers the peak the most, also when RAM is free. The first token can come later. +export GGML_OPENVINO_COMPILE_MEM_SPILL=0.1 +# Or without a cap: the kernel drops the spilled pages only when RAM runs out, so the peak does not change while RAM is free. +# export GGML_OPENVINO_COMPILE_MEM_SPILL=1 +# Both back the host buffers with files in /var/tmp and write them at each start: the load takes longer, and decoding can be a little slower. +# Needs free disk space of more than the model size, on CPU also the KV cache; with less, the backend warns and uses RAM. +# Another directory, on a local disk (not tmpfs): +export GGML_OPENVINO_COMPILE_MEM_SPILL_DIR=$HOME/ov_spill +mkdir -p $GGML_OPENVINO_COMPILE_MEM_SPILL_DIR + +# GPU: nothing to set. The backend already releases its host copy of the weights after compilation (GGML_OPENVINO_RELEASE_WEIGHTS=1, the default). + +# CPU, MoE model: build fewer weight nodes during compilation. +export GGML_OPENVINO_REDUCE_COMPILE_MEM=1 + +# All at once: GGML_OPENVINO_MEMORY_OPTIMIZE=1 sets GGML_OPENVINO_REDUCE_COMPILE_MEM=1, GGML_OPENVINO_COMPILE_MEM_SPILL=0.1 and, on GPU, GGML_OPENVINO_RELEASE_WEIGHTS=1 (already the default). +# Each one set on its own wins. +export GGML_OPENVINO_MEMORY_OPTIMIZE=1 +``` + +- The same model, started again and again: [cache-only mode](#cpu-and-gpu) skips the weight upload. `GGML_OPENVINO_COMPILE_MEM_SPILL` is optional in the first run. +- NPU: `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` uses the memory-mapped GGUF file as the model buffer. See [NPU: gemma-4 E2B example](#npu-gemma-4-e2b-example). +- `GGML_OPENVINO_COMPILE_MEM_SPILL` is ignored on Windows and in cache-only mode. +- `-lm none` (no mmap) does not lower the memory in use. Cache-only mode needs mmap loading and stops with an error with `-lm none`. +- The variables: [Memory optimization](OpenVINO-ENV-VARS.md#memory-optimization). + +## Large MoE models + +### Qwen3.6-35B-A3B on the NPU + +MoE models with a softmax router and SwiGLU experts run on the NPU through the MoE support of NPUW. This needs OpenVINO 2026.5 or later. A 35B MoE model needs nearly all of a 32 GB system: the backend and NPUW each hold a copy of the weights (about 18 GB each), and the NPU can address 18 GB of the shared memory. Use a small context and these settings: + +```bash +export GGML_OPENVINO_DEVICE=NPU +export GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 +export GGML_OPENVINO_NPU_CONFIG="NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1" +./build/ReleaseOV/bin/llama-cli -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256 +``` + +```bat +REM Windows +set GGML_OPENVINO_DEVICE=NPU +set GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 +set GGML_OPENVINO_NPU_CONFIG=NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1 +build\ReleaseOV\bin\llama-cli.exe -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256 +``` + +- `NPUW_WEIGHTS_BANK_ALLOC=CPU` keeps the NPUW copy of the weights in host memory instead of the NPU-addressable memory, at some cost in speed. +- `NPUW_FUNCALL_ASYNC=NO` and `COMPILATION_NUM_THREADS=1` lower the memory peak. +- The backend sets `NPUW_MOE_POOL_SIZE=0` and `NPUW_MOE_TOKEN_CHUNK_SIZE=16` itself for MoE models (see [NPU plugin properties](OpenVINO-ENV-VARS.md#npu-plugin-properties)). Without them, the load can hang on a 32 GB system. +- The NPU compiler type can stay unset: models with `GATED_DELTA_NET` layers, such as Qwen3.6, then compile with the compiler in OpenVINO. `NPU_COMPILER_TYPE=PREFER_PLUGIN` gives the same result. +- Linux: the NPU reports almost all of the system memory, so `--fit` keeps every weight in the backend, and a 32 GB system swaps heavily. Pass `--fit-target 16384`: `--fit` then leaves part of the expert weights in the memory-mapped model file. Windows does the same without it, because the NPU reports 16 GB there. The graph still runs on the NPU alone. +- `llama-perplexity`: see [Embeddings and perplexity](#embeddings-and-perplexity). + +### Muse-Glimmer-30B with a DFlash draft on the GPU + +This needs a 64 GB system. + +```bash +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_COMPILE_MEM_SPILL=1 +export GGML_OPENVINO_ROPE_SINCOS=device_f32 # long prompts +./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md .gguf \ + --spec-type draft-dflash --spec-draft-n-max 4 +``` + +## Speculative decoding + +MTP, for Qwen3.5 and Qwen3.6 models with MTP weights in the GGUF file. It needs the GPU (dynamic stateless execution). Internals and limitations: [Qwen MTP](README.md#qwen-mtp). + +```bash +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all # recommended for Qwen3.6-35B-A3B Q4_K_M +# Keep GGML_OPENVINO_KV_SLICE at its default (1) +./build/ReleaseOV/bin/llama-server -m Qwen3.6-35B-A3B-Q4_K_M.gguf --spec-type draft-mtp --spec-draft-n-max 2 + +# Several slots: the unified KV cache is the recommended layout on the GPU +./build/ReleaseOV/bin/llama-server -m Qwen3.6-35B-A3B-Q4_K_M.gguf --spec-type draft-mtp --spec-draft-n-max 2 -np 4 --kv-unified +``` + +DFlash: see [Muse-Glimmer-30B with a DFlash draft on the GPU](#muse-glimmer-30b-with-a-dflash-draft-on-the-gpu). + +## Image input + +Image input is experimental. It runs on CPU and GPU. Internals and limitations: [Multimodal](README.md#multimodal). + +Gemma4 E2B image input on GPU or CPU: + +```bash +# Gemma4 E2B image input on GPU (or CPU). The chat template of the model needs --jinja. +# The projector (mmproj) file is in the same Hugging Face repository as the model. +# The model writes its reasoning before the answer. +export GGML_OPENVINO_DEVICE=GPU +./build/ReleaseOV/bin/llama-mtmd-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf \ + --mmproj mmproj-google_gemma-4-E2B-it-f16.gguf --jinja -c 4096 \ + --image cat.jpg -p "What animal is in this image?" +``` + +Qwen3-VL-4B image input on GPU: + +```bash +# Qwen3-VL-4B image input on GPU. Model and projector: https://huggingface.co/unsloth/Qwen3-VL-4B-Instruct-GGUF +# --image-max-tokens 256 keeps the image prefill within the memory of a 16 GB system. +export GGML_OPENVINO_DEVICE=GPU +./build/ReleaseOV/bin/llama-mtmd-cli -m Qwen3-VL-4B-Instruct-Q4_K_M.gguf \ + --mmproj mmproj-F16.gguf --jinja -c 4096 --image-max-tokens 256 \ + --image tools/mtmd/test-1.jpeg -p "Describe this image in one sentence." +``` + +## Embeddings and perplexity + +```bash +# Embeddings: CPU or GPU (embedding models do not work on the NPU) +export GGML_OPENVINO_DEVICE=GPU +./build/ReleaseOV/bin/llama-embedding -m embedding-model-Q8_0.gguf -p "Hello world" + +# Perplexity +./build/ReleaseOV/bin/llama-perplexity -m model.gguf -f wiki.test.raw -c 512 + +# MoE models on the GPU: set -b to the -c value, so that each batch holds one sequence +./build/ReleaseOV/bin/llama-perplexity -m model.gguf -f wiki.test.raw -c 512 -b 512 + +# NPU: -b at most -c (one sequence per batch), -ub equal to the prefill chunk size (default 256) +export GGML_OPENVINO_DEVICE=NPU +./build/ReleaseOV/bin/llama-perplexity -m model.gguf -f wiki.test.raw -c 1024 -b 1024 -ub 256 + +# NPU, MoE models such as Qwen3.6-35B-A3B: -c at most twice GGML_OPENVINO_PREFILL_CHUNK_SIZE. +# The output rows of the last layer must not exceed the chunk size. +export GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 +./build/ReleaseOV/bin/llama-perplexity -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -f wiki.test.raw -c 256 +``` + +## Profiling and debug dumps + +The variables are in [Debug output](OpenVINO-ENV-VARS.md#debug-output). + +```bash +# Execution timing of each graph: 1. 2 or higher also turns on OpenVINO and OpenCL profiling. +# llama-simple prints the timing lines. llama-cli needs -lv 4, llama-bench needs -v. +export GGML_OPENVINO_DEVICE=GPU +export GGML_OPENVINO_PROFILING=1 +./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is " +``` + +```bash +# Show the variables in effect (log verbosity 4) +./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4 2>&1 | grep "settings from the environment" +``` + +```bash +# CPU in FP16, as the GPU and the NPU compute. This helps to debug the accuracy of a quantized model. +GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16" \ + ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 +``` + +```bash +# Find out whether a default optimization causes a wrong result: turn it off and compare the output +GGML_OPENVINO_DEVICE=NPU GGML_OPENVINO_NPU_FAST_MASK=0 \ + ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is" +``` + +```bash +# Dump the GGML graph and the OpenVINO IR of a run +GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \ + ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 + +# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout. +GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt + +# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher). +GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 + +# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call +GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op + +# Graph key and tensor shapes when an inference throws +GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG + +# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD). +export GGML_OPENVINO_DEVICE=NPU +export GGML_OPENVINO_NPUW_DUMP_SUBS=YES +export GGML_OPENVINO_NPUW_DUMP_SUBS_DIR=/tmp/npuw_dump # optional +./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 +``` + +List the properties of the installed NPU plugin (C++): + +```cpp +// List the properties of the installed NPU plugin with their current values +ov::Core core; +for (const auto & name : core.get_property("NPU", ov::supported_properties)) { + std::cout << name << " = " << core.get_property("NPU", name).as() << "\n"; +} +``` diff --git a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md index 22ed8bbba6af..ee983ad1bca9 100644 --- a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md +++ b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md @@ -13,20 +13,20 @@ Contents: ## Sampler behavior -- Qwen3.5/Qwen3.6 MTP uses a pure top-k backend sampler. +- The MTP draft (`--spec-type draft-mtp`) samples with a backend chain of one top-k sampler (k = 10). Draft backend sampling is on by default. If the backend rejects the chain, llama.cpp uses the CPU sampler for that sequence. - Dynamic stateless execution keeps the sampling branches for every configured slot and output row, including inactive branches. -- One packed `sampling_rows` input selects the logits rows at runtime. +- In dynamic execution, one packed `sampling_rows` input selects the logits rows at runtime. - Graph node names and candidate-output ports stay fixed. A change of the active subset of four slots therefore reuses the same compiled draft model, instead of creating up to 15 variants. - Active candidate IDs and scores are written to the normal GGML outputs. - Inactive branches read row 0 (the padding row when there are no logits) and write to private scratch tensors (device USM on GPU). They do not change sampler state or acceptance, and do not touch inactive GGML buffers. - The backend does not change the original cgraph or execute inactive stateful sampler chains. -- Only the small sampling branches stay at configured capacity. The expensive draft layer, the MTP layer and the output projection, processes the N active rows. +- Only the small sampling branches stay at configured capacity. The MTP layer and the output projection process only the N active rows. - The top-k computations stay separate per branch, not yet one batched TopK. This trades some extra sampling work for a stable graph interface. -- Other sampler chains keep their existing branch-selection behavior. +- Only a pure top-k chain keeps its inactive branches: VIEW, two Reshapes, TopK and GET_ROWS, with no other reader. Other chains drop the branches that have no COMPUTE flag. Static (NPU) and stateful execution drop them for every chain. ## Graph layout -The captured UD draft graph contains 107 nodes regardless of which of four slots are active. +Capture conditions: cache-only mode, four slots, context 8192 and `--spec-draft-n-max 2`. The captured draft graph of the UD (Unsloth Dynamic) Qwen3.6-35B-A3B model contains 107 nodes regardless of which of four slots are active. - It is the single MTP attention/MoE layer, not the recurrent trunk. - Two speculative tokens require two consecutive draft calls, batched over active sequences. @@ -51,26 +51,19 @@ MTP token IDs + input hidden state ## Active slots -| Active slots | Sampling COMPUTE flags, slots 0-3 | Raw/current nodes | Old filtered nodes | Packed sampling_rows | -|---|---|---:|---:|---| -| 3 | `[0,0,0,1]` | 107 | 92 | `[0,0,0,0]` | -| 0,2 | `[1,0,1,0]` | 107 | 97 | `[0,0,1,0]` | -| All four | `[1,1,1,1]` | 107 | 107 | `[0,1,2,3]` | +| Active slots | Sampling COMPUTE flags, slots 0-3 | Nodes | Packed sampling_rows | +|---|---|---:|---| +| 3 | `[0,0,0,1]` | 107 | `[0,0,0,0]` | +| 0,2 | `[1,0,1,0]` | 107 | `[0,0,1,0]` | +| All four | `[1,1,1,1]` | 107 | `[0,1,2,3]` | -- Old counts apply the old COMPUTE filter to the captures. -- Unselected nodes remain in the raw cgraph. - -
-Why the graph keeps inactive branches - -The old COMPUTE filter removed the unselected nodes. That changed the translated topology, the slot-specific row Parameter names and the output ports; even equal-sized subsets such as `{0,1}` and `{0,2}` differed. This could trigger up to 15 draft variants, with compilation/import on first use or a missing-cache error in cache-only mode. - -
+- Unselected branches stay in the graph, so every active subset uses one compiled draft model. +- Packed entries follow the sorted branch names. This matches the slot order for slots 0-9. ## Runtime row selection - All pure top-k branches remain. Their names include stable graph ordinals even when inactive. -- One int64 `sampling_rows` Parameter supplies row indices at runtime. +- In dynamic execution, one int64 `sampling_rows` Parameter supplies the row indices. Static execution uses one `sampling_row_` input per branch. - The vector is not an active mask. Host-side COMPUTE flags select normal versus scratch output destinations. - PAD provides a valid row when there are no logits. @@ -87,6 +80,7 @@ slot 3 -> row 0 -> private scratch, ignored ## Compiled models and the cache - One draft model exists per compatible graph configuration, not one compiled blob for the whole server. One compatible draft graph is shared across active subsets. +- The blob key and the in-process key leave out the COMPUTE flags, so all active subsets use one compiled draft model. - The trunk and other graph stages still have their own entries. Genuinely different graph stages and configurations remain separate. - Different sampler configurations, recurrent capacities, rollback modes or incompatible KV layouts can require additional models. - Cache-only mode still requires initial preparation: prepare compatible blobs once, then use cache-only mode. A change of the active subset needs no extra preparation. @@ -97,4 +91,4 @@ slot 3 -> row 0 -> private scratch, ignored - Dump shapes use GGML order `[width, rows, dim2, dim3]`. OpenVINO reverses it. - `view_offs` is in bytes: one logits row occupies `248320 * 4 = 993280` bytes. - Buffer labels describe GGML storage, not the device that executes imported GPU operations. -- Capture conditions: cache-only mode, four slots, context 8192 and the default two-token MTP settings. +- `GGML_OPENVINO_DUMP_CGRAPH=1` dumps the raw graph before the COMPUTE filter, with COMPUTE/OUTPUT flags and byte offsets. It overwrites `cgraph_ov.txt` on each call. Enable dumps only for diagnosis. diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 010ee88a334c..1294f0f9b87f 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -2,20 +2,19 @@ The default Qwen3.5/Qwen3.6 MTP path uses pending-token replay, dynamic stateless execution and stable pure-top-k sampling. When MTP discards a suffix, the next batch replays the retained tokens before it processes new tokens. -- Applies to `qwen35` and `qwen35moe`, with one or multiple slots. -- Reference model: the UD Qwen3.6-35B-A3B MTP GGUF model file. +- The backend finds replay groups by graph structure. It is validated with `qwen35` and `qwen35moe`, with one or more slots. +- Reference model: the UD (Unsloth Dynamic) Qwen3.6-35B-A3B MTP GGUF model file. - Setup: `GGML_OPENVINO_DEVICE=GPU` and the documented requantization policy ([Qwen MTP](README.md#qwen-mtp)). - The matching GPU plugin structurally fuses complete replay groups into its internal convolution and Gated Delta Net ops. +- Attention KV binding (`GGML_OPENVINO_ENABLE_KV_4D`, `GGML_OPENVINO_KV_SLICE`, `GGML_OPENVINO_GPU_KV_ROUND_UP`): [KV cache binding](README.md#kv-cache-binding). +- Backend files: [Source layout](README.md#source-layout). MTP sampling: [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md). Contents: - [Buffer ownership and operation boundaries](#buffer-ownership-and-operation-boundaries) - [Replay graph contract](#replay-graph-contract) - [Convolution cache stores](#convolution-cache-stores) -- [Attention KV layout](#attention-kv-layout) -- [Stable MTP sampling](#stable-mtp-sampling) -- [Validation](#validation) -- [Debugging and source map](#debugging-and-source-map) +- [Debugging and profiling](#debugging-and-profiling) ## Buffer ownership and operation boundaries @@ -51,17 +50,17 @@ Both kernels write their cache inputs directly. Graph selection: -- Qwen selects the recurrent graph when the target context is created. +- The llama context selects the replay graph when it is created. - `n_rs_seq=0` selects the ordinary graph. - With `--spec-type draft-mtp` and a positive draft limit, `n_rs_seq` is the draft limit, and `rs_replay` selects the replay graph even for a fresh prefill. -- Both forms use `GGML_OP_GATED_DELTA_NET`. The replay form sets `op_params[1]` to the pending-token capacity and adds inputs for pending K, V, gate/beta and the per-sequence replay count. +- Both forms use `GGML_OP_GATED_DELTA_NET`. The replay form sets `op_params[1]` to the pending-token capacity and adds inputs for pending K, V, gate/beta and the per-sequence replay count. `op_params[2]` holds the keep flag. - A fresh prompt supplies a replay count of zero. -- Prefill microbatches longer than `n_rs_seq + 1` tokens per sequence commit their final state. +- A ubatch commits its final state when it has one token, or more than `n_rs_seq + 1` tokens, per sequence. Other ubatches stay pending. - The unfused OpenVINO graph processes current tokens in a `Loop` and uses a bounded unrolled recurrence for the retained prefix. Standard-op graph and `Assign` sinks: -- The backend emits a standard-op graph for each complete dynamic stateless replay group. +- The backend emits the replay graph only on GPU, for a dynamic, stateless graph that is not split. `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` turns it off. In all other cases, another GGML backend runs the replay ops. - The computation feeds later layers, and the updated banks feed standard `Assign` sinks. - Fusion requires each bank to be a direct FP32 `Parameter` of shape `[1, 1, slots, features]`, backed by caller-owned writable GPU USM. - The backend opts each bank into in-place fusion by giving its sink the variable ID `__ggml_replay_cache_`. @@ -76,7 +75,7 @@ GPU fusion: Writeback without fusion: - When a sink remains, including on a GPU plugin without this pass, llama.cpp uses `query_state()` to find it and copies its state to the original GGML bank after inference. -- Mixed-precision execution of that graph can round bank values. +- The backend keeps the replay subgraph, its `Loop` body and its bank inputs in FP32 under the GPU f16 inference hint. Source of the replay pattern: @@ -96,71 +95,9 @@ When upstream modeling changes the GGML graph: - `ScatterNDUpdate` produces the updated bank for the `Assign` sink. - Row maps, replay counts and reset rows are runtime inputs. -## Attention KV layout - -| Variable | Default | Scope | Description | -|---|---|---|---| -| `GGML_OPENVINO_ENABLE_KV_4D` | On with OpenVINO 2026.5 or later | GPU | Eligible native stateless in-place attention updates | -| `GGML_OPENVINO_KV_SLICE` | `1` | Dynamic CPU and GPU; static NPU | Binding switch on dynamic CPU and GPU; base of the compiled KV windows on static NPU | -| `GGML_OPENVINO_GPU_KV_ROUND_UP` | `1` | Dynamic stateless GPU | Attended-width rounding | - -`GGML_OPENVINO_ENABLE_KV_4D`: - -- Uses the upstream stateless in-place attention KV update pattern where eligible. It binds full-capacity cache tensors and lets the GPU fusion expose the live prefix to attention. -- `0` turns it off. `1` turns it on with older OpenVINO versions. -- The current eligibility covers one physical stream, including unified KV. -- Explicit split multi-slot KV keeps the full-cache path and can be much slower, even with only one active slot. -- It does not change recurrent cache handling. -- Use `--kv-unified` for multi-slot OV GPU serving. Unified KV enables this in-place attention update. - -`GGML_OPENVINO_KV_SLICE` on dynamic CPU and GPU: - -- Eligible root: a contiguous ordinary attention K/V root with one allocated stream, one active sequence at offset zero, and no sliding-window attention. For it, the backend binds a view of the allocation sized to the attended prefix. -- Recurrent convolution/GDN caches and their rollback snapshots always keep their full stored row bank. Sliding-window attention and other layouts use the full binding. -- The 4-D in-place attention path binds the full allocation first and exposes the attended prefix inside the graph. -- Dynamic compiled blobs can accept either eligible binding, so the value can differ between cache population and cache-only runs. - -`GGML_OPENVINO_KV_SLICE` on static NPU: - -- Selects the base of the compiled KV windows. The default base is 1024; an explicit multiple of 256 changes it. -- The window is the smallest `base * 2^k` that covers the attended length, capped by the context. - -`GGML_OPENVINO_GPU_KV_ROUND_UP` on dynamic stateless GPU: - -- Controls the attended width separately from prefix binding. -- `0`: the decoder uses the GGML mask width. Ordinary GGML attention KV already pads it in steps of 256 rows. -- `1` (default): power-of-two windows when the graph input has more than 16 tokens, and coarser aligned steps for smaller batches. The step starts at 256 rows and doubles whenever the width reaches eight times the current step. -- Example: at 33,024 GGML rows, the added rounding can expand attention to 40,960 rows for decode or 65,536 for a larger prefill input, subject to the context cap. -- Added mask columns contain negative infinity. - -## Stable MTP sampling - -The fixed sampling interface, the handling of inactive slots and the reuse of compiled draft models are in [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md). - -## Validation - -- Validation checks the convolution bank that the caller mutated against the expected reset, reorder and history writes. -- The four-layer Qwen3.6 model exercises replay at one and four active sequences. - -## Debugging and source map - -Backend files, relative to `ggml/src/ggml-openvino/`, and OpenVINO GPU plugin parts: - -| File | Content | -|---|---| -| `ggml-decoder.cpp` | Dynamic dimensions, control inputs, output names and the `cgraph_ov.txt` dump | -| `utils.cpp` | Compute-branch filtering, compiled reuse and input/output binding | -| `openvino/recurrent_replay_fusion.cpp` | GGML group recognition and standard-op replay translation | -| `openvino/translate_session.cpp` | Runtime sampling aliases and model construction | -| OV `recurrent_replay_fusion.cpp` and `recurrent_cache_replay` | Structural matching, writable-input validation, source staging and GPU computation | - -`GGML_OPENVINO_DUMP_CGRAPH=1`: - -- Dumps the raw graph before filtering, with COMPUTE/OUTPUT flags and byte offsets. -- Overwrites `cgraph_ov.txt` on each call. -- Enable dumps only for diagnosis. Use the captured examples for a static view. - -Profiling: +## Debugging and profiling +- `GGML_OPENVINO_DUMP_CGRAPH=1` also logs the number of convolution and GDN replay groups. For annotated dumps, see [Reading graph dumps](MTP-SAMPLING-GRAPH.md#reading-graph-dumps). +- `test-backend-ops` does not cover the OpenVINO replay path. Its replay cases have no recurrent cache banks, so the backend rejects them. Check replay with a Qwen3.5 or Qwen3.6 MTP model at one and four active sequences. - GPU profiles and OpenCL copy traces add overhead. - The lack of an explicit copy call does not prove zero traffic inside a kernel. diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index 67c695575f9e..243a40c5cf2a 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -1,6 +1,6 @@ # OpenVINO backend environment variables for development -The variables for users, and the rules for values, are in [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md#runtime-configuration). This file lists the other `GGML_OPENVINO_*` variables. They are for debugging, comparisons and experiments, and they can change or be removed. +The variables for users, and the rules for values, are in [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md#configuration). This file lists the other `GGML_OPENVINO_*` variables. They are for debugging, comparisons and experiments, and they can change or be removed. Commands that use them are in [COOKBOOK.md](COOKBOOK.md). Contents: @@ -14,6 +14,8 @@ Contents: ## Debug output +Examples: [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps). + | Variable | Device | Type | Default | Description | |---|---|---|---|---| | `GGML_OPENVINO_DUMP_CGRAPH` | all | Boolean | `0` | Dump the GGML compute graph to `cgraph_ov.txt`. | @@ -34,39 +36,15 @@ Contents: | `GGML_OPENVINO_NPUW_DUMP_SUBS_ON_FAIL` | NPU | String | `not set` | Passed to OpenVINO unchanged as `NPUW_DUMP_SUBS_ON_FAIL`. | | `GGML_OPENVINO_NPUW_DUMP_IO` | NPU | String | `not set` | Passed to OpenVINO unchanged as `NPUW_DUMP_IO`. | -```bash -# Dump the GGML graph and the OpenVINO IR of a run -GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \ - ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 - -# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout. -GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt - -# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher). -GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 - -# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call -GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op - -# Graph key and tensor shapes when an inference throws -GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG - -# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD). -export GGML_OPENVINO_DEVICE=NPU -export GGML_OPENVINO_NPUW_DUMP_SUBS=YES -export GGML_OPENVINO_NPUW_DUMP_SUBS_DIR=/tmp/npuw_dump # optional -./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -``` - ## Switches for default optimizations Each variable turns off an optimization that is on by default, or sets its strength. Use them to find the cause of a wrong result or of a speed change. | Variable | Device | Type | Default | Description | |---|---|---|---|---| -| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. Dynamic CPU and GPU use a valid positive value to bind eligible ordinary attention KV as a view of the attended prefix. The 4-D GPU binding takes precedence. Dynamic compiled blobs support both bindings. Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. | -| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Controls the extra attended-width rounding on dynamic stateless GPU. With `1`, a graph input over 16 tokens uses the next power-of-two window and smaller batches use an aligned step that grows with the attended length. With `0`, the decoder uses the original GGML mask width. This setting is separate from prefix binding. | -| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | With `GGML_OPENVINO_KV_SLICE` on, decode attends the smallest `N * 2^k` rows (`N` from `GGML_OPENVINO_KV_SLICE`) that cover the next position, with one decode graph for each window, and the prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. Use the same value in the run that writes the cache and in the runs that read it. | +| `GGML_OPENVINO_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. See [KV cache binding](README.md#kv-cache-binding). | +| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Round the attended width up on dynamic stateless GPU. `0` uses the GGML mask width. See [KV cache binding](README.md#kv-cache-binding). | +| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | One decode graph for each KV window (base from `GGML_OPENVINO_KV_SLICE`), built or read from the cache on the first call. `0`: one decode graph for the whole context. Use the same value when you write and read the cache. See [KV cache binding](README.md#kv-cache-binding). | | `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. | | `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. | | `GGML_OPENVINO_GDN_Q_SCALE` | NPU | Float | `64` | Factor of the GDN q pre-scaling, which keeps the GDN output above the FP16 flush-to-zero floor of the NPU. `0` or a negative value turns it off. Values below `64` are raised to `64`. | @@ -76,13 +54,8 @@ Each variable turns off an optimization that is on by default, or sets its stren | `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS` | GPU | Boolean | `0` | By default an output tensor in a GPU buffer is bound directly to the infer request when its shape and type match. `1` turns this off. | | `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | `1` disables the OpenVINO backend's recurrent replay translation, so replay ops require another eligible GGML backend. For an unfused OpenVINO replay graph, leave this at `0` and use a GPU plugin without the replay fusion pass. | | `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN` | GPU | Boolean | `0` | By default the operands of an element-wise op get the same rank, which works around a GPU plugin defect when the op is fused into RMS norm (gemma-4 in stateful execution gave wrong output). `1` turns the workaround off. | -| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | auto | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Unset: on with OpenVINO 2026.5 or later, off with older versions (much slower there). `0` forces it off, a positive value forces it on. With OpenVINO 2026.5, `GGML_OPENVINO_ENABLE_KV_4D=0` can stop a process that runs two models on the GPU at the same time (`CL_OUT_OF_RESOURCES`). | - -```bash -# Find out whether an optimization causes a wrong result: turn it off and compare the output -GGML_OPENVINO_DEVICE=NPU GGML_OPENVINO_NPU_FAST_MASK=0 \ - ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is" -``` +| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | auto | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]` for in-place updates. Unset: on with OpenVINO 2026.5 or later. `0` forces it off, a positive value forces it on. Not used with `-fa off`, for soft-capped attention (gemma-2), or in static, stateful or split graphs. See [KV cache binding](README.md#kv-cache-binding). | +| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | `1` | Release the host weight buffers after compilation. The compiled model keeps its own copy. The backend writes them again from the model file before a new compile or a host read. `0` keeps them. Follows `GGML_OPENVINO_MEMORY_OPTIMIZE` when that is set. Off with `-lm none` and in cache-only mode. Linux only. | ## Experimental options @@ -97,69 +70,20 @@ Most of these options are off by default. They are not validated for general use | `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. | | `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. This includes the NPU translation of MoE blocks, which computes every expert on the CPU or the GPU and is slow. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | | `GGML_OPENVINO_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs that the scheduler splits between OpenVINO and another backend, and translate them as partial graphs, without the compiled model cache. By default every graph is treated as a complete model graph. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | -| `GGML_OPENVINO_ROPE_F32_ANGLE` | all | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model on the GPU. On CPU, `test-backend-ops -o ROPE` fails with it. | -| `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. | +| `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log1p(exp(-abs(x)))`. | | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. | -| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`. | -| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | -| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE`, `1` if that is unset | Release the host weight buffers when the compiled model holds its own copy. Before a new graph is compiled, or when the host reads a weight, they are written again from the model file. Weights loaded without mmap (`-lm none`) stay in host memory. Linux only. | -| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). It is not part of the key of the compiled model cache and is ignored in cache-only mode. | -| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | - -```bash -# NPU cache: weightless blobs plus one shared weights file. Keep all other NPU settings the same in both runs. -export GGML_OPENVINO_DEVICE=NPU -export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache -./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: warns "no usable cached blobs", exports - -export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 -./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # later runs: log shows "model cache HIT" -``` ## Memory optimization -With the default settings, the GPU and CPU plugins keep their own copy of the weights next to the backend's copy while a model compiles. On integrated GPUs both copies are in system RAM. The settings below lower that peak. They do not change the output. - -```bash -# GPU or CPU, large model: back the weight buffer with a file, so the kernel can drop its pages. -# Use a directory on a local disk (not tmpfs) with free space of about the model size. Can lower prompt speed. -export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill -mkdir -p $GGML_OPENVINO_SPILL_DIR -``` - -```bash -# GPU or CPU, the same model started again and again: compile once, then load the compiled model only. -export GGML_OPENVINO_DEVICE=GPU # or CPU -export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache -GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill ./build/ReleaseOV/bin/llama-cli -m model.gguf # first run writes the cache -export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 -./build/ReleaseOV/bin/llama-cli -m model.gguf # later runs skip the weight upload -``` - -```bash -# GPU: keep the host copy of the weights after compilation (it is released by default). -export GGML_OPENVINO_DEVICE=GPU -export GGML_OPENVINO_RELEASE_WEIGHTS=0 -``` - -```bash -# CPU, MoE model: build fewer weight nodes during compilation. -export GGML_OPENVINO_REDUCE_COMPILE_MEM=1 -``` - -```bash -# NPU: weightless cache, then use the memory-mapped GGUF as the model buffer. -export GGML_OPENVINO_DEVICE=NPU -export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache -./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # first run writes the cache -export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 -./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # later runs -``` +These variables lower the host memory peak. They do not change the output. Commands: [Lower memory use](COOKBOOK.md#lower-memory-use). `GGML_OPENVINO_RELEASE_WEIGHTS` is in [Switches for default optimizations](#switches-for-default-optimizations). -- A cache hit without `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1` shortens the load, but it uses about as much memory as a run without the cache. -- MoE models are not written to the cache on CPU, so cache-only mode does not work for them on CPU. -- `GGML_OPENVINO_SPILL_DIR` is ignored on Windows and in cache-only mode. -- `-lm none` (no mmap) does not lower the memory in use, and cache-only mode stops with an error with it: cache-only mode needs mmap loading. +| Variable | Device | Type | Default | Description | +|---|---|---|---|---| +| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | unset | When set, the default of `GGML_OPENVINO_REDUCE_COMPILE_MEM`, of `GGML_OPENVINO_COMPILE_MEM_SPILL` (`1` sets `0.1`) and, on GPU, of `GGML_OPENVINO_RELEASE_WEIGHTS`. `0` also keeps the host weights on GPU. | +| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | +| `GGML_OPENVINO_COMPILE_MEM_SPILL` | CPU, GPU | Float | `0.1` with `GGML_OPENVINO_MEMORY_OPTIMIZE=1`, else `0` | Back the host buffers of the backend (weights, KV cache, compute) with files in `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR`, so the kernel can drop their pages. `0`: off. `1`: on, but the kernel drops the pages only when RAM runs out, so the memory peak does not change while RAM is free. A fraction in between: on, and while the model loads and compiles, keep at most this fraction of the spilled weights in RAM, also when RAM is free (`0.1` keeps 10%, Linux 5.4 or later). A fraction lowers the peak the most; the model file's pages are dropped too, and the first token can come later, while the weights are written to disk. Each start writes the buffers to disk: the load takes longer, and decoding can be a little slower. The disk space is reserved when the files are created (not for rewrites on btrfs or ZFS): more than the model size, on CPU also the KV cache. With too little space, the backend warns and uses RAM. NPU: off unless set, and only with `GGML_OPENVINO_NPU_L0_HOST_TENSORS=0`. Not part of the cache key. Ignored on Windows and in cache-only mode. | +| `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR` | CPU, GPU | String | `/var/tmp` | Directory for the `GGML_OPENVINO_COMPILE_MEM_SPILL` files. Use real storage, not tmpfs (`/tmp` on many systems): on tmpfs, the backend warns and uses RAM. | +| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | ## NPU plugin properties @@ -203,78 +127,25 @@ Other properties for `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them, | `NPUW_UNFOLD_IREQS` | Boolean | `not set`; `NO` on graphs with a MoE block; `YES` on the decode graph with `GGML_OPENVINO_NPU_DECODE_UNFOLD=1` | `NO` | One infer request for each part, also for repeating blocks. | | `LOG_LEVEL` | String | `not set` | `LOG_ERROR` | Log level of the NPU plugin, for example `LOG_INFO`. | -Set properties with `GGML_OPENVINO_NPU_CONFIG`: - -```bash -export GGML_OPENVINO_DEVICE=NPU -export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO" -``` - -
-C++ sample: list the properties of the installed NPU plugin - -```cpp -// List the properties of the installed NPU plugin with their current values -ov::Core core; -for (const auto & name : core.get_property("NPU", ov::supported_properties)) { - std::cout << name << " = " << core.get_property("NPU", name).as() << "\n"; -} -``` - -
- - All NPU properties: [OpenVINO NPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/npu-device.html). -- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source. +- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source. To list the properties of the installed plugin, see the C++ sample in [Profiling and debug dumps](COOKBOOK.md#profiling-and-debug-dumps). - Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them. - -### Example: gemma-4 E2B with the model cache - -`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` saves the model compiled for the NPU, so only the first start compiles it. - -1. Run once to compile and save the model: - - ```bash - # This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory - # (with -lv 4 the log shows "no usable cached blobs ... compiling and exporting"). - # Use the model as usual, then exit with /exit. - export GGML_OPENVINO_DEVICE=NPU - export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache - export GGML_OPENVINO_NPU_HOST_GATHER=1 # optional: faster generation, less memory and disk; the output can differ slightly - export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy; wrong output on the Panther Lake NPU - export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer - ./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096 - ``` - -2. On every later start, load the model from the cache: - - ```bash - # Use the same exports as in step 1 (repeat them in a new shell) and the same command. - # The backend loads the compiled model instead of compiling it, so the model starts much faster - # (with -lv 4 the log shows "model cache HIT"). A changed setting or -c value compiles and saves again, - # or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set. - export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: slightly shorter start; fails without the cache of step 1 - ./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096 - ``` +- Compiled model cache on the NPU: see [NPU: gemma-4 E2B example](COOKBOOK.md#npu-gemma-4-e2b-example). ## GPU and CPU plugin properties GPU and CPU: the backend sets no property, except: - - `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set. - - With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`: no `CACHE_DIR`, and `CACHE_MODE=OPTIMIZE_SPEED`. This overrides the same properties in `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG`. - - `ENABLE_PROFILING` with `GGML_OPENVINO_PROFILING=2` or higher. - - `EXECUTION_MODE_HINT` on the small graphs of op tests. -```bash -# CPU in FP16, to compare with the GPU and the NPU, which compute in FP16 -GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16" \ - ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -``` +- `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set. +- With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`: no `CACHE_DIR`, and `CACHE_MODE=OPTIMIZE_SPEED`. This overrides the same properties in `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG`. +- `ENABLE_PROFILING` with `GGML_OPENVINO_PROFILING=2` or higher. +- `EXECUTION_MODE_HINT` on the small graphs of op tests. All properties: [OpenVINO GPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html), [OpenVINO CPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.html). ## Older variable names -Each of these variables sets one NPU property. They still work. `GGML_OPENVINO_NPU_CONFIG` sets the same properties and takes precedence when both are set. +Each of these variables sets one NPU property. They still work. `GGML_OPENVINO_NPU_CONFIG` sets the same properties and takes precedence when both are set. For example, `GGML_OPENVINO_NPU_CONFIG="NPUW_UNFOLD_IREQS=YES"` and `GGML_OPENVINO_NPUW_UNFOLD_IREQS=YES` do the same. Use the first form. | Variable | Device | Type | Default | Description | |---|---|---|---|---| @@ -283,9 +154,3 @@ Each of these variables sets one NPU property. They still work. `GGML_OPENVINO_N | `GGML_OPENVINO_NPUW_FUNCALL_FOR_ALL` | NPU | String | `not set` | Sets `NPUW_FUNCALL_FOR_ALL`. | | `GGML_OPENVINO_NPUW_UNFOLD_IREQS` | NPU | String | `not set` | Sets `NPUW_UNFOLD_IREQS`. | | `GGML_OPENVINO_COMPILATION_NUM_THREADS` | NPU | String | `not set` | Sets `COMPILATION_NUM_THREADS`. | - -```bash -# These two lines do the same. Use the first form. -export GGML_OPENVINO_NPU_CONFIG="NPUW_UNFOLD_IREQS=YES" -export GGML_OPENVINO_NPUW_UNFOLD_IREQS=YES -``` diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md index f08f6a999711..ee169e909cf9 100644 --- a/ggml/src/ggml-openvino/dev_doc/README.md +++ b/ggml/src/ggml-openvino/dev_doc/README.md @@ -1,91 +1,70 @@ # OpenVINO backend developer documentation -These pages cover the internals of the OpenVINO backend on CPU, GPU and NPU, and the options for development and debugging. Build steps, device selection, validated models and the user-facing environment variables are in [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md). +These pages cover the internals of the OpenVINO backend on CPU, GPU and NPU, and the options for development and debugging. + +- Build steps, device selection, validated models and the user environment variables: [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md). +- Commands for each task: [COOKBOOK.md](COOKBOOK.md). | Document | Content | |---|---| -| This page | Qwen MTP, compiled model cache, KV-only prefill, NPU host gather, multimodal input | +| This page | How the backend works, source layout, compiled model cache, KV cache binding, KV-only prefill, NPU host gather, Qwen MTP, multimodal input | +| [COOKBOOK.md](COOKBOOK.md) | Recipes: build scripts, Docker, devices, cache, memory, large MoE models, speculative decoding, image input, perplexity, profiling and debug dumps | | [OpenVINO-ENV-VARS.md](OpenVINO-ENV-VARS.md) | Debug output, switches for default optimizations, experimental options, memory optimization, plugin properties, older variable names | -| [OPENVINO-RECURRENT-CACHE.md](OPENVINO-RECURRENT-CACHE.md) | Qwen recurrent cache on GPU: buffer ownership, replay graph contract, attention KV layout, source map | +| [OPENVINO-RECURRENT-CACHE.md](OPENVINO-RECURRENT-CACHE.md) | Qwen recurrent cache on GPU: buffer ownership, replay graph contract, convolution cache stores | | [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md) | Multi-slot MTP draft graph: sampler behavior, graph layout, active slots, runtime row selection, compiled-model reuse | Contents of this page: -- [Qwen MTP](#qwen-mtp) +- [How the backend works](#how-the-backend-works) +- [Source layout](#source-layout) - [Compiled model cache](#compiled-model-cache) +- [KV cache binding](#kv-cache-binding) - [KV-only prefill](#kv-only-prefill) - [NPU host gather](#npu-host-gather) +- [Qwen MTP](#qwen-mtp) - [Multimodal](#multimodal) -## Qwen MTP - -The OpenVINO backend translates Qwen recurrent replay for complete dynamic stateless GPU graphs and supports stable MTP sampling. +## How the backend works -Requirements: - -- Dynamic stateless GPU execution. OpenVINO replay requires it. -- A GGUF model file that contains MTP weights. +When a `ggml_cgraph` is dispatched to the OpenVINO backend, it: -Options: +- Walks the GGML graph and identifies inputs, outputs, weights, and KV cache tensors. +- Translates the GGML operations into an `ov::Model` using OpenVINO's frontend API. +- Compiles and caches the model for the target device. +- Binds GGML tensor memory to OpenVINO inference tensors and runs inference. -- MTP: `--spec-type draft-mtp --spec-draft-n-max 2`. -- Parallel execution: `-np` and `--kv-unified`. Unified KV cache is the recommended layout for multi-slot GPU execution. See [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout). +## Source layout -Recommended setup for Qwen3.6-35B-A3B Q4_K_M: - -- Device: GPU. -- `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all`. -- `GGML_OPENVINO_KV_SLICE` at its default (`1`). See [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout) for eligibility. - -`q4_asym64_all` requantization: - -- Converts Q4_K, Q5_K, Q6_K, Q8_0, Q5_1 and Q5_0 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. -- `token_embd.weight` and `output.weight` keep symmetric channel-wise INT8. -- Q8_0, Q5_1 and Q5_0 rows whose width is not divisible by 64 also use channel-wise INT8. -- Follows the primary/backup precision scheme of [NNCF](https://github.com/openvinotoolkit/nncf) `INT4_ASYM` with `ratio=1.0`, `group_size=64` and `backup_mode=INT8_SYM` for these supported source types. -- Requantizes the GGUF values, not the original floating-point model. Floating-point weights stay unchanged. +Backend files, relative to `ggml/src/ggml-openvino/`, and OpenVINO GPU plugin parts: -Limitations: - -- Cache-only MTP serving requires the separate OpenVINO dynamic output-binding fix ([openvino#39354](https://github.com/openvinotoolkit/openvino/pull/39354)). Removing the recurrent cache Results does not remove that independent trigger in imported MTP graphs. - -Implementation details: - -- Buffer ownership, replay cache writeback through `Assign` sinks, and the GPU replay fusion: [Replay graph contract](OPENVINO-RECURRENT-CACHE.md#replay-graph-contract). -- In-place attention KV update (`GGML_OPENVINO_ENABLE_KV_4D`) and `GGML_OPENVINO_KV_SLICE`: [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout). -- MTP sampling across active slots: [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md). +| File | Content | +|---|---| +| `ggml-openvino.cpp` | Backend, device and buffer interfaces; op support checks, including the replay op checks | +| `ggml-openvino-extra.cpp` | Registry of the environment variables, value checks and device selection | +| `ggml-decoder.cpp` | Dynamic dimensions, control inputs, output names and the `cgraph_ov.txt` dump | +| `utils.cpp` | Compute-branch filtering, compiled reuse, input/output binding, and replay writeback through `query_state()` | +| `model-cache.cpp` | Compiled model cache on disk: cache key (`cache_settings[]`) and source file identity | +| `ggml-quants.cpp` | Extraction and requantization of the GGUF weights | +| `device/npu_config.cpp`, `device/npu_quant_policy.cpp` | NPU plugin properties and NPU weight layouts | +| `openvino/translate_session.cpp` | Runtime sampling aliases, model construction and replay `Assign` sinks | +| `openvino/recurrent_replay_fusion.cpp` | GGML group recognition and standard-op replay translation | +| `openvino/op/` | One translator for each GGML op. `recurrent_replay_graph.hpp` emits the replay pattern. | +| `openvino/pass/` | OpenVINO graph passes, for example `keep_cache_results.cpp` for the KV-only prefill | +| OV `recurrent_replay_fusion.cpp` and `recurrent_cache_replay` | Structural matching, writable-input validation, source staging and GPU computation | ## Compiled model cache -`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled CPU and GPU graphs with their weights. +`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled graphs. Commands: [Compiled model cache](COOKBOOK.md#compiled-model-cache). -- It bypasses the plugin-level `GGML_OPENVINO_CACHE_DIR` and uses `OPTIMIZE_SPEED`, so weightless caching is disabled. +- CPU and GPU: each blob holds its weights. The backend drops the plugin `CACHE_DIR` and uses `CACHE_MODE=OPTIMIZE_SPEED`. +- NPU: weightless blobs plus one shared weights file. - One directory can hold blobs for different models and compilation settings. +- Compatible prefill and decode graphs share one blob and manifest. A graph with different ports or incompatible shapes gets an exact entry instead. +- An interrupted export is not a cache hit. Wait for the `model cache WROTE` message and for the workload to complete before you stop the first run. -1. Run each intended workload once to export its dynamic graph: +The rest of this section covers CPU and GPU. - ```sh - GGML_OPENVINO_DEVICE=GPU \ - GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ - GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \ - ./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1 - ``` - - - `GGML_OPENVINO_SPILL_DIR` remains optional for this first run. - - Wait for the `model cache WROTE` message and for the workload to complete before stopping it. Interrupted exports are not cache hits. - - Compatible prefill and decode graphs share one blob and manifest. A graph with different ports or incompatible shapes gets an exact entry instead. - -2. On later runs, supply the same compilation settings and set `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`: - - ```sh - GGML_OPENVINO_DEVICE=GPU \ - GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \ - GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \ - GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \ - ./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1 - ``` - -Cache-only mode: +Cache-only mode (`GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`): - Allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. - Weight uploads only record the source identity. They do not read or requantize the weights. @@ -93,28 +72,29 @@ Cache-only mode: - Fails with an error for a missing or incompatible graph, instead of compiling with absent weights. - Uses the settings of the current process. A different workload can still require another graph: populate it first without cache-only mode. -Settings that must stay exactly the same between the runs, including set versus unset. A different value selects another cache entry, and cache-only mode then fails: +Settings that must stay exactly the same between the runs, including set versus unset. A different value selects another cache entry, and cache-only mode then fails. Source: `cache_settings[]` in `model-cache.cpp`. - `GGML_OPENVINO_GPU_CONFIG`, `GGML_OPENVINO_CPU_CONFIG`, `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_EXACT_ZERO_POINT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN` - `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_KV_SCATTER_ELEMENTS` - `GGML_OPENVINO_GDN_NATIVE_STATE`, `GGML_OPENVINO_GDN_DECOMPOSE`, `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` - `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` -- `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN`, `GGML_OPENVINO_ROPE_F32_ANGLE`, `GGML_OPENVINO_DEBUG_NODE` -- `GGML_OPENVINO_ENABLE_KV_4D` (its effective value). +- `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN`, `GGML_OPENVINO_DEBUG_NODE` +- `GGML_OPENVINO_ENABLE_KV_4D` and `GGML_OPENVINO_ROPE_SINCOS` (their effective values). - `GGML_OPENVINO_PROFILING`: only whether it is `2` or more. - On GPU, also `GGML_OPENVINO_MOE_OP=0` if used. - `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`: not part of the cache key, but `1` makes the backend reject the replay cache stores. The graph is then split, and cache-only mode does not support split graphs. Settings that can differ: -- `GGML_OPENVINO_SPILL_DIR`: optional on the first run and ignored in cache-only mode. Host-weight release is disabled in cache-only mode. +- `GGML_OPENVINO_COMPILE_MEM_SPILL` and `GGML_OPENVINO_COMPILE_MEM_SPILL_DIR`: optional on the first run and ignored in cache-only mode. Host-weight release is disabled in cache-only mode. - `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`: changes only the output bindings. -- `GGML_OPENVINO_KV_SLICE`: a runtime binding option for dynamic graphs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Eligibility: [Attention KV layout](OPENVINO-RECURRENT-CACHE.md#attention-kv-layout). +- `GGML_OPENVINO_KV_SLICE`: a runtime binding option for dynamic graphs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Eligibility: [KV cache binding](#kv-cache-binding). Cache entries: - The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings and OpenVINO version. - Changing only the dynamic token or KV sizes does not require a new entry. +- Exception: a model with one KV head whose first graph has one token. That graph gets its own entry, and a longer prompt converts it again. - MTP draft graphs: a change of the active slot subset reuses the same compiled draft model. See [Compiled models and the cache](MTP-SAMPLING-GRAPH.md#compiled-models-and-the-cache). ### Restrictions @@ -124,9 +104,55 @@ Cache entries: - The model must execute entirely on OpenVINO, with dynamic CPU or GPU graphs and in-process caching enabled. Static (NPU) execution and CPU fallback are not supported in cache-only mode. - GGUF metadata, tokenizer data, tensor descriptors and graph construction are still needed. The llama.cpp loader is unchanged: depending on its prefetch settings, it may request pages with `MAP_POPULATE` or read-ahead on Linux, or `PrefetchVirtualMemory` on Windows. Non-mmap loading also reads the payload before the backend sees it. - Cache entries are identified by file identity, size, modification and change timestamps, tensor offsets, graph structure, settings and OpenVINO version. Linux uses device and inode; Windows uses volume serial and file index. Replacing, copying or modifying a GGUF model file invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference. -- Use the same target device and a compatible OpenVINO and plugin installation. Import support depends on the plugin: the tested CPU plugin cannot import MoE graphs that contain `GatherMatmulCompressed`. GPU MoE and CPU dense graph imports were tested. +- Small weights that the loader builds in memory (up to 64 MiB, for example the Bonsai 2 Hadamard matrix) have no file identity. A hash of their first and last 4 KiB identifies them. +- Use the same target device and a compatible OpenVINO and plugin installation. The CPU plugin cannot import MoE graphs with `GatherMatmul` ops. The backend writes no blob for them, and cache-only mode fails for MoE models on CPU. GPU MoE and CPU dense graph imports were tested. - Blobs contain weights and can approach the model size for each compiled graph. Import still reads those blobs and initializes the device. +## KV cache binding + +This section covers how four variables bind the attention KV cache. Their table rows are in [Switches for default optimizations](OpenVINO-ENV-VARS.md#switches-for-default-optimizations). + +- `GGML_OPENVINO_ENABLE_KV_4D`: native stateless in-place attention updates on GPU. +- `GGML_OPENVINO_KV_SLICE`: binding switch on dynamic CPU and GPU; base of the compiled KV windows on static NPU. +- `GGML_OPENVINO_GPU_KV_ROUND_UP`: attended-width rounding on dynamic stateless GPU. +- `GGML_OPENVINO_NPU_BLOB_PREBUILD`: one decode graph for each KV window on static NPU. + +`GGML_OPENVINO_ENABLE_KV_4D`: + +- Binds the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. +- Uses the upstream stateless in-place attention KV update pattern where eligible. It binds full-capacity cache tensors and lets the GPU fusion expose the live prefix to attention. +- Unset: on with OpenVINO 2026.5 or later, off with older versions (much slower there). `0` turns it off. `1` turns it on with older OpenVINO versions. +- The current eligibility covers one physical stream, including unified KV. It also needs a dynamic, stateless graph that is not split. `-fa off` and soft-capped attention (gemma-2) keep the full-cache layout. +- Explicit split multi-slot KV keeps the full-cache path and can be much slower, even with only one active slot. +- It does not change recurrent cache handling. +- Use `--kv-unified` for multi-slot OV GPU serving. Unified KV enables this in-place attention update. +- With OpenVINO 2026.5, `GGML_OPENVINO_ENABLE_KV_4D=0` can stop a process that runs two models on the GPU at the same time (`CL_OUT_OF_RESOURCES`). + +`GGML_OPENVINO_KV_SLICE` on dynamic CPU and GPU: + +- Eligible root: a contiguous ordinary attention K/V root with one allocated stream, one active sequence at offset zero, and no sliding-window attention. For it, the backend binds a view of the allocation sized to the attended prefix, and sizes the KQ masks to match. +- Recurrent convolution/GDN caches and their rollback snapshots always keep their full stored row bank. Sliding-window attention and other layouts use the full binding. +- The 4-D in-place attention path takes precedence. It binds the full allocation first and exposes the attended prefix inside the graph. +- Dynamic compiled blobs can accept either eligible binding, so the value can differ between cache population and cache-only runs. + +`GGML_OPENVINO_KV_SLICE` and `GGML_OPENVINO_NPU_BLOB_PREBUILD` on static NPU: + +- `GGML_OPENVINO_KV_SLICE` selects the base of the compiled KV windows. `1` means base 1024; an explicit multiple of 256 changes it. `0` turns the windows off. With `0`, `llama-bench -d` fails on the NPU. +- The window is the smallest `base * 2^k` that covers the attended length, capped by the context. +- The prefill graph is compiled at the window that covers the attended length. A loaded prefill graph of a larger window also serves a shorter prompt. With `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window serves it. +- `GGML_OPENVINO_NPU_BLOB_PREBUILD=1`: decode attends the smallest window that covers the next position, with one decode graph for each window. The prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. +- With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window. Only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. +- `GGML_OPENVINO_NPU_BLOB_PREBUILD=0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. +- Use the same values of both variables in the run that writes the cache and in the runs that read it. + +`GGML_OPENVINO_GPU_KV_ROUND_UP` on dynamic stateless GPU: + +- Controls the attended width separately from prefix binding. +- `0`: the decoder uses the GGML mask width. Ordinary GGML attention KV already pads it in steps of 256 rows. +- `1` (default): power-of-two windows when the graph input has more than 16 tokens, and coarser aligned steps for smaller batches. The step starts at 256 rows and doubles whenever the width reaches eight times the current step. +- Example: at 33,024 GGML rows, the added rounding can expand attention to 40,960 rows for decode or 65,536 for a larger prefill input, subject to the context cap. +- Added mask columns contain negative infinity. + ## KV-only prefill On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), models whose tail layers read the KV cache of an earlier layer (Gemma 3n/4 E-series) get a KV-only prefill by default. @@ -134,27 +160,54 @@ On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), mod - The static prefill graph is compiled with only the KV-cache writes as outputs (`openvino/pass/keep_cache_results.cpp`). - Everything that only feeds the logits is dropped from that graph: every KV-shared layer, plus the LM head. - When the batch needs logits, the decode graph runs once on the output token. It rewrites the KV rows of that token and computes the dropped layers against the complete cache. +- With decode KV windows (`GGML_OPENVINO_NPU_BLOB_PREBUILD=1`), the output step runs the decode graph of the window that covers the output token. - It is used only when attention ops of the graph share a KV cache tensor and the graph has no recurrent state. -- If a batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on. - -Environment variables: - +- The first call of a graph decides. A first call with more than one output token uses the full prefill for that graph. +- If a later batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on. - `GGML_OPENVINO_KV_ONLY_PREFILL=0` turns it off. ## NPU host gather -`GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU only, off by default) gathers the rows of large host-resident embedding tables on the host. +`GGML_OPENVINO_NPU_HOST_GATHER` (NPU only, on by default; `0` turns it off) gathers the rows of large host-resident embedding tables on the host. -- Applies to tables of at least 64 MiB with raw GGUF data. +- Applies to tables of at least 64 MiB in host memory with raw GGUF rows: a CPU buffer, or an OpenVINO buffer with `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` set. - The static graph gets the gathered rows through a `ggml_host_rows_` input instead of an OpenVINO `Gather` over the table. - Without it, NPUW lifts the table to a function input. Gathering from an input that large costs about as much as streaming the whole table on every call. - A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all. +## Qwen MTP + +The OpenVINO backend translates Qwen recurrent replay for complete dynamic stateless GPU graphs and supports stable MTP sampling. Commands: [Speculative decoding](COOKBOOK.md#speculative-decoding). + +Requirements: + +- Dynamic stateless GPU execution. OpenVINO replay requires it. +- A GGUF model file that contains MTP weights. +- For several slots, the unified KV cache (`--kv-unified`) is the recommended layout. See [KV cache binding](#kv-cache-binding). + +`q4_asym64_all` requantization (recommended for Qwen3.6-35B-A3B Q4_K_M): + +- Converts Q4_K, Q5_K, Q6_K, Q8_0, Q5_1 and Q5_0 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. +- `token_embd.weight` and `output.weight` keep symmetric channel-wise INT8. +- Q8_0, Q5_1 and Q5_0 rows whose width is not divisible by 64 also use channel-wise INT8. +- Follows the primary/backup precision scheme of [NNCF](https://github.com/openvinotoolkit/nncf) `INT4_ASYM` with `ratio=1.0`, `group_size=64` and `backup_mode=INT8_SYM` for these supported source types. +- Requantizes the GGUF values, not the original floating-point model. Floating-point weights stay unchanged. + +Limitations: + +- Cache-only MTP serving requires the separate OpenVINO dynamic output-binding fix ([openvino#39354](https://github.com/openvinotoolkit/openvino/pull/39354)). Removing the recurrent cache Results does not remove that independent trigger in imported MTP graphs. The fix is on the OpenVINO master branch. It is not in a release yet. + +Implementation details: + +- Buffer ownership, replay cache writeback through `Assign` sinks, and the GPU replay fusion: [Replay graph contract](OPENVINO-RECURRENT-CACHE.md#replay-graph-contract). +- In-place attention KV update (`GGML_OPENVINO_ENABLE_KV_4D`) and `GGML_OPENVINO_KV_SLICE`: [KV cache binding](#kv-cache-binding). +- MTP sampling across active slots: [MTP-SAMPLING-GRAPH.md](MTP-SAMPLING-GRAPH.md). + ## Multimodal -Image input is experimental. +Image input is experimental. Commands: [Image input](COOKBOOK.md#image-input). -- Qwen3.5 and Gemma4 E2B image input runs on OpenVINO CPU and GPU with their matching projectors. +- Qwen3.5, Qwen3-VL and Gemma4 E2B image input runs on OpenVINO CPU and GPU with their matching projectors. - Four-slot serving was validated with unified and split KV. - Qwen3.5 reuses its vision graph across image resolutions. Gemma4 uses resolution-specific encoder graphs. @@ -162,27 +215,4 @@ Limitations: - NPU: work in progress. Image input fails because of dynamic shapes. - Gemma4 audio is not enabled. Preprocessing and Conformer still need dynamic length/block handling, runtime padding and view/state offsets, and cross-length compiled-model reuse. -- The small weightless preprocessing graph runs uncached because of the node-count heuristic of the naive path. - -Gemma4 E2B image input on GPU or CPU: - -```bash -# Gemma4 E2B image input on GPU (or CPU). The chat template of the model needs --jinja. -# The projector (mmproj) file is in the same Hugging Face repository as the model. -# The model writes its reasoning before the answer. -export GGML_OPENVINO_DEVICE=GPU -./build/ReleaseOV/bin/llama-mtmd-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf \ - --mmproj mmproj-google_gemma-4-E2B-it-f16.gguf --jinja -c 4096 \ - --image cat.jpg -p "What animal is in this image?" -``` - -Qwen3-VL-4B image input on GPU: - -```bash -# Qwen3-VL-4B image input on GPU. Model and projector: https://huggingface.co/unsloth/Qwen3-VL-4B-Instruct-GGUF -# -ub 128 keeps the image prefill within the memory of a 16 GB system (or use --image-max-tokens 256). -export GGML_OPENVINO_DEVICE=GPU -./build/ReleaseOV/bin/llama-mtmd-cli -m Qwen3-VL-4B-Instruct-Q4_K_M.gguf \ - --mmproj mmproj-F16.gguf --jinja -c 4096 -ub 128 \ - --image tools/mtmd/test-1.jpeg -p "Describe this image in one sentence." -``` +- The small preprocessing graph has no weights. It takes the naive path, which compiles it on every call. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 31b1aa9f1ae4..42dfeab4f18a 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -658,12 +658,13 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { const auto * concat = consumer->src[0]; if (concat->op == GGML_OP_CONCAT && concat->src[1]->op == GGML_OP_TRANSPOSE) { const auto * seq = concat->src[1]->src[0]; - // LFM2 short convolutions gate the input first: transpose(mul(view(node), view(node))). + // Short convolutions may gate two views of the same projection before transposing. if (seq->op == GGML_OP_MUL && seq->src[0]->op == GGML_OP_VIEW && seq->src[0]->src[0] == node && seq->src[1]->op == GGML_OP_VIEW && seq->src[1]->src[0] == node) { seq = node; } - recurrent_sequence = seq == node; + // Mamba splits the convolution input from its packed projection. + recurrent_sequence = seq == node || (seq->op == GGML_OP_VIEW && seq->src[0] == node); } else if (concat->op == GGML_OP_CONT && concat->src[0]->op == GGML_OP_TRANSPOSE) { const auto * cols = concat->src[0]->src[0]; recurrent_sequence = cols->op == GGML_OP_CONCAT && cols->op_params[0] == 1 && cols->src[1] == node; @@ -942,6 +943,16 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { } break; } + case GGML_OP_MUL: { + const auto * norm = node->src[0]; + const auto * weight = node->src[1]; + if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_RESHAPE && + weight->op == GGML_OP_NONE && weight->ne[0] == norm->ne[0] && weight->ne[1] == norm->ne[1] && + weight->ne[1] > 1 && weight->ne[2] == 1 && weight->ne[3] == 1 && ggml_openvino_is_gpu()) { + return 1; + } + break; + } case GGML_OP_GATED_DELTA_NET: { if (is_gdn_out_prescaled(node)) { op_case = 1; @@ -2667,7 +2678,7 @@ std::shared_ptr GgmlOvDecoder::create_weight_node(ggml_tensor * tensor // GGML_LOG_DEBUG("%s: creating new weight node for %s\n", __func__, tensor->name); static const std::set weight_types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q4_K, - GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_MXFP4}; + GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_MXFP4, GGML_TYPE_Q2_0}; if (weight_types.find(tensor->type) == weight_types.end()) { throw std::runtime_error("Unexpected weight tensor type: " + std::string(tensor->name) + " with type " + ggml_type_name(tensor->type)); @@ -3418,6 +3429,32 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { break; } } + if (m_node_dynamic_dims[node] == -1) { + // A reshape can also split or merge the dynamic axis (e.g. the blockwise Hadamard rotation: [T, K] <-> [T * K / block, block]), so the stride match above finds nothing. + // Take the output axis that spans the same elements: the axes above it are static, and the axes up to and including it hold as many elements as in the source. + int64_t src_below = 1; + for (int i = 0; i < dynamic_dim_idx; i++) { + src_below *= node->src[0]->ne[i]; + } + int64_t src_above = 1; + for (int i = dynamic_dim_idx + 1; i < GGML_MAX_DIMS; i++) { + src_above *= node->src[0]->ne[i]; + } + const int64_t src_upto = src_below * node->src[0]->ne[dynamic_dim_idx]; + + int64_t dst_below = 1; + for (int i = 0; i < GGML_MAX_DIMS; i++) { + int64_t dst_above = 1; + for (int j = i + 1; j < GGML_MAX_DIMS; j++) { + dst_above *= node->ne[j]; + } + if (dst_above == src_above && dst_below * node->ne[i] == src_upto) { + m_node_dynamic_dims[node] = i; + break; + } + dst_below *= node->ne[i]; + } + } if (m_node_dynamic_dims[node] == -1) { GGML_LOG_WARN("ggml-openvino: cannot determine dynamic dim for RESHAPE node '%s'\n", node->name); } @@ -3533,6 +3570,8 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { case GGML_OP_TRI: case GGML_OP_REPEAT: case GGML_OP_DUP: + case GGML_OP_SQR: + case GGML_OP_SQRT: // Shape-preserving elementwise ops: the dynamic dim is unchanged from src[0]. // DIV/CLAMP are used in the MoE routing-weight normalization // (sum_rows -> clamp -> div). If they are left untracked here the dynamic @@ -3550,9 +3589,9 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]]; break; case GGML_OP_SUM_ROWS: + case GGML_OP_MEAN: case GGML_OP_POOL_1D: - // SUM_ROWS/POOL_1D change only ggml axis 0 and preserve all other axes, so the - // dynamic dim is preserved unless it was axis 0. + // Only axis 0 changes. Preserve a dynamic dimension on any other axis. m_node_dynamic_dims[node] = (m_node_dynamic_dims[node->src[0]] == 0) ? -1 : m_node_dynamic_dims[node->src[0]]; break; @@ -3562,7 +3601,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() { break; case GGML_OP_CPY: case GGML_OP_SUM: - case GGML_OP_MEAN: case GGML_OP_ARANGE: m_node_dynamic_dims[node] = -1; break; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index ec017a8f56fa..762df6d29998 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -366,7 +366,7 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { const std::map & get_model_outputs() const { return m_model_outputs; } - virtual int get_ctx_size() const { return m_model_params.ctx; } + int get_ctx_size() const override { return m_model_params.ctx; } virtual int get_ctx_per_seq() const { return m_model_params.ctx_per_seq; } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index e9e431162e64..2ab49ba53300 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -128,7 +128,8 @@ constexpr env_var env_vars[] = { // Text {"GGML_OPENVINO_DEVICE", env_type::STR}, {"GGML_OPENVINO_CACHE_DIR", env_type::STR}, - {"GGML_OPENVINO_SPILL_DIR", env_type::STR}, + {"GGML_OPENVINO_COMPILE_MEM_SPILL", env_type::FLOAT}, + {"GGML_OPENVINO_COMPILE_MEM_SPILL_DIR", env_type::STR}, {"GGML_OPENVINO_DEBUG_NODE", env_type::STR}, {"GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR", env_type::STR}, {"GGML_OPENVINO_NPU_COMPILE_CONFIG", env_type::STR}, @@ -149,6 +150,7 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_NPU_REQUANT_POLICY", env_type::ENUM, "group-128|channel-wise"}, {"GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", env_type::ENUM, "f16|q8_0_c|q4_0_128|q4_0_c"}, {"GGML_OPENVINO_REQUANT_KQUANT", env_type::ENUM, "q4_sym128|q4_sym128_all|q4_asym64|q4_asym64_all|native"}, + {"GGML_OPENVINO_ROPE_SINCOS", env_type::ENUM, "auto|host|device|device_f32"}, // Numbers {"GGML_OPENVINO_PREFILL_CHUNK_SIZE", env_type::INT}, {"GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB", env_type::INT}, @@ -184,7 +186,6 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", env_type::BOOL}, {"GGML_OPENVINO_LOG_SUPPORTS_OP", env_type::INT}, {"GGML_OPENVINO_DIAG_GRAPH_IO", env_type::BOOL}, - {"GGML_OPENVINO_ROPE_F32_ANGLE", env_type::BOOL}, {"GGML_OPENVINO_LOG_SWA_LAYERS", env_type::BOOL}, {"GGML_OPENVINO_NATIVE_SOFTPLUS", env_type::BOOL}, {"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", env_type::BOOL}, @@ -271,10 +272,14 @@ std::string checked_env_value(const env_var & var, const char * value) { return std::to_string(number); case env_type::FLOAT: { char * end = nullptr; - (void) std::strtof(value, &end); + const float number = std::strtof(value, &end); if (end == value || !trim_spaces(end).empty()) { GGML_ABORT("ggml-openvino: %s=%s is not valid, use a number", var.name, value); } + if (std::strcmp(var.name, "GGML_OPENVINO_COMPILE_MEM_SPILL") == 0 && !(number >= 0 && number <= 1)) { + GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a fraction in between (0.1)", + var.name, value); + } break; } case env_type::BOOL: @@ -699,7 +704,21 @@ bool ggml_openvino_npu_kv_head_major_enabled() { } bool ggml_openvino_npu_host_gather_enabled() { - return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER") != 0; + return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER", 1) != 0; +} + +ggml_openvino_rope_sincos_mode ggml_openvino_rope_sincos() { + const char * value = ggml_openvino_getenv_str("GGML_OPENVINO_ROPE_SINCOS", "auto"); + if (strcmp(value, "host") == 0) { + return ggml_openvino_rope_sincos_mode::HOST; + } + if (strcmp(value, "device") == 0) { + return ggml_openvino_rope_sincos_mode::DEVICE; + } + if (strcmp(value, "device_f32") == 0) { + return ggml_openvino_rope_sincos_mode::DEVICE_F32; + } + return ggml_openvino_is_npu() ? ggml_openvino_rope_sincos_mode::HOST : ggml_openvino_rope_sincos_mode::DEVICE; } bool ggml_openvino_kv_only_prefill_enabled() { @@ -958,6 +977,17 @@ bool ggml_openvino_kv_4d_enabled() { return enabled; } +bool ggml_openvino_gpu_u2_matmul_broken() { + // OpenVINO 2026.5 and older: the GPU plugin runs oneDNN's u2 matmul in multi-token graphs so that later kernels fault (CL_OUT_OF_RESOURCES). Fixed in 2027.0. + static const bool broken = [] { + const char * build = ov::get_openvino_version().buildNumber; + int major = 0; + int minor = 0; + return build == nullptr || std::sscanf(build, "%d.%d", &major, &minor) != 2 || major < 2027; + }(); + return broken && ggml_openvino_is_gpu(); +} + size_t ggml_openvino_max_alloc_size(const std::string & device) { const auto & gpu_contexts = ggml_openvino_get_device_config().gpu_contexts; auto it = gpu_contexts.find(device); @@ -1001,11 +1031,24 @@ static bool is_8bit_layout(ggml_type type) { return type == GGML_TYPE_Q5_0 || type == GGML_TYPE_Q5_1 || type == GGML_TYPE_Q8_0; } +size_t ggml_openvino_u2_group_size(ggml_type type) { + switch (type) { + case GGML_TYPE_Q2_0: + return 64; + default: + return 0; + } +} + // Get requantization type for a tensor type (returns nullopt if no requant needed) std::optional ggml_openvino_get_requant_type(const ggml_tensor * tensor, bool no_requant) { if (no_requant) { return std::nullopt; } + // 2-bit weights stay u2: a requant (4 bit or wider) makes them larger and loses the ternary FullyConnected path, the only one with the fused Hadamard input transform. + if (ggml_openvino_u2_group_size(tensor->type) != 0) { + return std::nullopt; + } if (strncmp(tensor->name, "token_embd.weight", 17) == 0) { if (ggml_openvino_is_npu()) { if (auto npu_type = ggml_openvino_npu_token_embd_requant_type(tensor)) { @@ -1276,14 +1319,21 @@ ggml_openvino_extracted_layout ggml_openvino_get_extracted_layout(const ggml_ten case GGML_TYPE_Q5_K: break; + case GGML_TYPE_Q2_0: + // Codes {0,1,2,3} dequantize as (code - 1) * scale. The zero point is the same for every block, so make_int2_weights emits it as a scalar and no zp array is stored (is_symmetric means "no per-block zp" here). + layout.is_u2 = true; + layout.weights_per_block = ggml_openvino_u2_group_size(tensor->type); + layout.is_symmetric = true; + break; + default: // Unsupported quantization type return layout; } // Calculate sizes - // Weights: U4 = n_elements/2 bytes, U8 = n_elements bytes - layout.weights_size = layout.is_u4 ? (n_elements / 2) : n_elements; + // Weights: U2 = n_elements/4 bytes, U4 = n_elements/2 bytes, U8 = n_elements bytes + layout.weights_size = layout.is_u2 ? (n_elements / 4) : (layout.is_u4 ? (n_elements / 2) : n_elements); // Scales: F16 per block, except MXFP4 which stores one E8M0 byte per block. int64_t n_blocks = n_elements / layout.weights_per_block; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 2f805bb42cfa..267ff32dc78b 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -154,8 +154,7 @@ bool ggml_openvino_npu_l0_host_tensors_enabled(); // On by default: build the static prefill mask directly in the input tensor; GGML_OPENVINO_NPU_FAST_MASK=0 turns it off. bool ggml_openvino_npu_fast_mask_enabled(); -// NPU-only opt-in performance toggles (all default off). Centralized here so each -// env-var name lives in one place; see docs/backend/OPENVINO.md for semantics. +// NPU-only performance toggles (defaults vary). Centralized here so each env-var name lives in one place; see docs/backend/OPENVINO.md for semantics. bool ggml_openvino_npu_hfa_prefill_enabled(); bool ggml_openvino_npu_decode_unfold_enabled(); // Static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): prefill only the KV-writing part of the model @@ -168,6 +167,10 @@ bool ggml_openvino_kv_only_prefill_enabled(); // binding the whole table to the NPU (NPUW lifts it to a function input, and gathering from an input that large // costs about as much as streaming the table). bool ggml_openvino_npu_host_gather_enabled(); +// Where ROPE computes cos/sin (GGML_OPENVINO_ROPE_SINCOS): f16 loses whole radians of the angle at long positions, which breaks long-context recall. +// HOST: an f32 table built on the host (static graphs only), DEVICE: Sin/Cos on the device, DEVICE_F32: on the device with the angle kept in f32. "auto" is HOST on the NPU, else DEVICE. +enum class ggml_openvino_rope_sincos_mode { DEVICE = 0, HOST = 1, DEVICE_F32 = 2 }; +ggml_openvino_rope_sincos_mode ggml_openvino_rope_sincos(); // GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1), with GGML_OPENVINO_KV_SLICE on: static NPU decode also attends a KV // window of base*2^k rows (clamped to ctx, base from GGML_OPENVINO_KV_SLICE) instead of the whole ctx, with one @@ -280,6 +283,21 @@ void ggml_openvino_unregister_weight_buffer(const void * data); void ggml_openvino_release_weight_buffers(); bool ggml_openvino_restore_weight_buffers(); +// With a GGML_OPENVINO_COMPILE_MEM_SPILL fraction, the limiters trim the spilled weights while the model loads, and while a scope is alive and for 10 s after; otherwise they sleep. +// Hold one around compile_model (it reads the weights back) and around rewriting released weights. +struct ggml_openvino_spill_trim_scope { + ggml_openvino_spill_trim_scope(); + ~ggml_openvino_spill_trim_scope(); + ggml_openvino_spill_trim_scope(const ggml_openvino_spill_trim_scope &) = delete; + ggml_openvino_spill_trim_scope & operator=(const ggml_openvino_spill_trim_scope &) = delete; +}; + +// Group size of a 2-bit type that is loaded as u2 weights, 0 for other types +size_t ggml_openvino_u2_group_size(ggml_type type); + +// true if non-ternary 2-bit weights must reach the GPU as u4 (see make_int2_weights) +bool ggml_openvino_gpu_u2_matmul_broken(); + // Get requantization type for a tensor type (returns nullopt if no requant needed) std::optional ggml_openvino_get_requant_type(const ggml_tensor * tensor, bool no_requant = false); @@ -357,6 +375,7 @@ struct ggml_openvino_extracted_layout { size_t zp_offset = 0; // Offset to zero points in buffer size_t zp_size = 0; // Size of zero points in bytes (U4 or U8) bool is_u4; // true for U4 weights, false for U8 + bool is_u2 = false; // true for 2-bit U2 weights (Q2_0); is_u4 is then false int64_t weights_per_block; // weights per scale/zp block bool is_symmetric; // true for symmetric quantization diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index def89208abc2..848db4e0810d 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -13,7 +13,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -33,7 +35,10 @@ #include #include #include +#include +#include #include +#include #include #ifdef _WIN32 @@ -47,6 +52,15 @@ # include # include # include +# ifdef __linux__ +# include +# include +# endif +#endif + +// A GGML_OPENVINO_COMPILE_MEM_SPILL fraction needs MADV_PAGEOUT (Linux 5.4) +#if defined(__linux__) && defined(MADV_PAGEOUT) +# define GGML_OPENVINO_SPILL_LIMITER #endif // ===================================================== @@ -67,6 +81,201 @@ // ===================================================== namespace { +// Live ggml_openvino_spill_trim_scope objects, and when the last one ended +std::atomic spill_scopes{0}; +std::atomic spill_scope_end_us{0}; + +#ifdef GGML_OPENVINO_SPILL_LIMITER +// GGML_OPENVINO_COMPILE_MEM_SPILL fraction: keep at most `budget` bytes of a spilled weight buffer in RAM. The kernel evicts file-backed pages only under memory pressure, so with free RAM the whole buffer stays resident. +// A thread writes the dirty pages to the file and drops them: after every budget / 2 bytes of weight writes during load, and when the resident part exceeds the budget while a ggml_openvino_spill_trim_scope is alive and for 10 s after (the CPU plugin's first inference reads the weights too). +class spill_resident_limiter { +public: + spill_resident_limiter(void * data, size_t size, size_t budget) : + data_(data), + size_(size), + budget_(budget), + page_(static_cast(sysconf(_SC_PAGESIZE))) { + thread_ = std::thread([this] { run(); }); + } + + ~spill_resident_limiter() { + { + std::lock_guard lock(wake_mutex_); + stop_ = true; + } + wake_.notify_all(); + thread_.join(); + } + + // Called after a write into the buffer. Written pages are resident, so the thread pages out after every budget / 2 bytes without measuring; it runs alongside because the disk write takes as long as the conversion. + void note_write(size_t bytes) { + if ((written_ += bytes) >= budget_ / 2) { + written_ = 0; + { + std::lock_guard lock(wake_mutex_); + page_out_requested_ = true; + } + wake_.notify_all(); + } + } + +private: + static bool in_scope() { return spill_scopes > 0 || ggml_time_us() - spill_scope_end_us < 10 * 1000 * 1000; } + + // Stop at the first failed call: after a failed msync, dropping the pages could lose weights that are not on disk. + static void log_stop(const char * call) { + GGML_LOG_WARN("ggml-openvino: GGML_OPENVINO_COMPILE_MEM_SPILL: %s failed (%s), no limit from now on\n", call, + strerror(errno)); + } + + // Estimated from a sample, because mincore over every page takes ~65 ms for 7 GB. SIZE_MAX when mincore fails. + size_t resident_bytes() { + constexpr size_t run = 16, stride = 1024; // pages + unsigned char pages[run]; + size_t sampled = 0, resident = 0; + for (size_t off = 0; off < size_; off += stride * page_) { + const size_t len = std::min(run * page_, size_ - off); + const size_t n = (len + page_ - 1) / page_; + if (mincore(static_cast(data_) + off, len, pages) != 0) { + log_stop("mincore"); + return SIZE_MAX; + } + for (size_t i = 0; i < n; i++) { + resident += pages[i] & 1; + } + sampled += n; + } + return sampled ? static_cast(double(resident) / sampled * size_) : 0; + } + + // false when a call failed + bool page_out() { + // dirty file pages cannot be dropped until written back + if (msync(data_, size_, MS_SYNC) != 0) { + log_stop("msync"); + return false; + } + if (madvise(data_, size_, MADV_PAGEOUT) != 0) { + log_stop("madvise(MADV_PAGEOUT)"); + return false; + } + return true; + } + + void run() { + std::unique_lock lock(wake_mutex_); + while (!stop_) { + // outside of a scope only note_write brings work: the timeout only checks whether a scope started + const std::chrono::milliseconds wait(in_scope() ? 50 : 500); + wake_.wait_for(lock, wait, [this] { return stop_ || page_out_requested_; }); + if (stop_) { + break; + } + const bool requested = std::exchange(page_out_requested_, false); + if (!requested && !in_scope()) { + continue; + } + lock.unlock(); + const size_t resident = requested ? size_ : resident_bytes(); + if (resident == SIZE_MAX || (resident > budget_ && !page_out())) { + return; + } + lock.lock(); + } + } + + void * data_; + size_t size_; + size_t budget_; + size_t page_; + size_t written_ = 0; // only the loading thread writes weights + std::mutex wake_mutex_; + std::condition_variable wake_; + bool stop_ = false; + bool page_out_requested_ = false; + std::thread thread_; +}; + +// Resident limit of a spilled buffer in bytes: the fraction of its size, at least 1 MiB. 0 (no limit) for 1, or when the limit is not smaller than the buffer. +static size_t ggml_openvino_spill_resident_budget(size_t buffer_size, double fraction) { + if (!(fraction < 1)) { + return 0; + } + const size_t bytes = std::max(static_cast(buffer_size * fraction), 1024 * 1024); + return bytes < buffer_size ? bytes : 0; +} +#else +struct spill_resident_limiter { + void note_write(size_t) {} +}; + +[[maybe_unused]] static size_t ggml_openvino_spill_resident_budget(size_t, double fraction) { // unused on Windows + // warn only when set explicitly, not through GGML_OPENVINO_MEMORY_OPTIMIZE + static std::atomic warned{false}; + if (fraction < 1 && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL") != nullptr && + !warned.exchange(true)) { + GGML_LOG_WARN( + "ggml-openvino: a GGML_OPENVINO_COMPILE_MEM_SPILL fraction needs Linux 5.4 or later, spilling without a " + "limit\n"); + } + return 0; +} +#endif + +#ifndef _WIN32 +// GGML_OPENVINO_COMPILE_MEM_SPILL (checked at startup): 0 off, 1 back the host buffers with files, a fraction also limits the spilled weights kept in RAM. +// Unset: 0.1 with GGML_OPENVINO_MEMORY_OPTIMIZE=1 (not on NPU), else 0. Off in cache-only mode. +static double ggml_openvino_spill_fraction() { + if (ggml_openvino_model_cache_only()) { + return 0; + } + if (const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL")) { + return std::strtod(v, nullptr); + } + return !ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0 ? 0.1 : 0; +} + +// Back a buffer with an unlinked file in GGML_OPENVINO_COMPILE_MEM_SPILL_DIR via MAP_SHARED. Unlike anonymous pages, the kernel can write file-backed pages back and drop them, so the repacked weights need not stay resident next to the mmap'd GGUF. +// Returns nullptr with a warning when the file cannot be made; the caller then uses anonymous memory. +static void * ggml_openvino_spill_map(size_t size, const char * dir) { +# ifdef __linux__ + // On tmpfs or ramfs the file is RAM itself, and reserving its space below would make all of it resident at once. + struct statfs fs; + if (statfs(dir, &fs) == 0 && (fs.f_type == TMPFS_MAGIC || fs.f_type == RAMFS_MAGIC)) { + GGML_LOG_WARN("%s: the spill directory %s is in RAM (tmpfs), using anonymous memory\n", __func__, dir); + return nullptr; + } +# endif + char path[PATH_MAX]; + snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", dir, (int) getpid()); + const int fd = mkstemp(path); + if (fd < 0) { + GGML_LOG_WARN("%s: cannot create a spill file in %s (%s), using anonymous memory\n", __func__, dir, + strerror(errno)); + return nullptr; + } + int err = unlink(path) == 0 && ftruncate(fd, (off_t) size) == 0 ? 0 : errno; +# ifdef __linux__ + // Reserve the disk space now: on a full disk, the first write to a page of a sparse file raises SIGBUS. A filesystem without fallocate keeps the sparse file; copy-on-write filesystems (btrfs, ZFS) can still need space on a rewrite. + if (err == 0 && fallocate(fd, 0, 0, (off_t) size) != 0 && errno != EOPNOTSUPP) { + err = errno; + } +# endif + void * m = MAP_FAILED; + if (err == 0) { + m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + err = m == MAP_FAILED ? errno : 0; + } + close(fd); // the mapping keeps the file alive + if (err != 0) { + GGML_LOG_WARN("%s: cannot spill %zu MB to %s (%s), using anonymous memory\n", __func__, size / 1024 / 1024, dir, + strerror(err)); + return nullptr; + } + return m; +} +#endif + // Buffer context that manages per-tensor allocations (no contiguous buffer for weights) struct ggml_backend_openvino_buffer_context { int device; @@ -99,6 +308,11 @@ struct ggml_backend_openvino_buffer_context { // data is in the weight buffer registry bool weight_registered = false; + // Set for a spilled buffer with a fraction. The limiter starts at the first weight write: the buffer usage is not known at allocation, and KV cache and compute buffers must not be paged out. + std::unique_ptr spill_limiter; + size_t spill_budget = 0; + // source mappings already evicted once under the budget + std::vector evicted_sources; // One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer // buffer and an allocated buffer must never share one. @@ -168,55 +382,31 @@ struct ggml_backend_openvino_buffer_context { data = nullptr; } } - if (data != nullptr) { - // backed by the Level Zero host tensor above - } else + if (data == nullptr) { #ifndef _WIN32 - if (const char * spill_dir = - ggml_openvino_model_cache_only() ? nullptr : ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) { - // Disk-backed weight buffer: back the repacked weights with a temp file via MAP_SHARED - // instead of anonymous memory. Anonymous pages can only be evicted to swap, so the - // repacked buffer stays pinned alongside the mmap'd source and both are resident at once - // -- that double residency is the load-time peak. File-backed pages are reclaimable: the - // kernel can write them back and drop them under pressure, then re-read on demand, so RSS - // becomes a working set rather than the whole buffer. The file is unlinked immediately, - // so it disappears when the process exits. - // - // The directory must be real storage. Pointing this at a tmpfs mount (/tmp on many - // systems) backs the "spill" with RAM and makes matters worse. - char path[PATH_MAX]; - snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", spill_dir, (int) getpid()); - int fd = mkstemp(path); - if (fd < 0) { - GGML_LOG_ERROR("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno)); - return; - } - unlink(path); // anonymous-but-file-backed: freed on process exit - if (ftruncate(fd, (off_t) size) != 0) { - GGML_LOG_ERROR("%s: ftruncate(%zu) failed: %s\n", __func__, size, strerror(errno)); - close(fd); - return; - } - void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - close(fd); // the mapping keeps the file alive - if (m == MAP_FAILED) { - GGML_LOG_ERROR("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno)); - return; + if (const double spill = ggml_openvino_spill_fraction(); spill > 0) { + const char * spill_dir = + ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL_DIR", "/var/tmp"); + data = ggml_openvino_spill_map(size, spill_dir); + if (data != nullptr) { + spill_mapping = data; + spill_size = size; + GGML_LOG_INFO("%s: buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, + size / 1024 / 1024); + spill_budget = ggml_openvino_spill_resident_budget(size, spill); + ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); + } } - data = m; - spill_mapping = m; - spill_size = size; - GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, - size / 1024 / 1024); - ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); - } else -#endif - { -#ifdef _WIN32 - if (!ggml_openvino_model_cache_only() && ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) { - GGML_LOG_WARN("%s: GGML_OPENVINO_SPILL_DIR is not supported on Windows, ignoring\n", __func__); +#else + // only when set explicitly, not through GGML_OPENVINO_MEMORY_OPTIMIZE + const char * spill = ggml_openvino_getenv_str("GGML_OPENVINO_COMPILE_MEM_SPILL"); + if (spill != nullptr && std::strtod(spill, nullptr) > 0) { + GGML_LOG_WARN("%s: GGML_OPENVINO_COMPILE_MEM_SPILL is not supported on Windows, ignoring\n", + __func__); } #endif + } + if (data == nullptr) { // Anonymous OS memory reads as zero without being touched, so a buffer becomes resident only as it // is written: a weight buffer tensor by tensor while the model loads, the host-untouched prefill // compute buffer never. @@ -265,6 +455,7 @@ struct ggml_backend_openvino_buffer_context { if (kv_on_demand) { ggml_openvino_kv_storage_unregister(data, size); } + spill_limiter.reset(); // its thread reads the mapping if (spill_mapping != nullptr) { #ifdef _WIN32 VirtualFree(spill_mapping, 0, MEM_RELEASE); @@ -463,6 +654,15 @@ void ggml_openvino_unregister_weight_buffer(const void * data) { reg.buffers.end()); } +ggml_openvino_spill_trim_scope::ggml_openvino_spill_trim_scope() { + spill_scopes++; +} + +ggml_openvino_spill_trim_scope::~ggml_openvino_spill_trim_scope() { + spill_scope_end_us = ggml_time_us(); + spill_scopes--; +} + void ggml_openvino_release_weight_buffers() { auto & reg = ov_weight_registry(); std::lock_guard lock(reg.mutex); @@ -503,6 +703,7 @@ void ggml_openvino_release_weight_buffers() { bool ggml_openvino_restore_weight_buffers() { auto & reg = ov_weight_registry(); std::lock_guard lock(reg.mutex); + ggml_openvino_spill_trim_scope trim_scope; return ov_restore_weight_buffers(reg); } @@ -513,6 +714,7 @@ static void ggml_openvino_keep_weight_buffers() { if (reg.keep) { return; } + ggml_openvino_spill_trim_scope trim_scope; if (!ov_restore_weight_buffers(reg)) { GGML_ABORT("ggml-openvino: cannot write the released host weights again"); } @@ -719,6 +921,47 @@ static bool ggml_openvino_range_has_locked_pages(uintptr_t first, uintptr_t last } #endif +#ifdef GGML_OPENVINO_SPILL_LIMITER +// Spilled buffer with a fraction: start the limiter at the first weight, and evict the GGUF pages once. llama.cpp maps the GGUF with MAP_POPULATE, so after the eviction each tensor is read from disk when it is converted. +// The GGUF madvise calls are hints: with --mlock they fail and the pages stay. +static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer_context * ctx, + const void * data, + size_t size) { + if (ctx->spill_budget == 0) { + return; + } + if (!ctx->spill_limiter) { // set_tensor does not run concurrently on one buffer + try { + ctx->spill_limiter = + std::make_unique(ctx->spill_mapping, ctx->spill_size, ctx->spill_budget); + } catch (const std::system_error & e) { + GGML_LOG_WARN("%s: cannot start the GGML_OPENVINO_COMPILE_MEM_SPILL thread (%s), no limit\n", __func__, + e.what()); + ctx->spill_budget = 0; + return; + } + GGML_LOG_INFO( + "%s: at most %zu of %zu MB of the spilled weights stay in RAM (GGML_OPENVINO_COMPILE_MEM_SPILL)\n", + __func__, ctx->spill_budget / 1024 / 1024, ctx->spill_size / 1024 / 1024); + } + const ggml_openvino_source_mapping * mapping = ggml_openvino_find_source_mapping(data, size, ctx->source_mappings); + if (mapping == nullptr) { + return; + } + if (mapping->read_only && std::find(ctx->evicted_sources.begin(), ctx->evicted_sources.end(), mapping->begin) == + ctx->evicted_sources.end()) { + ctx->evicted_sources.push_back(mapping->begin); + madvise(reinterpret_cast(mapping->begin), mapping->end - mapping->begin, MADV_PAGEOUT); + } + // read this tensor back in large requests rather than one page fault at a time + const uintptr_t page = (uintptr_t) sysconf(_SC_PAGESIZE); + const uintptr_t first = (uintptr_t) data & ~(page - 1); + madvise(reinterpret_cast(first), (uintptr_t) data + size - first, MADV_WILLNEED); +} +#else +static void ggml_openvino_spill_before_weight_write(ggml_backend_openvino_buffer_context *, const void *, size_t) {} +#endif + // A weight's GGUF bytes have been converted into its OpenVINO buffer. Pages of a read-only file mapping are clean and // come back from the file if they are read again, so release them instead of letting them compete with the buffer for // RAM while the model loads. Only whole pages are released, and locked pages (--load-mode mlock) are kept. @@ -746,6 +989,12 @@ static void ggml_openvino_release_source_pages(ggml_backend_openvino_buffer_cont VirtualUnlock(reinterpret_cast(first), last - first); } #elif defined(__linux__) +# ifdef GGML_OPENVINO_SPILL_LIMITER + if (ctx->spill_limiter) { + // under a resident budget the GGUF's page cache must go too, not only this process's mapping of it + madvise(reinterpret_cast(first), last - first, MADV_PAGEOUT); // a hint, as above + } +# endif // MADV_DONTNEED fails on locked (mlock) memory and leaves it resident madvise(reinterpret_cast(first), last - first, MADV_DONTNEED); #endif @@ -786,6 +1035,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer memcpy(tensor->data, data, size); return; } + ggml_openvino_spill_before_weight_write(ctx, data, size); try { auto result = process_weight_tensor(tensor, data, tensor->data); result.weight_node->set_friendly_name(tensor->name); @@ -811,6 +1061,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer if (!ctx->external_memory) { ggml_openvino_release_source_pages(ctx, data, size); } + if (ctx->spill_limiter) { + ctx->spill_limiter->note_write(ggml_nbytes(tensor)); + } } catch (const std::exception & e) { GGML_LOG_ERROR("%s: failed to process weight tensor for %s: %s\n", __func__, tensor->name, e.what()); memcpy((char *) tensor->data + offset, data, size); @@ -820,6 +1073,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer } } else { // Non-weight tensor (KV cache, activations, etc.) - copy data. test-backend-ops also goes here + if (is_weight_buffer) { + ggml_openvino_spill_before_weight_write(ctx, data, size); + } if (ctx->is_remote) { cl_command_queue queue = ggml_openvino_get_cl_queue(ggml_openvino_get_available_devices()[ctx->device]); auto mem_cpy_fn = ggml_openvino_get_clEnqueueMemcpyINTEL(); @@ -840,6 +1096,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer if (is_weight_buffer && !ctx->is_remote) { ggml_openvino_record_weight_write(buffer, tensor, offset, data, size, false); } + if (is_weight_buffer && ctx->spill_limiter) { + ctx->spill_limiter->note_write(size); + } if (ggml_openvino_extra_unchanged(ctx, tensor)) { return; @@ -2280,8 +2539,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { !ov::frontend::ggml::op::gdn_per_key_gate_supported()) { reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state " "snapshots or the native state layout"; - } - else if (op->op_params[0] > 1) { + } else if (op->op_params[0] > 1) { if (ggml_openvino_is_static()) { reason = "GATED_DELTA_NET snapshots require dynamic execution"; } @@ -2317,6 +2575,13 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { if (ggml_openvino_is_static()) { return {false, "SSM_SCAN requires dynamic execution"}; } + // x, B and C are read as token-major views (the Mamba-2 graph layout); a view with a sequence stride smaller than its token stride gives wrong results. + for (int i : {1, 4, 5}) { + const ggml_tensor * t = op->src[i]; + if (t->ne[2] > 1 && t->ne[3] > 1 && t->nb[3] < t->nb[2]) { + return {false, "SSM_SCAN with sequence-major x, B or C is not supported"}; + } + } break; } case GGML_OP_VIEW: { @@ -2455,7 +2720,7 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg static std::unordered_set supported_types{ GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_I64, GGML_TYPE_I32, GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q4_K, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q5_K, GGML_TYPE_Q8_0, GGML_TYPE_Q6_K, - GGML_TYPE_MXFP4}; + GGML_TYPE_MXFP4, GGML_TYPE_Q2_0}; // derive supported op sets from the op_table map, keys in // the map use the full macro name (e.g. "GGML_OP_ADD"), while diff --git a/ggml/src/ggml-openvino/ggml-quants.cpp b/ggml/src/ggml-openvino/ggml-quants.cpp index 0c0501fec69e..3793c60128ec 100644 --- a/ggml/src/ggml-openvino/ggml-quants.cpp +++ b/ggml/src/ggml-openvino/ggml-quants.cpp @@ -6,6 +6,7 @@ #include "ggml.h" #include +#include #include #include #include @@ -57,6 +58,8 @@ void unpack_32_4(const uint8_t * data, uint8_t * dst) { } } +constexpr size_t Q2_0_BLOCK_SIZE = 64; // QK2_0 + constexpr size_t MXFP4_BLOCK_SIZE = 32; constexpr size_t MXFP4_BLOCK_QS_SIZE = MXFP4_BLOCK_SIZE / 2; constexpr size_t MXFP4_BLOCK_BYTES = sizeof(uint8_t) + MXFP4_BLOCK_QS_SIZE; @@ -89,6 +92,47 @@ void extract_mxfp4_data(const ggml_tensor * tensor, ov::Tensor & weights_arr, ov }); } +// Extracts (weight, scales) from 2-bit tensors loaded as u2 (see ggml_openvino_u2_group_size). Layout: |16 bit scale|group x 2 bit codes|, code j at bits [2*(j%4), +1] of byte j/4. +// OpenVINO packs u2 the same way, so the codes are copied as they are, in the {0,1,2,3} encoding; make_int2_weights subtracts the scalar zero point of 1. +// scales_arr may hold one scale per several blocks (see q2_0_is_group_128); the first block's scale is kept. +void extract_2bit_data(const ggml_tensor * tensor, size_t group_size, ov::Tensor & weights_arr, ov::Tensor & scales_arr) { + GGML_ASSERT(weights_arr.get_element_type() == ov::element::u2); + + const size_t qs_size = group_size / 4; + const size_t block_bytes = sizeof(uint16_t) + qs_size; + const size_t n_blocks = ggml_nelements(tensor) / group_size; + const size_t blocks_per_scale = n_blocks / scales_arr.get_size(); + const auto * data = static_cast(tensor->data); + auto * weights = static_cast(weights_arr.data()); + auto * scales = scales_arr.data::value_type>(); + + ov::parallel_for(n_blocks, [&](size_t i) { + const uint8_t * block = data + i * block_bytes; + if (i % blocks_per_scale == 0) { + scales[i / blocks_per_scale] = ov::float16::from_bits(*((const uint16_t *) block)); + } + memcpy(weights + i * qs_size, block + sizeof(uint16_t), qs_size); + }); +} + +// Q2_0 files made from group-128 ternary checkpoints store each scale twice. Such a tensor is loaded at group 128 (same values), which the GPU ternary FullyConnected kernel requires. +bool q2_0_is_group_128(const ggml_tensor * tensor, const void * data) { + if (tensor->type != GGML_TYPE_Q2_0 || tensor->ne[0] % 128 != 0) { + return false; + } + constexpr size_t block_bytes = sizeof(uint16_t) + Q2_0_BLOCK_SIZE / 4; + const auto * blocks = static_cast(data); + const size_t n_pairs = ggml_nelements(tensor) / 128; + std::atomic equal{true}; + ov::parallel_for(n_pairs, [&](size_t i) { + const uint8_t * b = blocks + 2 * i * block_bytes; + if (memcmp(b, b + block_bytes, sizeof(uint16_t)) != 0) { + equal.store(false, std::memory_order_relaxed); + } + }); + return equal.load(); +} + // Extracts (weight, scales, zp) from Q4_0 tensors. // Data layout is: |16 bit scale|32 x 4bit weights|. // When zp_arr is empty (symmetric), weights are stored as signed i4 (value - 8). @@ -767,6 +811,75 @@ ov::Output make_int4_weights(ov::Tensor & weight, return std::make_shared(result, ov::element::f32); } +// True if any u2 code is 3, i.e. the weights are not ternary {-1, 0, +1}. +bool u2_has_code_3(const ov::Tensor & weight) { + const auto * data = static_cast(weight.data()); + const size_t size = weight.get_byte_size(); + constexpr size_t chunk = 1 << 16; + std::atomic found{false}; + ov::parallel_for((size + chunk - 1) / chunk, [&](size_t c) { + uint8_t acc = 0; + for (size_t i = c * chunk; i < std::min(size, (c + 1) * chunk); ++i) { + acc |= data[i] & (data[i] >> 1); + } + if (acc & 0x55) { + found.store(true, std::memory_order_relaxed); + } + }); + return found.load(); +} + +// Decompression chain for u2 weights: (code - 1) * scale, grouped along the last axis, with one scalar zero point. +// Ternary weights at group 128 get the zero point as an f16 Constant (the GPU ternary FullyConnected kernel needs it); others get a Convert of an integer one (oneDNN's u2 matmul needs it). Where that matmul is broken, the others are unpacked to u4 (twice the memory). +ov::Output make_int2_weights(ov::Tensor & weight, ov::Tensor & scales, size_t group_size) { + const ov::Shape orig_weight_shape = weight.get_shape(); + GGML_ASSERT(!orig_weight_shape.empty()); + GGML_ASSERT(orig_weight_shape.back() % group_size == 0); + + ov::Shape packed_shape = orig_weight_shape; + packed_shape.back() /= group_size; + packed_shape.push_back(group_size); + + ov::Shape scale_shape = scales.get_shape(); + scale_shape.push_back(1); + scales.set_shape(scale_shape); + + const bool ternary = group_size == 128 && !u2_has_code_3(weight); + std::shared_ptr weights_node; + if (!ternary && ggml_openvino_gpu_u2_matmul_broken()) { + ov::Tensor codes(ov::element::u4, packed_shape); + const auto * src = static_cast(weight.data()); + auto * dst = static_cast(codes.data()); + // 4 codes of a u2 byte become 2 u4 bytes, low code first + ov::parallel_for(weight.get_byte_size(), [&](size_t i) { + const uint8_t b = src[i]; + dst[2 * i] = uint8_t((b & 0x3) | ((b & 0xc) << 2)); + dst[2 * i + 1] = uint8_t(((b >> 4) & 0x3) | ((b >> 2) & 0x30)); + }); + weights_node = std::make_shared(codes); + } else { + weights_node = std::make_shared(ov::element::u2, packed_shape, weight.data(), nullptr); + weights_node->get_rt_info()["__gguf_tensor_holder"] = weight; + } + auto weights_f16 = std::make_shared(weights_node, ov::element::f16); + + ov::Output zero_point = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {1.0f}); + if (!ternary) { + zero_point = std::make_shared( + ov::op::v0::Constant::create(ov::element::u8, ov::Shape{}, {1}), ov::element::f16); + } + auto w_zp = std::make_shared(weights_f16, zero_point, ov::op::AutoBroadcastType::NUMPY); + + auto scales_f16 = std::make_shared(scales); + ov::Output result = + std::make_shared(w_zp, scales_f16, ov::op::AutoBroadcastType::NUMPY); + + auto final_shape = std::make_shared(ov::element::i64, ov::Shape{orig_weight_shape.size()}, + orig_weight_shape); + result = std::make_shared(result, final_shape, false); + return std::make_shared(result, ov::element::f32); +} + ov::Output make_mxfp4_weights(ov::Tensor & weight, ov::Tensor & scales) { const ov::Shape final_shape = weight.get_shape(); GGML_ASSERT(!final_shape.empty()); @@ -1075,6 +1188,14 @@ std::shared_ptr extract_quantized_weights(const ggml_tensor * tensor, return result; } + if (const size_t group_size_2bit = ggml_openvino_u2_group_size(tensor->type)) { + extract_2bit_data(&temp_tensor, group_size_2bit, weights, scales); + const size_t group_size = ggml_nelements(tensor) / scales.get_size(); + auto result = make_int2_weights(weights, scales, group_size).get_node_shared_ptr(); + result->set_friendly_name(tensor->name); + return result; + } + // Determine block size based on tensor type int64_t weights_per_block; bool is_u4; @@ -1358,13 +1479,16 @@ OvWeight process_weight_tensor(const ggml_tensor * tensor, const void * data, vo ov::element::Type weight_type; if (tensor->type == GGML_TYPE_MXFP4) { weight_type = ov::element::f4e2m1; + } else if (layout.is_u2) { + weight_type = ov::element::u2; } else if (layout.is_symmetric) { weight_type = layout.is_u4 ? ov::element::i4 : ov::element::i8; } else { weight_type = layout.is_u4 ? ov::element::u4 : ov::element::u8; } ov::Shape scale_shape = node_shape; - scale_shape.back() /= layout.weights_per_block; + // A merged Q2_0 tensor needs half the scales the layout reserves. + scale_shape.back() /= q2_0_is_group_128(tensor, data) ? 128 : layout.weights_per_block; if (tensor->type == GGML_TYPE_MXFP4) { if (tensor->ne[2] == 1 && tensor->ne[3] == 1) { diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 338b81aa5024..bb1ef896919d 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -147,7 +147,6 @@ static const char * cache_settings[] = { "GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK", "GGML_OPENVINO_KV_SCATTER_ELEMENTS", "GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN", - "GGML_OPENVINO_ROPE_F32_ANGLE", }; void ggml_openvino_model_cache_init() { @@ -170,7 +169,8 @@ void ggml_openvino_model_cache_init() { #endif if (cache_only) { auto & config = ggml_openvino_get_device_config(); - config.environment_variables.erase("GGML_OPENVINO_SPILL_DIR"); + config.environment_variables.erase("GGML_OPENVINO_COMPILE_MEM_SPILL"); + config.environment_variables.erase("GGML_OPENVINO_COMPILE_MEM_SPILL_DIR"); config.environment_variables["GGML_OPENVINO_RELEASE_WEIGHTS"] = "0"; } } @@ -294,7 +294,10 @@ uint64_t ggml_openvino_source_fingerprint(const void * data, size_t size, std::v if (const auto * m = ggml_openvino_find_source_mapping(data, size, mappings)) { return fnv1a_u64(m->identity, m->offset + reinterpret_cast(data) - m->begin); } - if (ggml_openvino_model_cache_only()) { + // A small weight outside any file mapping was built in memory by the model loader (e.g. the Bonsai 2 Hadamard matrix). It is deterministic, and the export run identified it by the content hash below, so cache-only mode can too. + // Only large unmapped weights mean the model itself was not mmap-loaded. + constexpr size_t MAX_UNMAPPED_WEIGHT_BYTES = 64u << 20; + if (ggml_openvino_model_cache_only() && size > MAX_UNMAPPED_WEIGHT_BYTES) { GGML_ABORT("ggml-openvino: could not identify mapped GGUF weight; use --load-mode mmap"); } uint64_t h = FNV_OFFSET; @@ -358,7 +361,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 11 honors explicit F32 MatMul input precision with node-level guards. // Version 12 keeps the Q5_0 layout (was Q4_0_64). // Version 13 keeps models converted from an ambiguous one-token graph apart (see can_run_tokens()). - h = fnv1a_u64(h, 13); + // Version 14 hashes the effective GGML_OPENVINO_ROPE_SINCOS (in extra_cfg) instead of GGML_OPENVINO_ROPE_F32_ANGLE. + h = fnv1a_u64(h, 14); h = fnv1a(h, graph_signature.data(), graph_signature.size()); for (const char * name : cache_settings) { const char * value = ggml_openvino_getenv_str(name, ""); diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index a26ce617be95..8d314b42acd5 100644 --- a/ggml/src/ggml-openvino/openvino/decoder.h +++ b/ggml/src/ggml-openvino/openvino/decoder.h @@ -121,6 +121,9 @@ class GgmlDecoder : public DecoderBase { virtual int32_t * get_rope_params() const = 0; + // KV cache size in cells (0 if unknown). + virtual int get_ctx_size() const { return 0; } + virtual int get_ssm_state_size() const = 0; virtual std::map get_kv_param_res_names() const = 0; diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h index a11573216f0d..7e978860bc26 100644 --- a/ggml/src/ggml-openvino/openvino/node_context.h +++ b/ggml/src/ggml-openvino/openvino/node_context.h @@ -169,6 +169,8 @@ class NodeContext : public frontend::NodeContext { int get_ssm_state_size() const { return m_decoder->get_ssm_state_size(); } + int get_ctx_size() const { return m_decoder->get_ctx_size(); } + private: std::shared_ptr m_decoder; std::shared_ptr & m_tensor_map; diff --git a/ggml/src/ggml-openvino/openvino/op/cont.cpp b/ggml/src/ggml-openvino/openvino/op/cont.cpp index 7ea7ee0833b7..3eb3618ced24 100644 --- a/ggml/src/ggml-openvino/openvino/op/cont.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cont.cpp @@ -17,9 +17,9 @@ OutputVector translate_cont(const NodeContext & context) { auto src_shape = context.get_input_shape(0).to_shape(); auto dst_shape = context.get_output_shape().to_shape(); + auto input = process_view_input_new(context, 0); if (context.has_input("vision_shape_" + context.get_name())) { - auto input = process_view_input_new(context, 0); // CONT without a layout change already has its runtime shape. if (src_shape == dst_shape) { return rename_outputs_with_suffix({input}, context.get_name()); @@ -28,12 +28,16 @@ OutputVector translate_cont(const NodeContext & context) { return rename_outputs_with_suffix({std::make_shared(input, target, false)}, context.get_name()); } + // A shape-preserving copy of a recurrent view keeps the runtime sequence and token axes. + if (!context.is_static() && !context.is_stateful() && context.get_view_input_size(0) > 0 && + src_shape == dst_shape && input.get_partial_shape().compatible(dst_shape)) { + return {input}; + } + if (context.get_op_dynamic_dim() != -1) { dst_shape[3 - context.get_op_dynamic_dim()] = -1; } - auto input = process_view_input_new(context, 0); - ov::Output res; res = std::make_shared( input, ov::op::v0::Constant::create(ov::element::i64, {dst_shape.size()}, dst_shape), false); diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index 402d14b999b8..4e40389a011d 100644 --- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp @@ -221,9 +221,8 @@ OutputVector translate_get_rows(const NodeContext & context) { auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1}); res = std::make_shared(data, indices, axis, 1); } else { - // For a tied embedding the same weight also feeds the lm_head matmul. Gathering the - // dequantized table would give that dequantization chain a second consumer, forcing the - // full table to be materialized; gather the packed rows instead and dequantize those. + // For a tied embedding the same weight also feeds the lm_head matmul: gather the packed rows and dequantize those, so the dequantized table does not get a second consumer that forces it to be materialized in full. + // The same holds for a 2-bit u2 table, which the plugins do not gather correctly in compressed form. if (auto compressed = gather_compressed_rows(data, indices)) { res = compressed; } else { diff --git a/ggml/src/ggml-openvino/openvino/op/mul.cpp b/ggml/src/ggml-openvino/openvino/op/mul.cpp new file mode 100644 index 000000000000..c8eeb266c226 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/mul.cpp @@ -0,0 +1,39 @@ +#include "../op_table.h" +#include "../utils.h" + +#include +#include +#include +#include + +namespace ov::frontend::ggml::op { + +OutputVector translate_mul(const NodeContext & context) { + if (context.get_op_case() != 1) { + return translate_1to1_match_2_inputs(context); + } + + num_inputs_check(context, 2, 2); + auto norm = process_view_input_new(context, 0); + auto weight = process_view_input_new(context, 1); + if (weight.get_element_type() != norm.get_element_type()) { + weight = std::make_shared(weight, ov::element::f32); + norm = std::make_shared(norm, ov::element::f32); + } + + // The GPU RMS kernel shares one weight vector across rows. Apply weights with the groups flattened. + const auto weight_shape = context.get_input_shape(1).to_shape(); + const auto width = static_cast(weight_shape[2] * weight_shape[3]); + auto norm_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, {1, 1, -1, width}); + auto flat_weight_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, {1, 1, 1, width}); + auto flat_norm = std::make_shared(norm, norm_shape, false); + auto flat_weight = std::make_shared(weight, flat_weight_shape, false); + ov::Output output = std::make_shared(flat_norm, flat_weight); + if (output.get_element_type() != context.get_output_type()) { + output = std::make_shared(output, context.get_output_type()); + } + auto shape = std::make_shared(norm); + return rename_outputs_with_suffix({std::make_shared(output, shape, false)}, context.get_name()); +} + +} // namespace ov::frontend::ggml::op diff --git a/ggml/src/ggml-openvino/openvino/op/rope.cpp b/ggml/src/ggml-openvino/openvino/op/rope.cpp index c8703747cc11..6fba35f840e2 100644 --- a/ggml/src/ggml-openvino/openvino/op/rope.cpp +++ b/ggml/src/ggml-openvino/openvino/op/rope.cpp @@ -1,16 +1,24 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" +#include "ggml-impl.h" +#include "ggml-openvino/ggml-openvino-extra.h" #include +#include #include +#include +#include +#include #include #include #include #include +#include #include #include #include +#include #include #include #include @@ -18,6 +26,8 @@ #include #include #include +#include +#include #include namespace ov { @@ -25,6 +35,88 @@ namespace frontend { namespace ggml { namespace op { +namespace { + +constexpr int TYPE_NORMAL = 0; +constexpr int TYPE_NEOX = 1; +constexpr int TYPE_IMROPE = 2; +constexpr int TYPE_VISION = 3; +constexpr int TYPE_MROPE = 4; + +// RoPE tables are f16 constants, one per content for the whole process, never freed (as gdn_chunk_mask). The shared NPUW weights bank identifies a constant by its data pointer and keeps it after its model is gone, so a later table at a freed address would be read as the old one. +std::shared_ptr rope_table_f16(const std::shared_ptr & table) { + static std::mutex mutex; + static std::map, std::vector>, std::shared_ptr> cache; + std::pair, std::vector> key{table->get_shape(), table->cast_vector()}; + std::lock_guard lock(mutex); + auto & f16 = cache[key]; + if (!f16) { + f16 = std::make_shared(ov::element::f16, table->get_shape(), key.second); + } + return f16; +} + +// GGML_OPENVINO_ROPE_SINCOS=host: build make_sin_cos for positions 0..ctx-1, fold it on the host in f32, and gather the rows of inp_pos. +// Returns false (sin_cos unset) when the table does not apply; the caller then builds the angle-based subgraph. +bool make_rope_table(const NodeContext & context, + int32_t * op_params, + const std::shared_ptr & inp_pos, + const std::shared_ptr & rope_freqs_weight, + int mode, + int64_t head_dim, + std::pair, Output> & sin_cos) { + const int64_t n_pos = context.get_ctx_size(); + if (ggml_openvino_rope_sincos() != ggml_openvino_rope_sincos_mode::HOST || !context.is_static() || + context.is_stateful() || (mode != TYPE_NORMAL && mode != TYPE_NEOX) || n_pos <= 0) { + return false; + } + // Frequency factors that arrive as a Parameter cannot be folded. + if (rope_freqs_weight && !ov::as_type_ptr(rope_freqs_weight)) { + static std::once_flag warned; + std::call_once(warned, [] { + GGML_LOG_WARN( + "ggml-openvino: RoPE frequency factors are not a constant, so the RoPE angles are computed " + "on the device; long contexts may lose accuracy on the NPU\n"); + }); + return false; + } + const auto & pos_shape = inp_pos->get_output_partial_shape(0); + if (pos_shape.is_dynamic() || pos_shape.rank().get_length() != 4) { + return false; + } + + // All positions, in the [1, 1, 1, n_tokens] layout of inp_pos that make_sin_cos expects. + std::vector positions(n_pos); + std::iota(positions.begin(), positions.end(), 0); + auto all_pos = std::make_shared(inp_pos->get_output_element_type(0), + ov::Shape{1, 1, 1, (size_t) n_pos}, positions); + auto table = make_sin_cos(op_params, all_pos, rope_freqs_weight, mode, false, head_dim); + auto folded = std::make_shared(ov::OutputVector{table.first, table.second}, ov::ParameterVector{}); + ov::pass::Manager manager; + manager.register_pass(); + manager.run_passes(folded); + auto sin_table = ov::as_type_ptr(folded->get_results()[0]->get_input_node_shared_ptr(0)); + auto cos_table = ov::as_type_ptr(folded->get_results()[1]->get_input_node_shared_ptr(0)); + if (!sin_table || !cos_table) { + return false; + } + + // f16 tables (rope_table_f16): the values are in [-1, 1] (times mscale with YaRN or attn_factor != 1), where f16 is as accurate as the f16 the NPU computes with, at half the memory. + // The tables are [1, n_pos, 1, n_dims / 2]; the rows of the current positions give [1, n_tokens, 1, ...]. Positions are clamped, so the padding rows of a static chunk stay inside the table. + Output rows = std::make_shared( + inp_pos, ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}), false); + rows = std::make_shared(rows, 0.0, static_cast(n_pos - 1)); + auto axis = ov::op::v0::Constant::create(ov::element::i64, {}, {1}); + auto gather_rows = [&](const std::shared_ptr & table) -> Output { + auto gathered = std::make_shared(rope_table_f16(table), rows, axis); + return std::make_shared(gathered, table->get_element_type()); + }; + sin_cos = {gather_rows(sin_table), gather_rows(cos_table)}; + return true; +} + +} // namespace + OutputVector translate_rope(const NodeContext & context) { num_inputs_check(context, 2, 3); @@ -41,12 +133,6 @@ OutputVector translate_rope(const NodeContext & context) { const int64_t n_dims = configured_n_dims == 0 ? head_dim : configured_n_dims; const int64_t n_offs = static_cast(op_params[15]); - constexpr int TYPE_NORMAL = 0; - constexpr int TYPE_NEOX = 1; - constexpr int TYPE_IMROPE = 2; - constexpr int TYPE_VISION = 3; - constexpr int TYPE_MROPE = 4; - Output cos_theta_node; Output sin_theta_node; std::string cache_key = "rope_sin_cos"; @@ -67,7 +153,10 @@ OutputVector translate_rope(const NodeContext & context) { if (context.get_input_size() == 3) { rope_freqs_weight = context.get_input(2).get_node_shared_ptr(); } - auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim); + std::pair, Output> sin_cos; + if (!make_rope_table(context, op_params, inp_pos, rope_freqs_weight, mode, head_dim, sin_cos)) { + sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim); + } sin_theta_node = sin_cos.first; cos_theta_node = sin_cos.second; context.put_shared(cache_key + "_cos", cos_theta_node); diff --git a/ggml/src/ggml-openvino/openvino/op/unary.cpp b/ggml/src/ggml-openvino/openvino/op/unary.cpp index 5c338ec56b54..08751596daca 100644 --- a/ggml/src/ggml-openvino/openvino/op/unary.cpp +++ b/ggml/src/ggml-openvino/openvino/op/unary.cpp @@ -9,12 +9,12 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include #include @@ -30,6 +30,24 @@ namespace frontend { namespace ggml { namespace op { +namespace { + +// expm1(x), accurate near 0 like expm1f in the ggml reference: exp(x) - 1 loses the digits of a small x, so |x| <= 0.5 uses the Taylor series (as the Metal backend does). +ov::Output expm1_accurate(const ov::Output & x) { + const auto type = x.get_element_type(); + auto c = [&](float v) { return ov::op::v0::Constant::create(type, ov::Shape{}, {v}); }; + ov::Output p = c(1.0f / 40320.0f); + for (float k : {1.0f / 5040.0f, 1.0f / 720.0f, 1.0f / 120.0f, 1.0f / 24.0f, 1.0f / 6.0f, 0.5f, 1.0f}) { + p = std::make_shared(std::make_shared(p, x), c(k)); + } + auto series = std::make_shared(x, p); + auto direct = std::make_shared(std::make_shared(x), c(1.0f)); + auto small = std::make_shared(std::make_shared(x), c(0.5f)); + return std::make_shared(small, series, direct); +} + +} // namespace + OutputVector translate_unary_gelu(const NodeContext & context) { num_inputs_check(context, 1, 1); auto input = process_view_input_new(context, 0); @@ -56,8 +74,19 @@ OutputVector translate_unary_gelu_quick(const NodeContext & context) { OutputVector translate_unary_elu(const NodeContext & context) { num_inputs_check(context, 1, 1); + // compute in f32 like the ggml reference (NPU cannot take the f32 path) auto input = process_view_input_new(context, 0); - auto res = std::make_shared(input, 1.0); + const auto type = ggml_openvino_is_npu() ? input.get_element_type() : ov::element::f32; + ov::Output x = input; + if (type != input.get_element_type()) { + x = std::make_shared(input, type); + } + auto zero = ov::op::v0::Constant::create(type, ov::Shape{}, {0.0f}); + ov::Output res = + std::make_shared(std::make_shared(x, zero), x, expm1_accurate(x)); + if (type != input.get_element_type()) { + res = std::make_shared(res, input.get_element_type()); + } return rename_outputs_with_suffix({res}, context.get_name()); } diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp index 4983e2a7ccfe..835249b62a0d 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.cpp +++ b/ggml/src/ggml-openvino/openvino/op_table.cpp @@ -14,7 +14,6 @@ #include #include #include -#include #include #include #include @@ -43,7 +42,7 @@ std::unordered_map get_supported_ops() { {"GGML_OP_GET_ROWS", op::translate_get_rows }, {"GGML_OP_IM2COL", op::translate_im2col }, {"GGML_OP_IM2COL_3D", op::translate_im2col_3d }, - {"GGML_OP_MUL", op::translate_1to1_match_2_inputs}, + {"GGML_OP_MUL", op::translate_mul }, {"GGML_OP_MUL_MAT", op::translate_mulmat }, {"GGML_OP_MUL_MAT_ID", op::translate_mul_mat_id }, {"GGML_OP_PERMUTE", op::translate_permute }, diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 37acac0efadd..0f5305c4c025 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -20,6 +20,7 @@ GGML_OP_CONVERTER(translate_fill); GGML_OP_CONVERTER(translate_get_rows); GGML_OP_CONVERTER(translate_im2col); GGML_OP_CONVERTER(translate_im2col_3d); +GGML_OP_CONVERTER(translate_mul); GGML_OP_CONVERTER(translate_mulmat); GGML_OP_CONVERTER(translate_mul_mat_id); GGML_OP_CONVERTER(translate_moe_tiled); diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index 25377fc3ae1b..0825d9713633 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include #include #include @@ -362,10 +364,8 @@ std::pair, ov::Output> make_sin_cos(int32_t * rope_params // Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the // matmuls that dominate. The rotation itself and everything downstream stay f16. // - // Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model, - // it is validated on one model on the GPU only, and on an f32 path the round trip below makes - // cos and sin less accurate. - const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0; + // Off by default; GGML_OPENVINO_ROPE_SINCOS=device_f32 turns it on. It changes the RoPE of every model, it is validated on one model on the GPU only, and on an f32 path the round trip below makes cos and sin less accurate. + const bool pin_angle = ggml_openvino_rope_sincos() == ggml_openvino_rope_sincos_mode::DEVICE_F32; auto cos_op = std::make_shared(theta); auto sin_op = std::make_shared(theta); @@ -448,6 +448,32 @@ ov::Output process_view_input(const NodeContext & context, int input_i namespace { +// Gather rows of a 2-bit u2 Constant [N, K/G, G] (make_int2_weights) and unpack them to i32 codes. The GPU gather kernels have no u2 input, so gather whole rows of the packed bytes and unpack only those (LSB-first, 4 codes per byte). +std::shared_ptr gather_u2_rows(const std::shared_ptr & cnst, + const ov::Output & indices, + size_t idx_rank) { + const auto & shape = cnst->get_shape(); + if (shape.size() != 3 || shape[2] % 4 != 0) { + return nullptr; + } + auto packed = std::make_shared(ov::element::u8, ov::Shape{shape[0], shape[1], shape[2] / 4}, + cnst->get_data_ptr(), cnst); + auto axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0}); + auto rows = std::make_shared(packed, indices, axis); + auto bytes = std::make_shared( + std::make_shared(rows, ov::element::i32), + ov::op::v0::Constant::create(ov::element::i64, {1}, {-1})); + auto shifted = std::make_shared( + bytes, ov::op::v0::Constant::create(ov::element::i32, {4}, {0, 2, 4, 6})); + auto codes = std::make_shared( + shifted, ov::op::v0::Constant::create(ov::element::i32, {}, {3})); + std::vector target(idx_rank, 0); + target.push_back(static_cast(shape[1])); + target.push_back(static_cast(shape[2])); + return std::make_shared( + codes, ov::op::v0::Constant::create(ov::element::i64, {target.size()}, target), true); +} + // Walk a dequantization chain, gathering `indices` out of every leaf Constant that is indexed by // the gathered axis, and rebuild the chain on top of the gathered rows. Only the node types // make_intX_weights emits are recognized; anything else aborts the rewrite (nullptr). @@ -470,6 +496,10 @@ std::shared_ptr rebuild_on_gathered_rows(const ov::Output & type == ov::element::i8) { saw_compressed = true; } + if (type == ov::element::u2) { + saw_compressed = true; + return static_cast(shape[0]) == rows ? gather_u2_rows(cnst, indices, idx_rank) : nullptr; + } if (shape.empty() || static_cast(shape[0]) != rows) { // Scalar or already-broadcast operand (e.g. a single zero point): share it unchanged. return cnst; @@ -515,6 +545,23 @@ std::shared_ptr rebuild_on_gathered_rows(const ov::Output & return nullptr; } +bool has_u2_leaf(const ov::Output & out, size_t depth = 0) { + auto node = out.get_node_shared_ptr(); + if (auto cnst = ov::as_type_ptr(node)) { + return cnst->get_element_type() == ov::element::u2; + } + if (depth > 8 || !(ov::is_type(node) || ov::is_type(node) || + ov::is_type(node) || ov::is_type(node))) { + return false; + } + for (const auto & input : node->input_values()) { + if (has_u2_leaf(input, depth + 1)) { + return true; + } + } + return false; +} + } // namespace std::shared_ptr gather_compressed_rows(const ov::Output & weights, @@ -528,7 +575,8 @@ std::shared_ptr gather_compressed_rows(const ov::Output & we ps[1].is_dynamic() || idx_ps.rank().is_dynamic()) { return nullptr; } - if (ps[0].get_length() * ps[1].get_length() < min_elements) { + // a u2 table takes this path at any size: some GPU plugins (OpenVINO 2026.4) turn a dequantized u2 table plus Gather into GatherCompressed, which reads u2 wrongly + if (ps[0].get_length() * ps[1].get_length() < min_elements && !has_u2_leaf(weights)) { return nullptr; } diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index 194f08be5e76..22900dfa2d06 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -31,12 +31,8 @@ std::pair, ov::Output> make_sin_cos(int32_t * rope_params bool stateful = false, int64_t head_dim = 0); -// If `weights` is a dequantization chain emitted by make_int4_weights/make_int8_weights, rebuild -// it with `indices` gathered out of the leaf Constants, so a row lookup reads the packed rows and -// dequantizes only those. Returns nullptr if the subgraph is not such a chain, or is too small to -// be worth the rewrite. Used for tied embeddings, where the same weight also feeds the lm_head -// matmul: gathering the dequantized table would give that chain a second consumer and force it to -// be materialized in full. +// If `weights` is a dequantization chain from make_int{2,4,8}_weights, rebuild it with `indices` gathered from the leaf Constants, so a row lookup reads and dequantizes only the packed rows. Returns nullptr if it is not such a chain, or is too small to be worth it. +// Used for tied embeddings (a Gather of the dequantized table would give the chain a second consumer and materialize it in full) and for 2-bit u2 tables, which the plugins do not gather correctly in compressed form. std::shared_ptr gather_compressed_rows(const ov::Output & weights, const ov::Output & indices); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index fdc212178ad7..6925e8458775 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -228,6 +228,8 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren extra_cfg = extra_cfg * 131 + (ggml_openvino_shape_from_mask_enabled() ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_hfa_prefill_enabled() ? 4u : 0u); // HFA input ABI v4. extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_host_gather_enabled() ? 1u : 0u); + // The effective GGML_OPENVINO_ROPE_SINCOS: "auto" depends on the device, so the variable alone does not identify the graph. + extra_cfg = extra_cfg * 131 + static_cast(ggml_openvino_rope_sincos()); if (ggml_openvino_is_npu()) { extra_cfg = extra_cfg * 131 + static_cast(ggml_openvino_get_npu_requant_type()); } @@ -1699,10 +1701,13 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share const ov::AnyMap & compile_config = model_cache_dir.empty() ? config : mc_config; ov::CompiledModel compiled_model; auto remote_context = ggml_openvino_get_remote_context(device); - if (remote_context.has_value()) { - compiled_model = core.compile_model(model, remote_context.value(), compile_config); - } else { - compiled_model = core.compile_model(model, device, compile_config); + { + ggml_openvino_spill_trim_scope trim_scope; + if (remote_context.has_value()) { + compiled_model = core.compile_model(model, remote_context.value(), compile_config); + } else { + compiled_model = core.compile_model(model, device, compile_config); + } } compile_end_time = ggml_time_us(); @@ -2138,6 +2143,7 @@ static void build_static_model(const static_build_args & a, ov::AnyMap import_config = model_config; import_config[ov::hint::model.name()] = std::shared_ptr(model); const int64_t import_start_time = ggml_time_us(); + ggml_openvino_spill_trim_scope trim_scope; // ov::hint::model: the import can read the weights compiled_model = core.import_model(blob_in, device, import_config); const int64_t import_end_time = ggml_time_us(); if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) { @@ -2158,6 +2164,7 @@ static void build_static_model(const static_build_args & a, if (a.weightless_bank) { compile_config[ov::enable_weightless.name()] = true; } + ggml_openvino_spill_trim_scope trim_scope; compiled_model = core.compile_model(model, device, compile_config); } local_compile_end_time = ggml_time_us(); From 0570c970176489f4e89d9168822e1b0516a349d0 Mon Sep 17 00:00:00 2001 From: Aaron St George Date: Fri, 4 Dec 2026 09:54:45 -0700 Subject: [PATCH 398/401] docs : add kernel routing guidance to the Loom kernel style guide (#33569) Assisted-by: Codex --- .../ggml-hrx/dev_doc/kernel-style-guide.md | 90 +++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 ggml/src/ggml-hrx/dev_doc/kernel-style-guide.md diff --git a/ggml/src/ggml-hrx/dev_doc/kernel-style-guide.md b/ggml/src/ggml-hrx/dev_doc/kernel-style-guide.md new file mode 100644 index 000000000000..191d379f8f59 --- /dev/null +++ b/ggml/src/ggml-hrx/dev_doc/kernel-style-guide.md @@ -0,0 +1,90 @@ +# Loom kernel style guide + +## Table of contents + +- [Kernel routing](#kernel-routing) covers where to select an implementation and how to keep its Loom launch geometry and device code in agreement. + +## Kernel routing + +Kernel routing is the choice of which Loom kernel will execute an operation for a given graph, workload and device. That choice can affect how GPU threads share the work, which input representation the kernel reads and how many dispatches the operation requires. + +Tuning uses performance measurements to choose parameters for a device and workload. Those parameters often influence routing and can also control how the selected kernel runs. + +### Options + +For `GGML_OP_MUL_MAT` with one input vector, either C++ or Loom can choose between the paired-row and standard schedules. Both sketches use the same compute motifs. + +#### C++ chooses the schedule + +C++ checks whether the paired-row schedule is eligible and sets the kernel symbol in the HRX descriptor. + +```cpp +const bool paired = can_use_mul_mat_vec_pair(dst, input_format, token_capacity, publish_format); +desc.symbol = paired ? "ggml_mul_mat_vec_pair" : "ggml_mul_mat_vec_dot"; +ggml_hrx_kernel * kernel = ggml_hrx_get_kernel(ctx->device, desc); +``` + +Each entry sets up its launch and calls its compute motif directly. + +```mlir +kernel.def @ggml_mul_mat_vec_pair(...) { + ... // Each 64-thread workgroup handles up to two rows of src0. +} launch(...) { + func.call @ggml_matmul_vector_f32_decode_pair(...) + kernel.return +} + +kernel.def @ggml_mul_mat_vec_dot(...) { + ... // Launch geometry for the standard schedule. +} launch(...) { + func.call @ggml_matmul_vector_f32_activation_dot(...) + kernel.return +} +``` + +#### Loom chooses the schedule + +C++ supplies one kernel symbol and passes the information that Loom needs to choose the schedule. + +```cpp +desc.symbol = "ggml_mul_mat_vec"; +desc.config = { ... }; // src0->ne[0], bound input format, token capacity and output mode. +ggml_hrx_kernel * kernel = ggml_hrx_get_kernel(ctx->device, desc); +``` + +Loom checks eligibility in `@use_pair`. The entry uses that choice twice, first to set the launch geometry and then to call the matching compute motif. + +```mlir +func.def pure inline @use_pair() -> (i1) { + ... // Read the configuration and check paired-row eligibility. +} + +kernel.def @ggml_mul_mat_vec(...) { + %paired = func.call pure @use_pair() : () -> (i1) + %groups, %threads = func.call pure @launch_for_schedule(%paired, ...) + : (...) -> (index, index) + %one = index.constant 1 : index + kernel.launch.config workgroups(%groups, %one, %one) + workgroup_size(%threads, %one, %one) : index +} launch(...) { + %paired = func.call pure @use_pair() : () -> (i1) + scf.if %paired { + func.call @ggml_matmul_vector_f32_decode_pair(...) + } else { + func.call @ggml_matmul_vector_f32_activation_dot(...) + } + kernel.return +} +``` + +When the configuration is known during specialization, Loom can remove the unused path. Both options can produce the same device code. + +### Decision + +**Prefer C++ routing and dispatch a Loom entry that calls the selected implementation directly.** Name the entry for the operation and the specialization C++ selects. Keep launch geometry, device indexing, synchronization and target-specific compute motifs in Loom. Entries can share those motifs. When a GPU needs a different route, select it in C++. When the route needs a GPU-specific instruction sequence, specialize its motif in Loom. + +#### Rationale + +C++ may need to know the route ahead of time. For example, a split-K implementation that writes one partial output per partition requires the planner to allocate those partials and arrange their reduction. + +Calling the selected motif directly can also reduce JIT compilation time. In a `gfx1151` experiment, the median compile time was 157.6 ms with a broad Loom selector and 24.5 ms when the same entry called the selected motif directly. [Routing RFC and compiler measurements](https://github.com/ROCm/ggml-staging-automation/issues/189). From c3e91d61a262592ee475a3f8fd4c48253a0e4432 Mon Sep 17 00:00:00 2001 From: Ruben Ortlam Date: Fri, 4 Dec 2026 19:04:51 +0100 Subject: [PATCH 399/401] vulkan: tune Flash Attention flip shader for RDNA3/4 large ubatch (#33683) --- ggml/src/ggml-vulkan/ggml-vulkan-common.h | 2 +- ggml/src/ggml-vulkan/ggml-vulkan.cpp | 26 ++++++++++--------- .../vulkan-shaders/flash_attn_cm1_flip.comp | 9 +++++++ 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-common.h b/ggml/src/ggml-vulkan/ggml-vulkan-common.h index 4941d47a64ec..a3908b2bf074 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan-common.h +++ b/ggml/src/ggml-vulkan/ggml-vulkan-common.h @@ -34,7 +34,7 @@ bool ggml_vk_intel_windows_driver_in_range(uint32_t driver_version, uint32_t low // shaders void ggml_vk_destroy_pipeline(vk::Device& device, vk_pipeline& pipeline); -vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip = true); +vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, uint32_t n_kv_heads, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip = true); vk_fa_pipeline_state get_fa_pipeline_state(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool aligned, bool f32acc, bool use_mask, bool use_mask_opt, bool use_logit_softcap, bool use_sparse, bool use_kv_rows, ggml_type k_type, ggml_type v_type, uint32_t bias_bins, uint32_t gqa_tok); uint32_t get_subgroup_size(const std::string &pipeline_name, const vk_device_architecture &arch); void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested = nullptr); diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp index f0b5442b4f0c..bc9d80aac9d3 100644 --- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp +++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp @@ -1351,8 +1351,7 @@ static vk_fa_tuning_params get_fa_tuning_params_scalar(const vk_device& device, return result; } -static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip) { - GGML_UNUSED(n_kv); +static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, uint32_t n_kv_heads, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip) { vk_fa_tuning_params result{}; result.path = FA_COOPMAT1; @@ -1401,7 +1400,10 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat1(const vk_device& device hsk % 16 == 0 && hsv % 16 == 0 && hsk <= 256 && hsv <= 256 && k_type == v_type && (k_type == GGML_TYPE_F16 || k_type == GGML_TYPE_BF16)) { result.flip = true; - result.flip_direct = !device->uma && qk_ratio > 1 && device->vendor_id != VK_VENDOR_ID_NVIDIA; + // Direct loads re-read each K/V tile per subgroup, staged wins once K/V and workgroup drift outgrow the caches + const double kv_mib = (double)n_kv * n_kv_heads * (hsk + hsv) * ggml_type_size(k_type) / (1024.0 * 1024.0); + const bool kv_cached = kv_mib * std::sqrt((double)n_rows) < 6000.0; + result.flip_direct = !device->uma && qk_ratio > 1 && device->vendor_id != VK_VENDOR_ID_NVIDIA && kv_cached; if (force_flip != nullptr && strcmp(force_flip, "kvsep") == 0) { result.flip_direct = false; } else if (force_flip != nullptr && strcmp(force_flip, "direct") == 0) { @@ -1453,7 +1455,7 @@ static vk_fa_tuning_params get_fa_tuning_params_coopmat2(const vk_device& device return result; } -vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip) { +vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, uint32_t hsv, uint32_t n_rows, uint32_t n_kv, uint32_t n_kv_heads, ggml_type k_type, ggml_type v_type, bool f32acc, uint32_t qk_ratio, bool kv_rows, bool allow_flip) { FaCodePath path = device->coopmat2 ? FA_COOPMAT2 : device->coopmat1_fa_support ? FA_COOPMAT1 : FA_SCALAR; @@ -1472,11 +1474,11 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, if (path == FA_COOPMAT1) { bool shape_ok = (f32acc && device->coopmat_support_16x16x16_f32acc) || (!f32acc && device->coopmat_support_16x16x16_f16acc); - vk_fa_tuning_params params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip); + vk_fa_tuning_params params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, n_kv_heads, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip); bool shmem_ok = ggml_vk_flash_attn_coopmat_shmem_support(device, params, hsk, hsv, f32acc, k_type, v_type); if (!shmem_ok && params.flip) { allow_flip = false; - params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip); + params = get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, n_kv_heads, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip); shmem_ok = ggml_vk_flash_attn_coopmat_shmem_support(device, params, hsk, hsv, f32acc, k_type, v_type); } @@ -1494,7 +1496,7 @@ vk_fa_tuning_params get_fa_tuning_params(const vk_device& device, uint32_t hsk, case FA_SCALAR: return get_fa_tuning_params_scalar(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, kv_rows); case FA_COOPMAT1: - return get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip); + return get_fa_tuning_params_coopmat1(device, hsk, hsv, n_rows, n_kv, n_kv_heads, k_type, v_type, f32acc, qk_ratio, kv_rows, allow_flip); case FA_COOPMAT2: return get_fa_tuning_params_coopmat2(device, hsk, hsv, n_rows, n_kv, k_type, v_type, f32acc, kv_rows); default: @@ -9527,7 +9529,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const bool rows_compact = kv_rows && (xe_fa_rows_prefill || (neq1 >= 64 && (ctx->device->vendor_id == VK_VENDOR_ID_AMD || (ctx->device->vendor_id == VK_VENDOR_ID_NVIDIA && - get_fa_tuning_params(ctx->device, HSK, HSV, neq1, KV, k->type, v->type, f32acc, qk_ratio, kv_rows).path == FA_COOPMAT2)))); + get_fa_tuning_params(ctx->device, HSK, HSV, neq1, KV, nek2, k->type, v->type, f32acc, qk_ratio, kv_rows).path == FA_COOPMAT2)))); // gated to AMD, except RDNA4, which regressed in benchmarks const bool kv_raw_strided = (rows_compact && kv_raw && (HSK % 8) == 0 && (HSV % 8) == 0) || (ctx->device->vendor_id == VK_VENDOR_ID_AMD && @@ -9575,7 +9577,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const ggml_type v_type_eff = (use_dequant_kv && !kv_raw_strided) ? GGML_TYPE_F16 : v->type; // N=32 avoids the cm1 prefill block_rows doubling - vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 32, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows); + vk_fa_tuning_params tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, 32, KV, nek2, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows); const uint32_t max_gqa = std::min(tuning_params.block_rows, 32u); if (N <= 8 && qk_ratio > 1 && qk_ratio <= max_gqa && @@ -9588,7 +9590,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const workgroups_y /= gqa_ratio; } - tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows); + tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, nek2, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows); float scale = 1.0f; float max_bias = 0.0f; @@ -9635,7 +9637,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const bool fold_pays = true; if (tuning_params.path == FA_SCALAR) { // the scalar tile size depends on the row count, so size it for all folded rows - fold_params = get_fa_tuning_params(ctx->device, HSK, HSV, gqa_ratio * neq1, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows); + fold_params = get_fa_tuning_params(ctx->device, HSK, HSV, gqa_ratio * neq1, KV, nek2, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows); // scalar: fold if the unfolded dispatch gets no split_k (more tokens than rows), or if the fold adds no padded rows and each KV split keeps at least 16 blocks const uint32_t fold_tok = std::max(1u, fold_params.block_rows / gqa_ratio); const uint32_t fold_wgs = CEIL_DIV(neq1, fold_tok) * workgroups_y * workgroups_z; @@ -9701,7 +9703,7 @@ void ggml_vk_flash_attn(ggml_backend_vk_context * ctx, vk_context& subctx, const const bool kv_16b = use_dequant_kv || (((uintptr_t)k->data | (uintptr_t)v->data | nbk2_eff | nbk3_eff | nbv2_eff | nbv3_eff) % 16) == 0; if (!aligned || use_sparse || (use_kv_rows && tuning_params.flip_direct) || gqa_ratio != 1 || !kv_16b) { - tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows, false); + tuning_params = get_fa_tuning_params(ctx->device, HSK, HSV, N, KV, nek2, k_type_eff, v_type_eff, f32acc, qk_ratio, use_kv_rows, false); alignment = tuning_params.block_cols; aligned = fa_aligned(tuning_params); } diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp index e93f203bd8c3..6c9573ca11f9 100644 --- a/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp +++ b/ggml/src/ggml-vulkan/vulkan-shaders/flash_attn_cm1_flip.comp @@ -224,6 +224,15 @@ void fl_rescale(inout coopmat= 16) { + const uint32_t lin = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x; + i = lin / gl_NumWorkGroups.y; + iq2 = lin % gl_NumWorkGroups.y; + ik2 = iq2 / rk2; + iv2 = iq2 / rv2; + } + const uint32_t sg = gl_SubgroupID; const uint32_t lane = gl_SubgroupInvocationID; const uint32_t lr = lane / FL_LPR; From bf76a7d5035e0ceb9d1564994b458c65dc330f59 Mon Sep 17 00:00:00 2001 From: lichang Date: Fri, 4 Dec 2026 13:22:18 -0700 Subject: [PATCH 400/401] zonos3: use the channels-major convolution build_conv_state() returns the conv input as [channels, time, n_seqs] on gfx11, but zonos3 still called the time-major ggml_ssm_conv and aborted on GGML_ASSERT(sx->ne[1] == d_inner) when the graph was built. This is the same mismatch that was fixed for Clover; it predates this sync. Assisted-by: Claude Fable 5.2 --- src/models/zonos3.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/models/zonos3.cpp b/src/models/zonos3.cpp index dd0a88f321c1..a8e48d590f4b 100644 --- a/src/models/zonos3.cpp +++ b/src/models/zonos3.cpp @@ -275,7 +275,8 @@ ggml_tensor * llama_model_zonos3::graph::build_layer_gdn( ggml_tensor * state = build_rs(inp, ssm_states_all, hparams.n_embd_s(), n_seqs); state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs); - ggml_tensor * conv_out = ggml_silu(ctx0, ggml_ssm_conv(ctx0, conv_input, conv_kernel)); + // build_conv_state() returns the channels-major layout [channels, time, n_seqs] on this branch + ggml_tensor * conv_out = ggml_silu(ctx0, ggml_ssm_conv_channels_major(ctx0, conv_input, conv_kernel)); cb(conv_out, "conv_output_silu", il); const int64_t qkv_dim = head_k_dim * num_k_heads * 2 + head_v_dim * num_v_heads; From 28b9b4876f6471795889e7a6efdd07e0a0dcf61c Mon Sep 17 00:00:00 2001 From: lichang Date: Fri, 4 Dec 2026 15:45:10 -0700 Subject: [PATCH 401/401] qwen3next: keep the time-major conv state with -sm tensor build_conv_state() keeps the conv history channels-major on gfx11. For Qwen 3 Next that row then has two segment sizes per conv column (q/k and v heads), which the meta backend cannot carry through a reshape, so tensor split mode aborted in ggml-backend-meta.cpp. Upstream keeps this arch on the time-major layout for the same reason. Use the time-major layout only when the model runs with LLAMA_SPLIT_MODE_TENSOR. Every other mode keeps the channels-major convolution: on Qwen3-Next-80B-A3B a 3968-token prefill is 3.1% faster with it at ubatch 512 and 29.5% faster at ubatch 4096. A session state saved with -sm tensor uses the other conv history layout and is not interchangeable with one saved in another split mode. Assisted-by: Claude Fable 5.2 --- src/models/delta-net-base.cpp | 20 ++++++++++++++++++++ src/models/models.h | 5 +++++ src/models/qwen3next.cpp | 3 ++- 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/models/delta-net-base.cpp b/src/models/delta-net-base.cpp index b6743d105122..8104c55f4dc4 100644 --- a/src/models/delta-net-base.cpp +++ b/src/models/delta-net-base.cpp @@ -50,6 +50,10 @@ std::pair llm_build_delta_net_base::build_delta_ne return {output, new_state}; } +bool llm_build_delta_net_base::conv_state_channels_major() const { + return !(model.arch == LLM_ARCH_QWEN3NEXT && model.split_mode() == LLAMA_SPLIT_MODE_TENSOR); +} + ggml_tensor * llm_build_delta_net_base::build_conv_state( llm_graph_input_rs * inp, ggml_tensor * conv_states_all, @@ -67,6 +71,22 @@ ggml_tensor * llm_build_delta_net_base::build_conv_state( ggml_tensor * conv_states = build_rs(inp, conv_states_all, hparams.n_embd_r(), n_seqs); cb(conv_states, "conv_states", il); + if (!conv_state_channels_major()) { + // time-major layout of upstream: [time, conv_channels, n_seqs] + conv_states = ggml_reshape_3d(ctx0, conv_states, conv_kernel_size - 1, conv_channels, n_seqs); + cb(conv_states, "conv_states_reshaped", il); + + qkv_mixed = ggml_transpose(ctx0, qkv_mixed); + cb(qkv_mixed, "qkv_mixed_transposed", il); + + ggml_tensor * conv_input = ggml_concat(ctx0, conv_states, qkv_mixed, 0); + cb(conv_input, "conv_input", il); + + build_conv_state_store(inp, conv_states_all, conv_input, conv_kernel_size - 1, 0); + + return conv_input; + } + // channels-major layout: [conv_channels, time, n_seqs] (channels contiguous). // qkv_mixed already arrives channels-major as [conv_channels, n_tokens, n_seqs], // so no transpose is needed: we prepend the recurrent conv state along the time diff --git a/src/models/models.h b/src/models/models.h index 2bbfbe0bbe9c..32fbb4574de7 100644 --- a/src/models/models.h +++ b/src/models/models.h @@ -47,6 +47,11 @@ struct llm_build_delta_net_base : public llm_graph_context { // read conv state from cache, concat with qkv_mixed, write back (single slot or per-token) // qkv_mixed: (qkv_dim, n_seq_tokens, n_seqs); returns conv_input: (kernel_size + n_seq_tokens - 1, channels, n_seqs) + // gfx11: build_conv_state() returns the conv input channels-major, [channels, time, n_seqs], for ggml_ssm_conv_channels_major. + // The exception is Qwen 3 Next with -sm tensor: its q, k, v head pattern has two segment sizes per conv column, which the + // meta backend cannot carry through a reshape, so it keeps the time-major layout of upstream there. + bool conv_state_channels_major() const; + ggml_tensor * build_conv_state( llm_graph_input_rs * inp, ggml_tensor * conv_states_all, diff --git a/src/models/qwen3next.cpp b/src/models/qwen3next.cpp index c294f09e37c3..2bcb1e154c1f 100644 --- a/src/models/qwen3next.cpp +++ b/src/models/qwen3next.cpp @@ -455,7 +455,8 @@ ggml_tensor * llama_model_qwen3next::graph::build_layer_attn_linear( state = ggml_reshape_4d(ctx0, state, head_v_dim, head_v_dim, num_v_heads, n_seqs); cb(state, "state_predelta", il); - ggml_tensor * conv_output_proper = ggml_ssm_conv_channels_major(ctx0, conv_input, conv_kernel); + ggml_tensor * conv_output_proper = conv_state_channels_major() ? ggml_ssm_conv_channels_major(ctx0, conv_input, conv_kernel) + : ggml_ssm_conv(ctx0, conv_input, conv_kernel); cb(conv_output_proper, "conv_output_raw", il); ggml_tensor * conv_output_silu = ggml_silu(ctx0, conv_output_proper);